Systemsfor Aravinda
0 / 78 core
Week 1 · Fundamentals

Load balancing

2.5 hours · core path

Read first: Networking for request paths

In one sitting

L4 spreads connections without reading HTTP; L7 can route and terminate TLS. Round robin, least connections, and power of two choices balance live load in different ways, while consistent hashing moves about 1/N of the keys and modulo moves almost all of them. Sticky sessions then pin a hot client to a machine that can die during a drain.

You add a load balancer when one process cannot hold the concurrency, or when a dead process must stop receiving work. The algorithm is the short part. The long part is what happens to in-flight requests, and to cached keys, when the set of machines changes. Networking for request paths is why a WebSocket can only live on the machine that accepted it. This page is how everyone else gets spread out, and why “spread out” breaks the hour you lose a node.

Core concepts

L4 and L7 look at different bytes. An L4 balancer forwards TCP or UDP. It does not read HTTP. It can spread connections, and it cannot send one path to one pool and another path to a different pool, because it never sees the path. An L7 balancer reads the request. It can route on path, host, and header, and it can terminate TLS. Terminating TLS means the balancer finishes the handshake with the client and then opens its own connection to the backend.

That termination is a cost you can price. A cold client still pays TCP’s one round trip and about one more for TLS 1.3, at the balancer, before any application byte. The balancer then needs a connection inward. If that pool is warm, the extra hop is a same-datacenter round trip, Dean’s 0.5 ms, and it is not on the handshake. If you open it cold, add another TCP round trip and about one TLS round trip on that 0.5 ms path, about a millisecond, and keep the inner hop encrypted anyway. L7 is how /static and the API can land in different pools. L4 is how you spread a single TCP service when every connection is the same kind of work. Pick L7 when the routing decision is the feature. Pick L4 when you do not want a parser and a certificate on the data path of every packet.

Three algorithms for live load. Round robin hands connection 1 to A, 2 to B, 3 to C. Counts match. Cost does not. A 1 millisecond health check and a one-second upload count as one turn each, so a server that drew the uploads is busy while its neighbor is idle.

Least connections sends the next request to whoever currently holds the fewest. Occupancy tracks load when “a connection” means “work in flight,” which is true for ordinary HTTP and very true for a WebSocket that sits open for an hour. The cost is that someone must know the counts, and the count has to mean what you think. A server full of idle sockets looks busy. A server with three requests that are each stuck in a slow database looks almost idle if you only count new accepts.

Power of two choices, Mitzenmacher’s result: pick two candidates at random, send to the less loaded. You do not ask every machine. Two samples get you most of the balance. Define “loaded” or you sampled noise. A small proof is worth doing once so the result is not a slogan. Suppose one server is strictly the most loaded, and you sample two distinct candidates and keep the lighter one. The heavy server is chosen only if it is the lighter of the pair, which means the other sample is even heavier. There is no such sample. So the unique maximum never receives the next request. With four servers the pairs are the six ways to choose two of them, and every pair either excludes the heavy server or includes it next to a lighter one. In all six you avoid it. Least connections would have picked the global minimum. Power of two choices only needed two numbers and still refused to make the worst server worse.

Consistent hashing and modulo disagree the moment N changes. Consistent hashing, Karger and others in 1997, places nodes and keys on a ring. A key belongs to the next node clockwise. Virtual nodes give each physical machine many points on the ring so the arcs stay close to equal. Amazon Dynamo used that so one host owns many short arcs instead of one lucky slice. Adding a node moves about 1/N of the keys, the share the newcomer takes. The other keys stay. Removing a node, on a balanced ring, moves about the share that node held, again about 1/N. Everyone else keeps hitting.

