Load Balancing & Discovery

Getting every request to a healthy instance: the algorithms that spread load, the layers that route it, and how services find each other.

LB algorithms L4 vs L7 Health checks Service registry API gateway
โš–๏ธ

Load Balancing Algorithms

Given a pool of healthy instances, the load balancer picks one per request. The algorithm choice matters when requests aren't uniform โ€” some are slow, some instances are bigger, some clients benefit from landing on the same node twice.

AlgorithmHow it worksBest for
Round robinNext instance in rotationUniform requests, equal instances
WeightedRound robin biased by capacityMixed instance sizes
Least connectionsFewest active connections winsLong-lived or uneven-duration requests
Least response timeFastest-responding instance winsLatency-sensitive, variable backends
IP / consistent hashHash the key to a stable instanceSession affinity, cache locality
๐Ÿ’ก
Round robin is the safe default. Reach for least connections when request durations vary a lot โ€” round robin can pile short and long requests unevenly. Reach for consistent hashing when landing on the same instance twice is valuable, like keeping a user's data in one node's local cache (Sharding).
๐Ÿง…

L4 vs L7

A load balancer can operate at two layers. L4 works at the transport level โ€” it sees IPs and ports, forwards packets, and never opens the payload. L7 works at the application level โ€” it terminates the connection, reads the HTTP request, and can route on path, header, or cookie.

  L4 (transport)                        L7 (application)
  sees: IP : port                       sees: full HTTP request
  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”                      โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
  โ”‚  forward the โ”‚  โ”€โ”€โ–ถ backend         โ”‚  GET /api/*  โ”€โ”€โ–ถ api pool  โ”‚
  โ”‚  TCP packets โ”‚      (blind to        โ”‚  GET /img/*  โ”€โ”€โ–ถ cdn pool  โ”‚
  โ”‚  fast, cheap โ”‚       content)        โ”‚  header: beta โ”€โ”€โ–ถ canary   โ”‚
  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜                      โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
   can't route by URL,                   routing, TLS termination,
   can't retry a request                 retries, rewrites โ€” at a cost
L4L7
SeesIP, port, TCPFull HTTP: path, headers, cookies
Can doFast forwarding, any protocolPath routing, TLS termination, retries, rewrites
CostMinimal overheadTerminates and parses โ€” more CPU
Use whenRaw throughput, non-HTTP trafficSmart routing on HTTP semantics
โ„น๏ธ
Most web systems use L7 at the edge because routing by path and terminating TLS there is worth the CPU (Networking Basics). L4 shows up where you need raw speed or non-HTTP protocols, or as a first hop in front of an L7 tier.
๐Ÿฉบ

Health Checks

The balancer only routes to instances it believes are healthy, so it constantly probes them. Active checks send a periodic request and watch for a good response. Passive checks infer health from real traffic โ€” a burst of errors or timeouts marks an instance down without a separate probe.

Checks also vary in depth. A shallow check confirms the process is up ("return 200 on /health"). A deep check verifies dependencies too โ€” can it reach the database, the cache, the downstream service.

โš ๏ธ
Deep health checks are a double-edged tool. If every instance's health check pings a shared database and that database hiccups, every instance reports unhealthy at once โ€” and the balancer takes the entire fleet out of rotation over a blip. A shared dependency failing should degrade service, not vanish the whole pool. Keep the check shallow, or fail it only on sustained, local problems (Resilience Patterns).
๐Ÿ›ฐ

Service Discovery

In a dynamic fleet, instances start, stop, crash, and autoscale constantly. Nobody can hard-code addresses. A service registry is the live directory: instances register on startup and send heartbeats; they deregister on shutdown, or the registry evicts them when heartbeats stop. Callers ask the registry where a service lives.

Client-side discovery caller picks

The client queries the registry, gets the list of instances, and load-balances itself. Fewer hops and full control, but every client needs the discovery logic and a fresh view of the registry.

Server-side discovery balancer picks

The client just calls a stable load balancer, which consults the registry and forwards. Clients stay dumb; the routing tier owns discovery. One more hop, one more thing to run.

โš ๏ธ
The registry can be stale in both directions. It may still list an instance that just died (calls fail until it's evicted) or not yet list one that just started (traffic misses it). Short heartbeat intervals and retries on the caller side paper over the gap. The registry itself needs strong consistency for membership, which is why it's usually built on a consensus store (Consensus).
๐Ÿšช

API Gateway

An API gateway is the single front door to a system of services. It handles the cross-cutting edge concerns you don't want scattered across every service: authentication, rate limiting, routing, request shaping, and response aggregation. One place to enforce policy, one place clients target.

   clients
      โ”‚
      โ–ผ
  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
  โ”‚            API GATEWAY                    โ”‚
  โ”‚  authn ยท rate limit ยท routing ยท shaping   โ”‚
  โ””โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
      โ–ผ           โ–ผ           โ–ผ
   user svc    order svc    search svc     (internal services stay focused
                                            on business logic, not edge policy)

The terms blur on purpose. A reverse proxy forwards requests to backends. A load balancer spreads them across instances. An API gateway adds application-aware policy on top. In practice one component often does all three, which is why the words get used interchangeably โ€” the distinction is the responsibility, not the box (Security Basics, Rate Limiter).

๐ŸŒ

Global Load Balancing

Everything above balances within one region. Across regions, two mechanisms send a user to the right one. GeoDNS answers a DNS query with the nearest region's address based on the resolver's location. Anycast advertises one IP from many locations, and the network routes packets to the closest โ€” routing at the network layer, so it reacts faster than DNS and needs no TTL wait.

โ„น๏ธ
GeoDNS is simple but coarse and slow to fail over โ€” it sees the resolver, not the user, and is bound by TTLs (Networking Basics). Anycast is more precise and reroutes near-instantly when a location goes dark, which is why CDNs and DNS providers run on it. Getting the user to the right region is only half the job; what happens to their data across regions is a separate, harder problem (Multi-Region).
๐Ÿ“‹

Quick Reference

AlgorithmHow it worksBest for
Round robinRotate through instancesUniform requests โ€” the default
WeightedBiased by capacityMixed instance sizes
Least connectionsFewest active winsVariable request durations
Least response timeFastest winsLatency-sensitive backends
Consistent hashKey โ†’ stable instanceSession affinity, cache locality
L4L7
SeesIP, portFull HTTP
Can doFast forwardingPath routing, TLS term, retries
Use whenThroughput, any protocolSmart HTTP routing
โ„น๏ธ
The one-liners to keep ready. Round robin by default; least-connections for uneven requests; consistent hash for affinity. L7 at the edge for routing and TLS, L4 for raw speed. Keep health checks shallow so a shared dependency doesn't take the whole fleet down. A registry with heartbeats handles a fleet that's always changing, and it's stale in both directions โ€” retry. Gateway, load balancer, and reverse proxy are three responsibilities that often live in one box.