Load Balancing

Eight servers run at 90% busy. Send each request to a random server, and the slowest 1 in 100 takes about 480 ms. Send it to the less busy of two random servers, and that drops to about 110 ms.

Pick a way to choose the server and watch the queues. Then push the load up and compare the slowest requests. Then we build, piece by piece, why queues explode near full, DNS, L4 and L7 balancers, the algorithms, hashing, health checks and global routing.

You need what a TCP connection is and what an HTTP request is. Network Foundations helps. We build the rest from zero.

Choose a server for each request

90%

Simulated in your browser: 8 equal servers, random arrivals, 10 ms of work per request on average (exponential), 400,000 requests per method with one fixed seed. The animation runs the same rules slowed down. Chapters 0, 4 and 5 work each number.

Chapter 0

One Line or Ten Lines

Add servers, then see why the way you split the traffic decides the wait

Traffic jumps to 10,000 requests a second, and one server handles 1,000. You start ten copies, but every client still sends to the first one. It drowns while nine sit idle.

You need a load balancer: a box in front of the servers that picks a server for each request. How it picks decides how long requests wait in each server's queue.

How busy is the pool? Call the requests arriving each second λ, the number of servers c, and the requests one server finishes each second μ.

Say it aloud

Rho equals lambda divided by c times mu.

ρ
rho the utilisation: the share of time a server is busy. It must stay below 1.
λ
lambda the arrival rate: 900 requests a second here.
c
c the number of servers: 10 here.
μ
mu the service rate of one server: 100 requests a second, so 10 ms each on average.
In plain words

Multiply the servers c by what one server finishes, mu. That is the pool's capacity. Divide the arrivals lambda by it. The result rho is how busy each server is.

With numbers

With made-up numbers: λ = 900, c = 10, μ = 100. ρ = 900 / (10 × 100) = 0.9. Each server is busy 90% of the time.

Random arrivals bunch up, so requests wait even at 90%. If all ten servers share one line, a request waits only when all ten are busy. The chance of that is the Erlang C probability, C. Call the mean wait in the line Wq.

Say it aloud

W-q equals C divided by, c-mu minus lambda.

Wq
W-q the mean time a request waits in the line before a server starts on it.
C
C the Erlang C probability: the chance an arriving request finds all c servers busy.
cμ
c-mu the capacity of the pool: 1,000 requests a second here.
λ
lambda the arrival rate. cμ − λ is the spare capacity that drains the line.
In plain words

Find the spare capacity, c-mu minus lambda. Take the chance C that a request must wait at all. Divide C by the spare capacity. As lambda nears c-mu, the spare capacity goes to zero and the wait explodes.

With numbers

c = 10, λ = 900, μ = 100: C = 0.669, so Wq = 0.669 / (1,000 − 900) s = 6.7 ms. Now split the same traffic at random into ten separate lines. Each server is its own one-server queue at ρ = 0.9, and its wait is ρ / (μ − λ/c) = 0.9 / 10 s = 90 ms. The same servers wait 13 times longer.

Where C comes from

Call the offered load a = λ / μ: the servers busy on average, 9 here. C weighs "all c busy" against every count of busy servers:

C = [ ac/c! · c/(c − a) ] / [ Σk=0..c−1 ak/k! + ac/c! · c/(c − a) ] a = 9, c = 10: C = 0.669

With c = 1, C = ρ and this becomes the one-server formula, ρ / (μ − λ).

Wait in one line or in many

The yellow curves are the mean wait against how busy the pool is. Solid: one shared line. Dashed: each server its own line, picked at random. Drag the load and the server count.

90%
10

Exact M/M/c formulas: random arrivals, exponential service with a 10 ms mean. The slowest-1-in-100 wait uses P(wait > t) = C · e−(cμ − λ)t. Real traffic is burstier, so real waits are longer.

A real balancer must send each request to a server at once, so it cannot keep one shared line. Its algorithm decides how close it gets. Chapters 4 and 5 close most of the gap.