Modulo hashing is hash % N. Change N and almost every key changes bucket. Here is the removal in arithmetic, for a scheme that resizes the modulus to the number of live nodes. Going from N nodes to N minus 1, a key keeps the same bucket index only when hash % N equals hash % (N - 1). N and N minus 1 are coprime, so the pair of residues repeats every N * (N - 1) keys. The two residues match for N minus 1 of those values: the common residue can be 0 through N minus 2, and it cannot be N minus 1 because hash % (N - 1) never equals N minus 1. The fraction that stays is (N - 1) / (N * (N - 1)) = 1/N. The fraction that moves is (N - 1) / N. For 100 nodes, modulo moves 99 percent of the keys. Consistent hashing moves about 1 percent. Same failure, opposite cache behavior.

A hot key is still one key. The ring does not split it. Partitioning and sharding makes the same point for data: more partitions do not fix a key that everyone wants. The node that owns it is the bottleneck, and adding nodes moves other keys off their owners without moving that one.

Health checks and draining. A health check is the question “should you receive work?” A process that answers while its database is down will say yes and then fail every real request. The check has to mean “can you serve,” or you need a second signal that pulls the node out when the dependency is gone. Do not invent a magic interval. Do require more than one failure before you eject a node, or a single dropped probe flaps the membership and you churn connections for a blip.

Draining is how you remove a node on purpose. Stop assigning new work. Let in-flight requests finish, or cancel them at a deadline you chose. Then stop the process. Cutting every socket the moment the health check fails turns a deploy into an error spike. The drain takes as long as the slowest call you refuse to cancel. A 5 second timeout means a drain can sit for 5 seconds even if the typical call was 2 milliseconds. That is Little’s law again, pointed at one machine: the in-flight count on the way out is the arrival rate that machine still owns, times the timeout.

Sticky sessions hide a bug and then freeze it. The balancer remembers that this client goes to machine 7, usually with a cookie, because machine 7 stored something in memory that machine 8 does not have. That memory is the bug. While it works, load follows users instead of spreading. One hot client lives on machine 7. When machine 7 dies, a sticky rule that outranks the health check keeps sending that client to a dead machine. The rest of the pool looks healthy. The symptom is one customer on fire and a green average.

Stickiness also fights drains. If the cookie still selects a node you are trying to empty, the node never goes idle, the deploy script gives up and kills it, and those users take the errors. Connection affinity for an open socket is a different thing: the file descriptor is on that machine, so the frames have to go there until the socket closes. A cookie that pins the next hour of ordinary HTTP requests is the part that rots. Put the session in a shared store, or hash the client so any live machine can serve, and keep affinity only for the connection that physically cannot move. Slack’s real-time path puts channel assignment on a consistent-hash ring rather than on a cookie. Channel servers are in memory, on the order of 16 million channel ids per host at peak in that writeup, where a “channel” is an id for a channel, a user, a file, or a similar entity. Losing a host moves the channels that hashed to it, not every channel, and not “whoever’s cookie said so.”

A worked example

One hundred cache nodes. The traffic is the teaching scale: 100 million daily users, 20 reads each, two billion reads a day. Assumptions besides that scale: the ring is balanced, so each node owns about 1/100 of the keys; a hit is served from the node that owns the key; a key that moves is a miss until something refills it; peak is 3 times the average, a guess inside the 2x to 5x band.

average reads              2,000,000,000 / 86,400 = 23,148 per second
shortcut                   2,000,000,000 / 100,000 = 20,000 per second
peak, assumption 3x        3 * 23,148 = 69,444 per second

one node dies, consistent hash, about 1/N of keys move
  average extra misses     23,148 / 100 = 231 per second
  peak extra misses        3 * 23,148 / 100 = 694 per second
  keys that stay           about 99 percent

same death, modulo resized from 100 to 99
  fraction that stay       1/100
  fraction that move       99/100
  average extra misses     23,148 * 0.99 = 22,917 per second
  peak extra misses        about 68,750 per second

in flight, assume 2 ms per read
  whole fleet, average     23,148 * 0.002 = 46
  one node, average        about 0.5
  one node stuck to 5 s    (23,148 / 100) * 5 = 1,157 hung calls on the way out

