Highlights

Contents

Part III
03

Load balancing

We spread requests across many instances so that none is overwhelmed and a failed one is skipped. The layer the balancer works at decides what it can see, and the algorithm decides how evenly the load lands. We will cover layer 4 and layer 7 balancing, the common algorithms including power of two choices, consistent hashing, and health checks, slow start, draining and sticky sessions.

CHAPTER ATLAS / FOLLOW THE READING PATHCHAPTER ATLAS / FOLLOW THE READING PATH1Reverse proxies2Nginx internals3Load balancing4TCP load balancers5Service discovery6Gateways and servicemeshes7Private networks andTailscale8Sockets and connectionsin production9Cloud building blocks10A request across thenetwork

#Section 7Layer 4 and layer 7

A load balancer distributes incoming work across a pool of backends. The first question is what it looks at to decide. A layer 4 balancer works at the transport layer, TCP or UDP. It sees source and destination IP addresses and ports, and nothing inside the connection. It makes one decision per connection, choosing a backend when the connection opens, and every byte of that connection goes to the same backend. A layer 7 balancer works at the application layer, HTTP. It terminates the connection, reads each request’s method, host, path, headers and cookies, and makes a decision per request.

L4 READS THE ENVELOPE; L7 OPENS IT AND READS THE LETTERL4 READS THE ENVELOPE; L7 OPENS IT AND READS THE LETTERlayer 4 (TCP)layer 7 (HTTP)198.51.100.7:51234 → :443IP, port, protocol;one decision per connectionGET /orders/123Host: api.wren.exampleCookie: sess=…X-Api-Version: 2host, path, headers, cookies;one decision per request
Figure 11.8Layer 4 sees only the envelope. Layer 7 opens it and reads the request.

Each has its strengths. Layer 4 is fast and protocol-agnostic. It can balance databases, Redis, MQTT, gRPC or anything over TCP, it adds very little latency, and it can pass TLS through untouched so the backend terminates it. Cloud network load balancers, Linux IPVS and Google’s Maglev, described in 2016, are layer 4. Layer 7 is flexible. It can route /orders and /menus to different services, split traffic by header for canary deploys, retry a failed request on another backend, add headers, and balance each request of a long-lived HTTP/2 connection independently. Nginx, HAProxy in HTTP mode, Envoy and cloud application load balancers are layer 7.

The difference matters most for long-lived connections. A mobile app holding one HTTP/2 connection for ten minutes sends all its requests to one backend behind a layer 4 balancer, and to many behind a layer 7 one, which Part IV examines. Most production paths use both. A layer 4 balancer spreads connections across a fleet of layer 7 proxies, which then route and balance individual requests to services.

#Section 8Choosing a backend

Once a balancer has a pool of healthy backends, an algorithm picks one for each connection or request.

Round robin takes backends in turn, the simplest choice, and fine when backends are identical and requests similar. Weighted round robin gives some backends more turns, for machines of different sizes or for sending 5% of traffic to a canary. Least connections sends each new connection or request to the backend with the fewest in progress, which adapts when some requests are much slower than others. Least response time prefers backends that have answered fastest recently, combining speed and load. Random choice is surprisingly good with many requests and needs no shared state.

SIX WAYS TO PICK A BACKEND, AND WHAT EACH ONE LOOKS ATSIX WAYS TO PICK A BACKEND, AND WHAT EACH ONE LOOKS ATround robinnext in turnweightedbigger gets moreleast connectionsfewest openleast response timefastest recentlyrandomcoin tosspower of twobetter of 2 random
Figure 11.9Six algorithms. The power of two choices gets close to least-loaded with almost no coordination.

The power of two choices, analysed by Michael Mitzenmacher in his 1996 thesis, deserves special mention. Pick two backends at random and send the request to the less loaded of the two. The improvement over picking one at random is dramatic. With n backends, a single random choice leaves the busiest backend with load growing roughly as ln n ÷ ln ln n above average, while two choices reduce it to about ln ln n ÷ ln 2, an exponential improvement, for the cost of looking at one extra number.

POWER OF TWO CHOICES: PICK TWO AT RANDOM, SEND TO THE LESS LOADEDPOWER OF TWO CHOICES: PICK TWO AT RANDOM, SEND TO THE LESS LOADEDb0b1b2b3b4b5b6b7sampled b1 (2) and b4 (7)max load with n backends: about ln ln n ÷ ln 2,against ln n ÷ ln ln n for one random pickno global view needed, so many independent balancers can use it without herding onto one backend
Figure 11.10Two random backends sampled, the lighter one chosen.

It also behaves well when there are many balancers. If ten independent Nginx instances each use least connections, they all see the same lightly loaded backend at the same moment and all send to it, a herd that makes it the most loaded. With power of two choices, their random samples differ, and the herd never forms. Envoy’s default LEAST_REQUEST policy and HAProxy’s random(2) implement it, and Wren uses it for requests to its services.

#Section 9Consistent hashing