Failure. Symptom: p99 latency triples while average CPU reads 85%. Measure: utilisation per server. Cause: near full, a small rise in load grows the queue fast. Fix: keep headroom, and pick servers by their queues.

  1. DNS: several addresses for one name, and answers that stay in caches.
  2. L4: forward packets by their addresses, and send replies around the balancer.
  3. L7: read each request, route by its path, and pay for it in CPU.
  4. Algorithms: round robin, weights and least connections on unequal servers.
  5. Two choices: why asking two random servers beats asking one.
  6. Hashing: keep a key on one server, with Maglev's lookup table.
  7. Health: find a dead server by probes and by errors.
  8. Global: GeoDNS, anycast and the speed of light.
  9. Showcase: a balancer you can slow down and break.
  10. The field guide: numbers, choices, code and links.
Ten servers run at 90% busy. Why does a random split wait far longer than one shared line?

Chapter 1

Answers That Stay in Caches

Give one name several addresses, then watch a dead address linger for a whole TTL

The cheapest balancer is one you already have. DNS turns a name into addresses. Publish three A records for api.example.com, one per server, and many DNS servers rotate their order on each answer. Clients usually try the first address. This is DNS round robin.

dnsapi.example.com.  300  IN  A  10.0.1.1
api.example.com.  300  IN  A  10.0.1.2
api.example.com.  300  IN  A  10.0.1.3

The 300 is the TTL (time to live), in seconds. A recursive resolver, the DNS server of an ISP or an office, keeps the answer for that long and gives it to every client behind it. You do not control the order the clients finally use. Resolvers may rotate their cached copy, and clients may sort the list (RFC 6724 defines one sort order).

The real cost shows when a server dies. You remove its record, but every resolver that cached the old answer keeps handing it out until its copy expires. Call the time since you removed the record t.

Say it aloud

Stale of t equals the larger of zero, and one minus t over TTL.

stale(t)
stale of t the share of resolvers that still hand out the removed address, t seconds after the change.
max
the larger of the share never goes below zero.
t
t seconds since you removed the record.
TTL
T-T-L the time to live on the record: 300 seconds here.
In plain words

Each resolver cached the answer at some random moment in the last TTL seconds. After t seconds, the ones that cached it in the last TTL minus t seconds still hold it. That share falls in a straight line from 1 to 0 over one TTL.

With numbers

TTL = 300 s. After 60 s, 1 − 60/300 = 80% of resolvers still send clients to the dead server. On average the stale share is one half over 300 s. With 3,000 requests a second meant for that server, about 3,000 × 150 = 450,000 requests try it before the caches drain.

Remove a server from DNS

Each small box is a resolver and the address it has cached. Crash server C: red boxes still send clients to it. The chart below counts them over time. Change the TTL and run it again.

Illustrative: 48 resolvers that honour the TTL, each cached at a random moment, 3,000 requests a second meant for C. The clock runs fast. Some clients keep their own caches and retry other addresses; this toy ignores both.

A lower TTL drains faster but sends more queries to your DNS servers. DNS also cannot see load or health. So it works as the coarse first layer: it picks a region or a balancer address.

Failure. Symptom: errors continue for minutes after you pull a dead server from DNS. Measure: requests still arriving at the old address, against the record's TTL. Cause: resolvers and clients serve the cached answer until it expires. Fix: put a balancer address in DNS, not server addresses, and keep TTLs short on records you may change.

You remove a dead server's A record. The TTL is 300 s. Two minutes later, about what share of resolvers still hand it out?

Chapter 2

Forward Packets, Not Requests

Pick a server from the packet's addresses, then send the big replies around the balancer

An L4 balancer works at the transport layer. It reads each packet's protocol, source and destination address and port: the 5-tuple. It never reads the HTTP inside. On a connection's first packet it picks a server. It writes the choice into a connection table, so later packets of that connection follow.