hot key, assume one object is a tenth of reads
  that node                0.10 * 23,148 = 2,315 per second
  each other node          (23,148 - 2,315) / 99 = 210 per second

Losing one node on a ring is a 1 percent miss storm: about 231 extra database reads per second average, about 700 at the assumed peak. The other 99 nodes still hit. You can survive that if the database can absorb a few hundred reads per second it was not seeing. Caching is the refill. Those misses are also a stampede risk on the keys that moved: many clients miss the same key together, and a single-flight fill keeps the database at one read per key instead of one per client.

Losing one node under modulo is a different incident. Ninety-nine percent of keys change bucket. The cache you paid for misses all at once, about 23,000 extra database reads per second average and about 69,000 at the 3x peak. You turned a one-node failure into a full flush. The derivation is the 1/N that stay, not a vibe about hashing. Write 1/N and (N - 1)/N on the board so the 99 percent is earned.

The in-flight line is why draining is cheap when calls are short and expensive when the timeout is long. At 2 milliseconds, a node holds a fraction of a request. You can pull it out and barely notice. If the node is wedged and every call runs to a 5 second timeout, it is holding on the order of a thousand requests that all fail together when you finally cut it. Cancel at a drain deadline instead of inheriting the longest timeout on the box.

The hot-key line is the limit of both algorithms. A tenth of the reads on one object is an assumption, to show the shape. That object hashes to one node. Consistent hashing, modulo, round robin of the cache nodes: none of them split the key. That node does about 2,300 reads per second and the others do about 210. About eleven times its peers. Adding a hundred and first node moves about 1 percent of other keys and leaves this one alone. The fix is a different key, a local cache in front, or accepting that one object is a single-node problem. More boxes are not the fix.

Sticky sessions make the same picture worse. Suppose the balancer also pins a user to a cache node with a cookie, because someone stored a session in process memory. The node dies. Health checks remove it from round robin, so most users recover. The pinned user keeps presenting the cookie. If the cookie wins, that user is stuck to a dead target after the fleet has healed. The dashboard averages them into the noise: one user is 1 percent of nothing, and they see 100 percent errors. During a deploy the same cookie keeps the draining node busy, so the drain never reaches zero.

flowchart LR
  client[Client]
  lb[Balancer]
  live[Live cache node]
  other[Other cache node]
  db[Database]
  client --> lb
  lb --> live
  lb --> other
  live --> db
  other --> db

A dead node is absent from the drawing on purpose. Once the health check has fired, no new arrow points at it. The keys it owned miss through to the database. If your real balancer still has an arrow, labeled with a cookie, you have not finished the health check.

Tradeoffs

Choice What you gain What you spend
L4 Cheap spread of connections, no HTTP parsing You cannot route on path, host, or header
L7 Path and header routing, TLS in one place A parser and a handshake on the data path
Round robin Even counts, no shared metrics Long requests pile on whoever drew them
Least connections Occupancy follows real work A global count, and it lies if idle sockets count as load
Power of two choices Most of the balance from two samples A bad load signal sampled twice is still bad
Consistent hashing Adding or losing a node moves about 1/N of the keys A hot key still lives on one node
Modulo of a resized N Simple, even, fine while N is frozen A membership change moves almost every key
Sticky cookie In-memory session keeps working A hot client sticks to a dead machine, and drains stall

Pitfalls

  • Resizing hash % N when a cache node dies. About (N - 1)/N of the keys miss at once. The database sees a flush, not a 1/N blip.
  • Expecting consistent hashing to cool a hot key. The key still maps to one node. The symptom is one host saturated and the others bored.
  • Round robin across a mix of tiny requests and long uploads, or across WebSockets. Counts look fair. CPU and sockets do not.
  • A health check that only proves the process is listening. The database is down, the node stays in rotation, and about 1/N of traffic fails while the pool looks complete.
  • Ejecting a node on a single failed probe. Membership flaps, connections reset, and a blip becomes churn.
  • Killing sockets the instant a node fails health, with no drain. Every in-flight request errors. The drain existed so they could finish or hit a short deadline.
  • A sticky cookie that outranks the drain bit. The node never empties, the deploy kills it, and one slice of users takes all of the errors.
  • Using the sticky cookie to paper over a session stored in memory. The bug survives until the pinned machine dies, which is the worst time to discover it.
  • Forgetting that an open WebSocket is affinity you cannot configure away. The frames have a home. The user’s next ordinary request does not have to share it.

