Skip to content

How a load balancer picks a server

Working knowledgeUnder the hood

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”.

What a balancer can see depends on its layer
LayerSeesPicks a server perExamples
Layer 4 (TCP)IP addresses and portsconnectionAWS NLB, Linux IPVS, HAProxy in TCP mode
Layer 7 (HTTP)paths, headers, cookiesrequestnginx, 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.

Round robin over three servers
Step 1 of 7
Servers in the pool
nextA
B
C
Requests, in arrival order
Empty
  • gets this request
  • just sent

Three servers sit in the pool. The balancer keeps one number: which server is next. It starts at A.

0 sent

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.

Least connections with one slow request
Step 1 of 10
Open connections per server
A · 0 open
B · 0 open
C · 0 open
What happened
Empty
  • 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.

fewest open wins rule
Round robinEqual countsGood when requests cost about the same. A slow request still gets new work stacked behind it.
Least connectionsEqual loadAdapts to slow requests and slow servers. Needs the balancer to track open connections.

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.

Active health checks take a server out and back
Step 1 of 8
Down after 3 failsUp after 2 passes
Probes and traffic (example timings)
ClientBalancerServer AServer BNothing sent yet
Pool as the balancer sees it
StatusFails in a rowPasses in a row
AUP0–
BUP0–
  • 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.

every 5 s probe

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.

Sticky sessions with a cookie
Step 1 of 7
Servers, and the sessions in their memory
A
B
C
Cookie each browser holds
Empty
  • 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.

nginx.conf
upstream app {
zone app 64k; # share round-robin state between workers
server a:80;
server b:80;
server c:80;
}
server {
listen 80;
location / {
proxy_pass http://app;
}
}
Shell
# three backends that answer "served by a", "served by b", "served by c",
# and nginx in front of them on port 8080 (a Docker network makes this easy)
for i in 1 2 3 4 5 6; do curl -s localhost:8080; done
docker stop b # kill one backend
for i in 1 2 3 4 5 6; do curl -s -w ' (%{time_total}s)\n' localhost:8080 | tr -d '\n'; echo; done
Text
served by a
served by b
served by c
served by a
served by b
served by c
served by a (0.000995s)
served by c (38.974130s)
served by c (0.003257s)
served by a (0.007898s)
served by c (0.002706s)
served by a (0.001632s)

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:

haproxy.cfg
backend app
balance leastconn
option httpchk GET /healthz
cookie SERVERID insert indirect nocache
server a 10.0.0.11:3000 check inter 5s fall 3 rise 2 cookie a
server b 10.0.0.12:3000 check inter 5s fall 3 rise 2 cookie b
server c 10.0.0.13:3000 check inter 5s fall 3 rise 2 cookie c

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.

08 Check yourself

Question

Three servers, round robin. Server A is stuck on a 30-second request. What happens to the next request it would be given?

Question

A balancer marks a server down after 3 failed probes, sent every 5 seconds. The server crashes just after a successful probe. Roughly how long can real requests still reach it?

Question

Login sessions live in each server’s memory, with cookie stickiness. You add a fourth server to cope with load. Which users does it serve?

09 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?