It can deliver the packets in three ways.

  1. NAT. It rewrites the destination to the server's address. Replies must come back through it so it can rewrite them again.
  2. Direct server return (DSR). It forwards the packet but the server replies straight to the client. The server must accept traffic for the balancer's address.
  3. Tunnelling. It wraps the packet in another IP packet, so the server can sit on another network, and the server replies directly too.

Linux IPVS offers all three. Google's Maglev wraps packets in GRE and uses DSR; Facebook's Katran wraps them in IP-in-IP and also uses DSR.

Why skip the return path? Replies are often much larger than requests. Call the request rate r, the request size q and the reply size s. The balancer's traffic under NAT is BNAT.

Say it aloud

B-NAT equals r times, q plus s.

BNAT
B-NAT bytes per second through the balancer in NAT mode. Under DSR the s term drops out: r · q.
r
r requests per second: 10,000 here.
q
q bytes in one request: 2 KB here.
s
s bytes in one reply: 200 KB here.
In plain words

Under NAT, each request q goes in and each reply s comes back through the balancer. Add them and multiply by the rate r. Under DSR only the requests pass through.

With numbers

With made-up numbers: 10,000 × (2 KB + 200 KB) = 2.02 GB/s, or 16.2 Gbit/s, more than a 10 Gbit/s link. Under DSR: 10,000 × 2 KB = 20 MB/s, or 0.16 Gbit/s, 101 times less.

Route the replies

Blue packets are requests; teal ones are replies. The bar is the balancer's link against 10 Gbit/s. Pick a mode, then drag the reply size.

200 KB

Illustrative: 10,000 requests a second of 2 KB each, decimal units (1 KB = 1,000 bytes), headers ignored, one 10 Gbit/s link on the balancer.

The connection table is the L4 balancer's memory: one entry per live connection. If that balancer restarts, or traffic shifts to another balancer, the entries are gone. Chapter 6 shows how a hash lets a second balancer make the same choice without the table.

Failure. Symptom: the balancer's network card saturates while the servers idle. Measure: bytes out of the balancer against bytes in. Cause: NAT mode carries every reply. Fix: DSR or tunnelling, so replies skip the balancer.

An L4 balancer in NAT mode serves 5 MB replies and its link is full. What helps most?

Chapter 3

Read the Request, Pay for It

Terminate the connection, route each request by its path, and count the CPU it costs

Some choices need the request itself. Send /api/v2 to a new fleet. Send /static to a file pool. Keep a user's cookie on one server. An L4 balancer cannot see any of this, because a path is inside the encrypted HTTP.

An L7 balancer is a reverse proxy. It accepts the client's TCP connection, and usually the TLS session too. It decrypts and parses each request, picks a server, and sends the request over a second connection that it keeps open to that server. NGINX, HAProxy, Envoy and AWS's Application Load Balancer work this way.

TLS termination means the balancer holds the certificate and does the handshakes. Servers spend their CPU on the app, and you renew one certificate. The proxy can re-encrypt to the servers if the internal network is not trusted.

The proxy pays for this in CPU. Call the request rate r and the share of requests that start a new TLS connection f. Call the CPU time of one handshake ths, and the CPU time to parse and route one request treq.

Say it aloud

Cores equals r times, f times t-h-s, plus t-req.

cores
cores CPU cores kept busy: CPU-seconds needed per second.
r
r requests per second: 20,000 here.
f
f the share of requests that open a new TLS connection. Kept-alive connections make it small.
ths
t-h-s CPU time of one full handshake: 1 ms, illustrative.
treq
t-req CPU time to decrypt, parse and route one request: 50 µs, illustrative.
In plain words

Each request costs t-req. A share f of them also pays a handshake t-h-s. Add the two costs per request and multiply by the rate r. The answer is how many cores the proxy needs.

With numbers

With made-up costs: 20,000 × (0.1 × 1 ms + 50 µs) = 20,000 × 0.15 ms = 3 cores. If every request opens a new connection (f = 1): 21 cores. An L4 balancer that spends about 1 µs on each of 6 packets per request needs 0.12 cores.

Route by path

