How a load balancer picks a server
You run three copies of your app behind one address, and requests somehow spread across them. Here is how a load balancer chooses a server for each request, how it notices one has died, and why some users keep landing on the same machine.
01 One address, many servers
Clients only know one address: the balancer’s. The balancer keeps a pool of backend servers. For each new connection or request it picks one server from the pool, forwards the traffic, and passes the reply back. The client never learns which server answered.
To pick well it has to answer two questions every time: which healthy server is next, and is each server still healthy. The rest of this page is those two answers, plus the case where the answer must be “the same one as last time”.
| Layer | Sees | Picks a server per | Examples |
|---|---|---|---|
| Layer 4 (TCP) | IP addresses and ports | connection | AWS NLB, Linux IPVS, HAProxy in TCP mode |
| Layer 7 (HTTP) | paths, headers, cookies | request | nginx, HAProxy in HTTP mode, AWS ALB, Envoy |
A layer 7 balancer ends the client’s connection and opens its own to the backend, so it can route /api and /images to different pools, add headers and read cookies. A layer 4 balancer only shuffles TCP connections, which is cheaper but blind to what is inside them.
02 Round robin: take turns
The simplest rule is to go down the list and wrap around. The balancer stores one thing, the index of the next server, and needs no information from the servers at all.
- gets this request
- just sent
Three servers sit in the pool. The balancer keeps one number: which server is next. It starts at A.
Round robin is fair by count, not by work. If one request is a 30-second report and the rest take 5 ms, the server holding the report still gets its turn every third request, and those requests queue behind it. Weighted round robin lets a bigger machine take more turns, but it still knows nothing about what each request costs.
03 Least connections: ask who is busy
A balancer can keep a count of the connections it has open to each server, because every one of them passes through it. Sending each new request to the server with the fewest open connections steers work away from a server that is stuck on something slow.
- request sent
- request finished
All three servers are idle, with no open connections. This time the balancer keeps a count per server and sends each request to the lowest one.
Other common rules: random of two picks two servers at random and takes the less busy one, which works well when several balancers each keep their own counts; hashing a key such as the client IP or URL always maps the same key to the same server, which is useful for caches.
04 Health checks: stop sending to a dead server
Any rule is useless if it keeps picking a server that has crashed. With active health checks, the balancer sends its own probe, typically an HTTP request to an endpoint such as /healthz, on a timer. A server leaves the pool after a number of failures in a row and comes back after a number of passes in a row. Both thresholds stop one slow reply from making a server flap in and out.
- just sent
- no reply, or down
- counter changed
- back in the pool
Both servers are in the pool. The settings: probe GET /healthz every 5 seconds, mark a server down after 3 failures in a row, and back up after 2 passes.
Passive checks watch real traffic instead: if connecting to a server fails, mark it bad for a while. Open-source nginx works this way (max_fails and fail_timeout on each server line). It needs no extra requests, but real users are the ones who discover the failure, as the run below shows.
Keep the health endpoint about this server. If /healthz also checks the shared database, one database blip fails every probe at once, the balancer marks every server down, and a short outage becomes a total one.
05 Sticky sessions: the same server every time
Some apps keep per-user state in a server’s memory, such as a login session or a shopping cart. Then the user must keep reaching the same server. A layer 7 balancer can do this with a cookie that names the server; a layer 4 one can hash the client’s IP address instead.
- just created
- cookie used
- gets the request
- down
Three servers. Each one keeps signed-in sessions in its own memory. No browser has a cookie from the balancer yet.
Stickiness also breaks the even spread: a user who stays for hours stays on one server, and a server added to the pool only gets new users. The sturdier fix is to keep sessions out of server memory, in a signed cookie or a shared store such as Redis, so any server can handle any request. Then stickiness is at most a cache-friendliness tweak, not something correctness depends on.
06 Watch nginx balance three servers
This is a real run: three nginx containers that each reply with their own name, and one more nginx in front with round robin, its default rule.
The first six requests rotate a, b, c. After b is stopped, nginx has only passive checks, so one unlucky request still tried b and hung for about 39 seconds before nginx gave up and retried it on c. After that, nginx skipped b for fail_timeout (10 seconds by default) before trying it again. A short proxy_connect_timeout, or active checks, shrinks that window.
Without the zone line, every request in this run went to a. Each nginx worker process kept its own round-robin counter, starting at the first server. Six fresh curl connections were spread over several workers, so each worker’s first pick was a. The zone directive puts the counter in memory shared by all workers.
HAProxy has active checks built in. The same pool with least connections, probes and a sticky cookie looks like this:
07 When it bites
one gRPC connectionLong connections defeat a layer 4 balancerA layer 4 balancer picks once per connection. A client that sends thousands of requests over one HTTP/2 or WebSocket connection sends all of them to one server. Balance at layer 7, per request.balance leastconn + new serverA new server gets floodedA server that just joined has 0 connections, so least connections sends it everything while its caches are cold. HAProxy’s slowstart ramps a new server’s share up over a set time.hash(client IP)Many users behind one IPEveryone behind a company NAT or a mobile carrier gateway shares an address, so IP stickiness can pile thousands of users onto one server.retry on 502Retries add load to a struggling poolRetrying a failed request on another server hides a crash, but when every server is overloaded, each retry adds work. Cap retries, and only retry requests that are safe to repeat.one balancerThe balancer is a server tooIf it dies, everything behind it is unreachable. Run at least two, with a floating IP or several DNS records, or use a managed balancer that does this for you.