Load Balancing (System Design #8)
You scaled from one server to four, and for a week everything is faster. Then one afternoon three servers idle at 20% CPU while the fourth pegs at 100% and times out. Nobody reconfigured anything. What happened is that your traffic is not uniform: a few heavy clients, a hot endpoint, or a cache that only warms on one box can concentrate load. A load balancer is supposed to prevent exactly this — but only if it is configured for your traffic.
This chapter covers how load balancers work, the difference between L4 and L7, the algorithms that distribute requests, health checking, and how to keep the balancer itself from becoming the outage.
What a load balancer does
A load balancer (LB) sits in front of a pool of servers and forwards each incoming request to one of them. It turns “a server” into “a pool of interchangeable servers”, which is the prerequisite for horizontal scaling, rolling deploys, and fault tolerance.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
b/.style={draw, thick, rounded corners=3pt, minimum width=1.6cm, minimum height=0.7cm, align=center, font=\rmfamily\small},
a/.style={->, thick}]
\node[b, fill=gray!10] (c) at (-3.6,0) {clients};
\node[b, fill=orange!16] (lb) at (-1.3,0) {LB};
\node[b, fill=green!12] (s1) at (1.0,1.1) {srv 1};
\node[b, fill=green!12] (s2) at (1.0,0) {srv 2};
\node[b, fill=green!12] (s3) at (1.0,-1.1) {srv 3};
\draw[a] (c) -- (lb);
\draw[a] (lb) -- (s1); \draw[a] (lb) -- (s2); \draw[a] (lb) -- (s3);
\end{tikzpicture}
Two jobs it must do well: distribute according to the algorithm, and remove unhealthy servers via health checks. A third, subtler job is observability — the LB is the best place to measure request rate, latency, and error rate per backend.
LB vs reverse proxy
The two are often the same software, but they are conceptually different:
- A load balancer distributes across multiple instances of the same service.
- A reverse proxy sits in front of one or more backends and does more: TLS termination, routing by path/host, compression, caching, rate limiting, request/response rewriting.
Most modern tools (Nginx, Envoy, HAProxy, cloud ALBs) are both. The distinction matters at design time: if a request must reach the same service, it is balancing; if it must be transformed or routed by content, it is proxying.
Layer 4 vs Layer 7
The OSI layer at which the LB operates determines what it can see and decide.
- Layer 4 (transport). Routes by IP and TCP/UDP port. It never looks inside the packet, so it is fast and protocol-agnostic (works for any TCP/UDP app). But it cannot route by URL or HTTP header, cannot terminate TLS with content awareness, and cannot do HTTP-level retries.
- Layer 7 (application). Terminates and parses HTTP. It can route by path (
/apivs/static), host, header, or cookie; do health checks on application endpoints; retry idempotent requests; and apply per-route policies. It is slower per request but far more capable.
| L4 | L7 | |
|---|---|---|
| Sees | IP, port | full HTTP request |
| Routing | connection-level | path, host, headers, cookies |
| TLS | passthrough | terminate + inspect |
| Speed | fastest | fast enough, more features |
| Example | HAProxy TCP, NLB | Nginx, Envoy, ALB |
\begin{tikzpicture}[font=\rmfamily, >=stealth,
b/.style={draw, thick, rounded corners=3pt, minimum width=1.9cm, minimum height=0.7cm, align=center, font=\rmfamily\small},
a/.style={->, thick}]
\node[b, fill=blue!10] (l4) at (-2.3,0.8) {L4\\ip:port only};
\node[b, fill=orange!16] (l7) at (-2.3,-0.8) {L7\\inspect HTTP};
\node[b, fill=green!12] (a2) at (1.4,0.8) {backend by conn};
\node[b, fill=green!12] (b2) at (1.4,-0.8) {route by /api, host};
\draw[a] (l4) -- (a2); \draw[a] (l7) -- (b2);
\end{tikzpicture}
Use L4 for raw throughput and non-HTTP protocols; use L7 when routing or policy needs to understand the request. Many architectures use both: an L4 LB for TLS passthrough to a fleet of L7 proxies.
Distribution algorithms
| Algorithm | How it picks | Best when |
|---|---|---|
| Round robin | take turns | homogeneous servers, uniform requests |
| Weighted round robin | turns proportional to capacity | mixed instance sizes |
| Least connections | fewest active connections | long-lived/uneven requests |
| Least response time | fastest recent backend | latency-sensitive |
| IP / hash | hash of client IP or key | affinity, cache locality |
| Consistent hashing | key → ring, minimal reshuffle | distributed caches, sharded stores |
Round robin is the default and usually fine. Least connections handles heterogeneous request durations better — a slow request should not lock a server out while others idle. Consistent hashing is the important one for stateful caches and sharded data: when a node is added or removed, only \(1/N\) of keys move instead of all of them.
import hashlib
def ring_pos(key):
return int(hashlib.md5(key.encode()).hexdigest(), 16)
def build_ring(nodes, vnodes=100):
ring = []
for n in nodes:
for i in range(vnodes): # virtual nodes smooth the distribution
ring.append((ring_pos(f"{n}-{i}"), n))
return sorted(ring)
def pick(ring, key):
h = ring_pos(key)
for pos, node in ring: # first node clockwise
if pos >= h:
return node
return ring[0][1]
nodes = ["A", "B", "C"]
ring = build_ring(nodes)
print([pick(ring, f"user-{i}") for i in range(10)])
# remove a node -> only ~1/3 of keys move, unlike modulo hashing
Virtual nodes are why consistent hashing works in practice: hashing each physical node many times smooths the ring so one node does not own a huge arc.
Health checks and connection handling
A backend that accepts TCP connections but returns 500s should not receive traffic. Health checks fix that:
- Passive — the LB observes real request failures and ejects a backend that fails too often.
- Active — the LB periodically probes a health endpoint (
/healthz) that checks dependencies (DB, cache) and returns 200⁄503. - Connection draining — on deploy or ejection, stop sending new requests but let in-flight ones finish. Without draining, deploys drop requests.
Sticky sessions pin a client to one backend, usually to keep a local session or cache warm. Prefer not to rely on them: they defeat even distribution, break when a backend dies, and prevent clean horizontal scaling. If you need affinity, do it for caching (consistent hashing), not identity — put sessions in a shared store and stay stateless.
Scaling out and keeping the LB up
Horizontal scaling means adding servers behind the LB; the LB distributes load and, combined with health checks, makes failures invisible. But now the LB is a single point of failure, so it must itself be redundant:
- Active-passive pair with a floating IP or virtual IP: the passive takes over if the active dies.
- DNS round-robin / anycast: multiple LBs share the address; DNS returns several, or the network routes to the nearest.
- Cloud managed LBs handle this for you (and scale internally).
\begin{tikzpicture}[font=\rmfamily, >=stealth,
b/.style={draw, thick, rounded corners=3pt, minimum width=1.7cm, minimum height=0.7cm, align=center, font=\rmfamily\small},
a/.style={->, thick}]
\node[b, fill=gray!10] (c) at (-4.4,0) {clients};
\node[b, fill=orange!16] (lb1) at (-2.2,0.8) {LB active};
\node[b, fill=gray!12, dashed] (lb2) at (-2.2,-0.8) {LB passive};
\node[b, fill=green!12] (s1) at (0.8,1.2) {srv};
\node[b, fill=green!12] (s2) at (0.8,0) {srv};
\node[b, fill=green!12] (s3) at (0.8,-1.2) {srv};
\draw[a] (c) -- (lb1); \draw[a] (c) -- (lb2);
\draw[a] (lb1) -- (s1); \draw[a] (lb1) -- (s2); \draw[a] (lb1) -- (s3);
\end{tikzpicture}
Pitfalls
- LB without health checks. Traffic keeps flowing to dead or unhealthy backends; users see errors an LB was supposed to hide.
- Sticky sessions by default. They concentrate load, break failover, and block deploys. Go stateless.
- Modulo hashing for caches. Adding or removing a node moves nearly every key, cold-starting every cache. Use consistent hashing.
- No connection draining. Rolling deploys drop in-flight requests. Drain before shutdown.
- A single LB. It becomes the outage. Pair it, or use a managed/anycast load balancer.
- Ignoring slow backends. Least-connections and passive health checks matter more than throughput when one backend is sick.
When do you reach for L7 over L4? Why is consistent hashing preferred over hash % N for distributing keys?
ASolution
Use L7 when routing or policy must understand HTTP — path/host/header routing, TLS termination, content-aware retries. Consistent hashing maps keys to a ring so adding or removing a node moves only about \(1/N\) of keys, whereas modulo hashing reshuffles almost everything and cold-starts caches.
Next: The Application Layer and Microservices (System Design #9) — what runs behind the balancer, and how the pieces find each other.