Blue requests carry a path. The proxy reads it and sends each to its pool. The bars compare the CPU cores an L7 proxy and an L4 balancer need. Drag the share of new connections.

10%

Illustrative costs, not measurements: 20,000 requests a second, 1 ms of CPU per full handshake, 50 µs per request, 6 packets per request at 1 µs each for L4. Measure your own proxy before you size it.

Most large sites stack both. An L4 layer spreads connections over many L7 proxies, and the proxies route requests. Google's Maglev paper describes Maglev forwarding to service endpoints such as its front-end proxies. On AWS, a Network Load Balancer can send traffic to an Application Load Balancer.

Failure. Symptom: proxy CPU spikes each time a deploy restarts clients, though request rate is flat. Measure: new TLS connections per second. Cause: every client reconnects at once, so f jumps toward 1. Fix: session resumption, more proxy headroom, and staggered client restarts.

You want /api/v2 on a canary fleet and /api/v1 on the old one, on the same address and port. Which balancer can do it?

Chapter 4

Pick the Next Server

Compare round robin, weights and least connections on servers of different speeds

The balancer now sees four servers: A has 8 cores, B has 4, and C and D have 2 each. A request arrives. Which server gets it?

Round robin takes them in turn: A, B, C, D, A, B. It needs only a counter. Each server gets a quarter of the traffic, so the small servers get as much as the big one. At 80% of the pool's total capacity, C and D receive 160% of what they can serve, and their queues grow without limit. Random picking has the same problem.

Weighted round robin gives each server a weight in proportion to its capacity: 4, 2, 1, 1. Server i gets a share wi / Σw of the requests: A gets 4/8 = 50%. NGINX spreads the turns out with its smooth weighted round robin. On each request it adds every server's weight to a running score, picks the highest score, and subtracts the total weight from the winner.

weights A 4, B 2, C 1, D 1 (total 8) scores after adding: A 4 B 2 C 1 D 1 → pick A, A becomes 4 − 8 = −4 next: A 0 B 4 C 2 D 2 → pick B, B becomes −4 eight picks: A B A C D A B A (A 4, B 2, C 1, D 1)

Weights are fixed numbers. They miss a server that slows down: a noisy neighbour, a long garbage collection, a cold cache. Least connections sends each request to the server with the fewest requests in flight. A fast server finishes sooner, so its count drops and it gets more. Weighted least connections divides the count by the weight.

Spread over unequal servers

Each orange box is a server, sized by its cores. The bar is its utilisation against 100%; red means it gets more than it can serve. Pick an algorithm, then drag the load.

80%

Simulated: speeds 4, 2, 1, 1 (a speed-1 server takes 10 ms per request on average), random arrivals, 100,000 requests, one fixed seed. Utilisation is each server's share of requests times the load, over its speed.

The worked number at 80% load. Weighted round robin gives a mean of 16.7 ms, and the slowest 1 in 100 takes 96 ms. Least connections, with no weights, gives 11.8 ms and 71 ms, because it reacts to the queues. Weighted least connections gives 10.4 ms and 44 ms.

Failure. Symptom: after you add bigger servers, the old small ones time out. Measure: utilisation per server, not the pool average. Cause: round robin sends equal shares to unequal servers. Fix: weights in proportion to capacity, or least connections.

Servers with 8, 4 and 2 cores get weights 4, 2 and 1. What share does the 8-core server get under weighted round robin?

Chapter 5

The Power of Two Choices

Ask two random servers instead of one, and watch the time in the system fall nearly four times

Least connections needs every server's count, on every request. A large fleet often has many balancers, each with its own slightly old view. If they all chase the same least-loaded server, they pile onto it together.

The power of two choices asks less. Pick two servers at random. Send the request to the one with fewer requests in flight. Mitzenmacher (2001) analysed this as the supermarket model: n servers, random arrivals at rate λn, and service times averaging 1. Each request samples d servers and joins the shortest queue. Call the mean time a request spends in the system Td.

Say it aloud