Sometimes requests for the same key should go to the same backend. A cache sharded across nodes wants each key on one node, so it is cached once. A WebSocket server may want each chat room on one node. The obvious method, hash(key) mod n, works until n changes. Going from 4 nodes to 5 changes the result for most keys. Only keys whose hash gives the same remainder modulo 4 and 5 stay, 4 out of every 20, so 80% of keys move, and a cache cluster loses most of its hits at once.

Consistent hashing, from David Karger and colleagues in 1997, places both nodes and keys on a ring, the space of hash values bent into a circle. Each key belongs to the first node clockwise from it. Adding a node E takes over only the arc between E and the node before it, so only the keys in that arc move, all of them from one neighbour. With 4 nodes becoming 5, about 1/5 of keys move instead of 4/5. Removing a node hands its arc to the next node clockwise.

CONSISTENT HASHING: ADD A NODE AND ONLY ITS SLICE OF KEYS MOVESCONSISTENT HASHING: ADD A NODE AND ONLY ITS SLICE OF KEYS MOVESABCDEhash(key) → a point on the ring;the next node clockwise owns itadding E to 4 nodes moves about 1/5of keys, all from one neighbourhash mod n moves 80% of keyswhen n goes from 4 to 5100 to 200 virtual nodes per serversmooth out uneven slices
Figure 11.11E joins the ring and takes one arc. Only keys in that arc move.

A ring with a few nodes divides unevenly, since random positions leave some arcs much longer than others. Virtual nodes fix this. Each physical node is placed at 100 to 200 points on the ring, so its share is the sum of many small arcs and comes out close to equal. Virtual nodes also let a bigger machine take more points and more load. Amazon’s Dynamo paper in 2007 popularized the design, and Cassandra, Riak and many caches use it.

Variants trade different properties. Rendezvous hashing, or highest random weight, computes a score for each node per key and picks the highest, with similar movement and no ring. Jump consistent hash, from Google in 2014, needs no memory but only supports adding and removing nodes at the end. Maglev hashing builds a lookup table that spreads load very evenly with minimal disruption, for Google’s layer 4 balancers. Envoy offers ring hash and Maglev as load-balancing policies for sticky routing by header or cookie.

#Section 10Health checks, slow start, draining and stickiness

A balancer must know which backends can take traffic. Active health checks probe each backend regularly. Wren’s balancer sends GET /healthz every 5 s, removes a backend after 2 consecutive failures, and returns it after 3 consecutive successes, so a single blip neither removes nor restores it. Passive health checks, called outlier detection in Envoy, watch real traffic, and eject a backend that returns 5 consecutive 5xx responses or connection resets, for 30 s at first and longer each time it repeats. Passive checks react within seconds of real failures. Active checks find backends that are broken before any user hits them.

The health endpoint should check what makes the instance useful, that it can serve requests, and not every dependency, Unit XV. A health check that fails whenever the database is slow removes every instance at once, turning a slow database into a total outage.

ACTIVE AND PASSIVE HEALTH CHECKS, THEN A SLOW STARTACTIVE AND PASSIVE HEALTH CHECKS, THEN A SLOW STARTLBactive: GET /healthz every 5 s;2 failures → out, 3 passes → inpassive: 5 consecutive 5xx orresets on real traffic → eject 30 ssshareslow start over 30 s
Figure 11.12Probes every 5 s, ejection on repeated errors, and a 30 s ramp for a returning backend.

A backend that has just started, or just returned, may be cold, with empty caches, unloaded code and an unwarmed connection pool. Slow start ramps its share of traffic over a period, 30 s for Wren, instead of giving it its full share at once.

Removing a backend for a deploy needs connection draining. The instance stops receiving new connections or requests, while those in progress finish, up to a limit such as 20 s, and only then is it stopped. In Kubernetes, that means handling SIGTERM by failing readiness, waiting for the balancer to notice, finishing in-flight work, and closing idle keep-alive connections before exiting, Unit XV.

CONNECTION DRAINING: STOP SENDING NEW WORK, LET OLD WORK FINISH, THEN STOPCONNECTION DRAINING: STOP SENDING NEW WORK, LET OLD WORK FINISH, THEN STOPinstancenew requestsin flightsservingdrainingexitrouted hereremoved from the poolfinish naturally, up to 20 sSIGTERM → fail readiness → wait for the LB to notice → finish in-flight → close idle keep-alives → exit
Figure 11.13Removed from the pool, in-flight requests finish, then the process exits.

Sticky sessions, or session affinity, send a user’s requests to the same backend, by a cookie the balancer sets or by hashing the client address. They help when a backend keeps per-user state in memory or a warm per-user cache. They also make that state fragile, since when the backend dies or is drained, its users lose the state, and they unbalance load when some users are much busier than others. Wren keeps sessions in Redis, Unit III, so it needs no stickiness for correctness, and uses it only for WebSocket servers, Unit XII.

STICKY SESSIONS PIN A USER TO ONE BACKEND, AND ITS FATESTICKY SESSIONS PIN A USER TO ONE BACKEND, AND ITS FATECookie: lb=backend-2LBuseful for in-memory session state or warm caches; when backend 2 dies, its users lose their state
Figure 11.14A cookie pins the user to backend 2, and to its failure too.