In the interview

Say L4 or L7 in the first minute, then the algorithm, then what a lost node does to the keys. A cache wants consistent hashing. A set of stateless HTTP servers wants least connections or power of two choices, and round robin only if the requests are the same size. A WebSocket tier wants affinity for the socket and a drain that does not honor a stale cookie.

Skip a taxonomy of twenty vendor algorithms. The grader has heard of round robin. They are listening for “modulo moves almost everything, the ring moves about 1/N” and for the drain.

The question that usually follows is “one node dies” or “one user is a tenth of the traffic.” Node dies: on a ring you miss about 1/N and you refill; under modulo you miss almost everything; either way you stop sending new work and you drain or cancel the in-flight calls. Hot user: hashing will not split them, stickiness makes them worse, and the fix is to get their state out of the process. Design a chat system is where the socket affinity and the shared store show up together. Offer that tradeoff before they ask what you gave up. You gave up pinning, and you took a shared session store.

Check yourself

You add one node to a balanced ring of 100, and you also try hash modulo resized from 100 to 101. What fraction of keys move in each scheme?

On the ring, the new node takes about 1/N of the keys, with N the new size, so about 1 percent move and the rest stay. That is the consistent-hashing result. Under modulo, a key keeps the same index only when the old residue and the new one match. Going from N to N plus 1, that fraction is 1 over N plus 1, so about 1 percent stay and about 99 percent move. Resizing the modulus is a cache flush. Adding a ring node is not.

Four servers hold 10, 12, 40, and 11 connections. Where does the next request go under round robin, least connections, and power of two choices?

Least connections sends it to the server holding 10. Power of two choices samples two distinct servers and keeps the lighter one. The server holding 40 is strictly the heaviest, so it loses every pair it is in, and it is never chosen. Round robin might hand it to the server holding 40, because round robin does not look at the counts. That is the whole difference: counts are fair, load is not.

One hundred cache nodes serve 23,148 reads per second and one dies. Compare database misses on a balanced ring and on modulo resized to 99.

The ring moves about 1/100 of the keys: about 231 misses per second until those keys are refilled. Modulo keeps about 1/100 of the keys in the same bucket and moves the rest: about 22,900 misses per second. Peak, if you assumed 3x, multiplies both. The failure you can absorb is the 231. The failure that takes the database down is the 22,900.

A health check passes, the database behind that node is down, and a sticky cookie pins your largest customer there. What does the dashboard show?

The node stays in the pool because the process is alive, so the balancer keeps offering it work. About 1/N of unpinned traffic fails if the bad node is one of N. The pinned customer fails on every request, including after you thought you had drained the node, if the cookie outranks the drain. An average error rate hides them. The check has to mean the node can serve, and the cookie has to die when the node leaves rotation.

A typical cache read takes 2 ms and the timeout is 5 seconds. Why can a drain of one idle-looking node still take seconds?

Drain time is the longest call you refuse to cancel, not the average. At 2 ms a healthy node holds a fraction of a request and can leave quickly. A wedged node runs each call out to the 5 second timeout. Its share of a 23,148 per second fleet is about 231 arrivals per second, times 5 seconds, about a thousand hung calls. Cancel them at a drain deadline or you wait out a timeout you did not mean to inherit.

Based on: Karger and others, consistent hashing, 1997; Mitzenmacher, the power of two choices; Amazon Dynamo, DeCandia and others; Slack Engineering, real-time messaging.