T-d equals the sum over i from one up, of lambda to the power, d to the i minus d, over d minus one.

Td
T-d the mean time in the system, waiting plus service, in units of one mean service time, as n grows large.
Σi≥1
the sum over i from one up one term for i = 1, 2, 3 and so on. The terms shrink fast.
λ
lambda the utilisation of each server, below 1: 0.9 here.
(di − d)/(d − 1)
d to the i minus d, over d minus one the power. For d = 2 it is 2i − 2: 0, 2, 6, 14, 30. It grows exponentially, so the terms vanish.
In plain words

For each i, raise lambda to the power d-to-the-i minus d, over d minus one. Add the terms. With one choice, d = 1, the sum is 1 / (1 − lambda), the one-server queue. With two choices the powers double each step, so only a few terms count.

With numbers

λ = 0.9, d = 2: 0.90 + 0.92 + 0.96 + 0.914 + 0.930 = 1 + 0.81 + 0.531 + 0.229 + 0.042 = 2.61. With one choice: 1 / (1 − 0.9) = 10. Two samples cut the time 3.8 times. Three samples give 2.03, a smaller gain.

Sample d servers

Yellow curves are the formula for d = 1, 2 and 3. Pick d and the load, then run 100 servers: the blue dot is the simulated result.

0.90

Formula: Mitzenmacher 2001, Theorem 1, the limit of many servers. Simulation: 100 servers, 60,000 requests, d samples without repeats, exponential service. "All" is least connections and has no simple closed form.

The simulation agrees: at λ = 0.9 on 100 servers it gives about 2.67 for two choices, against the formula's 2.61. Envoy's least-request balancer samples 2 hosts by default. NGINX offers random two least_conn, and HAProxy offers balance random(2).

Failure. Symptom: a new server joins, every balancer floods it at once, and it times out. Measure: requests sent to it in its first seconds. Cause: every balancer sees it as least loaded and sends to it together. Fix: two random choices, plus a slow start that ramps its weight.

At 90% load, the formula gives 10 for one random choice. What does it give for two?

Chapter 6

Keep a Key on One Server

Hash each connection or user to a server, and move few of them when a server leaves

Sometimes a client must reach the same server each time. An L4 balancer must keep a connection's packets together, even on a balancer machine that never saw the connection. This is affinity.

The tool is a hash. Hash the connection's 5-tuple, or the user ID, to pick the server. Every balancer computes the same answer with no shared table. Hash mod N fails: removing one of 100 servers moves 98.9% of keys in our check. Consistent hashing moves only the keys of the server that left (see Partitioning for the ring).

Maglev (Eisenbud and others, NSDI 2016) uses a lookup table of M entries, with M prime. Each backend gets its own preference order over the entries. The backends take turns, each claiming its favourite entry that is still empty. To build backend i's order, hash its name twice to get an offset and a skip.

Say it aloud

Perm of j equals offset plus j times skip, mod M.

perm[j]
perm of j the backend's j-th choice of table entry.
offset
offset its first choice: one hash of its name, mod M.
j
j the step in its list: 0, 1, 2 and so on.
skip
skip its stride: another hash, mod (M − 1), plus 1. It is never 0.
mod M
mod M wrap around the table of M entries. Because M is prime, any skip visits every entry once.
In plain words

Start at the offset. Step forward by skip each time, wrapping at M. The list of entries you land on is the backend's preference order. A packet's hash, mod M, picks an entry, and the entry names the backend.

With numbers

The paper's example: M = 7 and backend B1 has offset 3, skip 4. Its order is 3, 0, 4, 1, 5, 2, 6: for j = 2, (3 + 2 × 4) mod 7 = 11 mod 7 = 4. With M = 65,537 and 100 backends, each gets 655 or 656 entries.

Fill the lookup table

Each purple row is a backend's preference order. The cells below are the lookup table. Press Fill to watch the turns, then remove B2: blue cells changed owner.

The M = 7 rows use the offsets and skips of the paper's Table 1. The M = 13 rows and the 65,537-entry count use our own 32-bit hash of each backend name, computed in your browser.

Maglev trades a little disruption for balance. Removing one of 100 backends changes 1.56% of entries in our check: the 1.0% it owned plus 0.56% elsewhere. A connection table keeps live connections on their backend through such changes.

An L7 balancer can also pin a user with a cookie that names the server (sticky sessions). Pinning by source IP is cruder: thousands of users behind one NAT share an IP. Better still, keep session state in a shared store, so any server can serve any user.

Failure. Symptom: you remove one server and cache hit rates drop on every server. Measure: keys that changed server after the change. Cause: hash mod N remapped almost every key. Fix: consistent hashing or a Maglev table.

Why must M be prime in Maglev's lookup table?

Chapter 7

Find the Dead Server

Probe on a timer, or watch real requests fail, and count the requests lost while you wait

Server 3 of 10 crashes. The balancer does not know, so it keeps sending it a tenth of the traffic, and those requests fail.

An active health check is a probe on a timer: open a TCP connection, or send GET /health and expect a 200. One miss could be a blip, so the balancer waits for k misses in a row, the unhealthy threshold. Call the probe interval I, the threshold k, and the probe timeout T.

Say it aloud

T-detect is at most k times I, plus T.

tdetect
t-detect the time from the crash until the balancer stops sending to the server.
≤
is at most the worst case: the crash comes just after a passed probe.
k
k misses in a row before the balancer marks the server down: 3 here.
I
I seconds between probes: 10 here.
T
T the probe timeout: a probe to a silent host fails only after 5 seconds.
In plain words

In the worst case the server dies just after a probe passes. The next k probes each miss, I seconds apart, and the last one waits T before it counts as a miss. If the host refuses connections instead of staying silent, drop the T.

With numbers

I = 10 s, k = 3, T = 5 s: at most 3 × 10 + 5 = 35 s, at least 25 s, 30 s on average. At 100 requests a second to that server, about 3,000 requests fail. AWS's Application Load Balancer defaults (I = 30 s, k = 2, T = 5 s) give up to 65 s.

Time the ejection

The line is time. Each tick is a probe: teal passed, red missed, and the yellow line is its 5 s timeout. The red band is requests sent to a dead server. Move the crash, try the presets, then turn on passive ejection.

12 s

Probe timeout 5 s, a silent host, 100 requests a second to the dead server. Passive ejection follows Envoy's default of 5 consecutive errors; it needs live traffic to notice. Probes start at time 0 for clarity.

Passive health checking, or outlier ejection, watches real responses. Envoy ejects a host after 5 consecutive 5xx errors by default, for 30 s at first and longer each time it repeats. At 100 requests a second, 5 errors take 50 ms, not 30 s. Envoy also caps ejection at 10% of hosts by default, so a bad deploy cannot empty the pool.

Two more rules. A readiness probe asks "can you take traffic now?" and a failure removes the server from the pool. A liveness probe asks "should we restart you?" Put database checks in readiness only: a database outage that fails liveness restarts every server. To retire a server, drain it: stop new requests, let the open ones finish, then remove it.

Failure. Symptom: one server returns errors to 5% of requests, and every probe passes. Measure: error rate per server from real traffic. Cause: /health tests the process, not the path that fails. Fix: outlier ejection on real responses, and a readiness check that covers the dependency.

Probes every 10 s, 3 misses to mark down, a 5 s timeout on a silent host. What is the worst-case detection time?

Chapter 8

Pick the Data Centre

Send each user to a near site with GeoDNS or anycast, then fail a site and compare

You run sites in Virginia, Frankfurt and Tokyo. A user in Seoul who reaches Virginia pays for distance on every round trip. No algorithm can beat the speed of light. Call the distance between client and site d and the speed of light in fibre v.

Say it aloud

R-T-T-min equals two d over v.

RTTmin
R-T-T-min the shortest possible round trip, there and back.
2
two the signal goes out and comes back.
d
d the great-circle distance in km. Real cables run longer.
v
v light in glass: about 200,000 km per second, two thirds of its speed in a vacuum.
In plain words

Double the distance d. Divide by the speed v. No route is faster, and real routes add detours and queues on top.

With numbers

Tokyo to Ashburn, Virginia: d = 10,872 km, so RTTmin = 2 × 10,872 / 200,000 s = 109 ms. A page that needs 5 round trips waits over half a second for distance alone.

GeoDNS answers each DNS query with the address of a near site, judged by the resolver's IP. It shares DNS's weakness from Chapter 1: when a site fails, cached answers keep sending users there until their TTL runs out. Anycast gives every site the same address and lets each announce it in BGP, the internet's routing protocol. Routers deliver each packet to a nearby announcer. When a site withdraws its route, packets flow to the next site once routes converge, with no DNS change.

Fail a site

Orange squares are sites; blue lines carry each city's traffic, labelled with the shortest round trip. Pick a method, then fail Tokyo: red lines are traffic sent to a dead site.

Schematic map from real coordinates; round trips use 2d / 200,000 km/s. Recovery times are illustrative: a 60 s TTL for GeoDNS, and 20 s for BGP to converge. Each city goes to its nearest working site.

Anycast has a catch for long connections. If routes change mid-connection, packets can reach a site that never saw the connection, and TCP breaks. RFC 4786 notes that anycast suits short exchanges, like DNS over UDP, best. The DNS root servers use anycast. Many large sites combine the two: DNS or anycast picks the site, then L4 and L7 balance inside it.

Failure. Symptom: Asian users see errors for a minute after the Tokyo site fails, though Frankfurt is healthy. Measure: requests still arriving at Tokyo's address. Cause: GeoDNS answers stay cached for their TTL. Fix: a short TTL with health-checked answers, or anycast.

The Tokyo site fails. With anycast, what happens to new connections from Japan?

Chapter 9

A Balancer You Can Break

Choose the algorithm, slow one server, crash another, and read the latency and the errors

Six servers behind one balancer, with every knob from Chapters 4, 5 and 7. Requests arrive at random. Probes check each server every 150 ms, sped up so you can watch. The read-out counts the last 500 finished requests.

Run the balancer

Blue dots are requests on their way; pink dots wait in a queue. A red server is dead; a grey one is out of the pool. Change anything and watch the slowest requests.

75%

Simulated live in your browser: 6 servers, 10 ms of work per request on average, probes every 150 ms with 2 misses to mark down and a 30 ms timeout, passive ejection after 5 errors in a row. Load is a share of six full-speed servers' capacity. Numbers move with each run.

Things to try:

  1. Round robin at 75%, then slow server 3. Its queue grows and the slowest requests jump, because it still gets a sixth of the traffic at a quarter of the speed.
  2. Switch to two choices or least connections. The slow server's queue stays short: requests go around it.
  3. Crash server 5. Red errors appear until two probes miss. Then turn on passive ejection and crash it again: the errors stop after about 5.
  4. Push the load to 95% under random. Queues grow long even with all servers healthy.

The worked number at 75% load, with server 3 at a quarter speed. Round robin gives it a sixth of the traffic: 0.75 × 6 / 6 / 0.25 = 300% of what it can serve. Its queue never stops growing. Least connections sends it only what it can finish.

Failure. Symptom: p99 latency climbs, every server passes health checks, and averages look fine. Measure: queue length or in-flight requests per server. Cause: one slow server still gets its fixed share. Fix: a load-aware algorithm (least connections or two choices) and outlier ejection on latency or errors.

One server becomes 4 times slower but stays healthy. Which algorithm keeps the p99 low?

Chapter 10

The Field Guide

Keep the numbers, the choices and the code for the next pool you put behind a balancer

Queues explode near full, and how you spread requests decides how close you get to one shared line. DNS picks a region and keeps old answers for a TTL. L4 forwards connections fast and can send replies around itself. L7 reads each request and pays for it in CPU.

Inside a pool, weights handle unequal servers, and least connections or two random choices handle servers that slow down. Hashing keeps a key on one server and Maglev keeps the table even. Health checks find dead servers in tens of seconds; outlier ejection on real errors finds them in a few requests.

Terms and numbers

TermWhat it isThis lesson's number
Utilisationρ = λ / (cμ)900 / (10 × 100) = 0.9
Erlang C waitWq = C / (cμ − λ)shared line 6.7 ms; random split 90 ms
DNS stalenessstale(t) = max(0, 1 − t / TTL)TTL 300 s: 80% stale after 60 s
NAT trafficBNAT = r(q + s); DSR r · q16.2 against 0.16 Gbit/s
L7 CPUcores = r(f · ths + treq)illustrative: 3 cores at f = 10%
Weighted sharewi / Σw4, 2, 1: the big server gets 57%
Two choicesTd = Σ λ(di − d)/(d − 1)λ 0.9: 10 for d = 1, 2.61 for d = 2
Maglev tableperm[j] = (offset + j · skip) mod MM 65,537, 100 backends: 655 or 656 each
Detection timetdetect ≤ kI + T10 s × 3 + 5 s: 35 s
Round trip floorRTTmin = 2d / vTokyo to Virginia: 109 ms

Which balancer for which job

JobLayer and methodExamples
Pick a regionGeoDNS or anycastRoute 53 geolocation, the DNS root servers
Spread connections fastL4 with a hash table and DSRMaglev, Katran, IPVS, AWS NLB
Route by path or cookie, end TLSL7 reverse proxyNGINX, HAProxy, Envoy, AWS ALB
Servers that slow downleast connections or two choicesEnvoy least request, random two least_conn
Keep a key on one serverconsistent hashing, MaglevEnvoy ring hash and Maglev

Corrections to common figures

Checklist

  1. Plan for utilisation below about 70 to 80% per server at peak, and measure per server.
  2. Put a balancer address in DNS, not server addresses.
  3. Use DSR or tunnelling at L4 when replies are large.
  4. Prefer least connections or two choices over plain round robin.
  5. Use consistent hashing or Maglev wherever affinity matters.
  6. Combine active probes with outlier ejection, and keep dependencies out of liveness probes.
  7. Drain servers before you remove them.

The core as code

python# two random choices against random placement, on 100 servers (sketch)
import heapq, random

def simulate(n=100, lam=0.9, d=2, reqs=200_000, seed=1):
    rnd = random.Random(seed)
    done = [[] for _ in range(n)]          # finish times of requests in flight, per server
    free_at = [0.0] * n                    # when each server's queue empties
    t, total = 0.0, 0.0
    for _ in range(reqs):
        t += rnd.expovariate(lam * n)          # random arrivals at rate lam * n
        def busy(i):                          # requests still in flight on server i
            while done[i] and done[i][0] <= t: heapq.heappop(done[i])
            return len(done[i])
        i = min(rnd.sample(range(n), d), key=busy)   # d = 1 is random placement
        free_at[i] = max(t, free_at[i]) + rnd.expovariate(1.0)
        heapq.heappush(done[i], free_at[i])
        total += free_at[i] - t
    return total / reqs                        # mean time in system, in service times

for d in (1, 2):
    print(d, round(simulate(d=d), 2))         # about 10 and 2.6: the formula gives 10 and 2.61

Keep going

The takeaway. Keep each server below full, because queues grow like 1 / (1 − ρ). Pick servers by what they are doing, with least connections or two random choices. Hash only when a key must stay put, and find dead servers from real errors, not only from probes.

Now press Present or Teach and explain five things from memory. Explain why one shared line waits 6.7 ms where ten random lines wait 90 ms. Explain why a removed DNS record lingers for a TTL. Explain why DSR saves the balancer's link. Explain why two random choices cut the time from 10 to 2.6. Then go back to the hero, pick Random, and push the load to 95%.

Load Balancing
Mitzenmacher 2001 · Maglev 2016 · Envoy · Back to Gleams