Skip to content

Lesson 4 of 38Building blocks

Load Balancers

Spread traffic across many servers, pick the right algorithm and layer, drain and health-check safely, and keep servers stateless.

23 min read0/7 questions

One server eventually runs out of CPU, and when it crashes your whole product is down. The fix is to run many identical servers and put a load balancer in front of them. It is the first box you add when an app outgrows one machine, and it shows up in nearly every system design answer.

What a load balancer does

A load balancer (LB) is a server that accepts every incoming request and forwards it to one of several backend servers (also called targets, upstreams, or a pool). It gives you three things at once:

  • Scale: ten servers handle roughly ten times the traffic of one.
  • Availability: if a server dies, the LB stops sending it traffic. Users never notice.
  • Zero-downtime deploys: take servers out one at a time, upgrade them, put them back.

Step through a round-robin load balancer, including what happens when a server fails its health check.

Round robin with health checks
ClientsClientsLoad balancer: round robinLoad balancerround robinServer AServer AServer BServer BServer CServer CDatabaseDatabaseHTTPSreq 1, 4req 2req 3, 5

Request 1 goes to Server A. Round robin just takes turns.

1/7

Vertical vs horizontal scaling

Vertical (scale up)Horizontal (scale out)
HowBigger machine: more CPU, RAMMore machines behind a load balancer
LimitThe biggest box you can buy (a few hundred cores, a few TB of RAM)Practically none
FailureOne machine is a single point of failureLose one of many, keep serving
Code changesNoneServers must be stateless
Good forDatabases, early-stage appsWeb and API servers

Most systems do both: scale the app tier out horizontally and scale the database up until that stops working (the next lessons cover what you do then).

Stateless servers and sticky sessions

For a load balancer to send a request to any server, no server can hold data that only it knows. If Server A keeps your login session in its memory and the next request lands on Server B, you are suddenly logged out.

Two ways to fix it:

  1. Sticky sessions (session affinity): the LB pins each user to one server, usually with a cookie. It works, but load becomes uneven, and when that server dies, its users lose their sessions.
  2. Stateless servers: keep no user state on the server. Store sessions in a shared store like Redis, or in a signed token the client sends each time (a JWT). Any server can handle any request.

Stateless is the default answer. It makes autoscaling, deploys, and failures boring, which is exactly what you want.

Quick check
Users report being randomly logged out since you went from one app server to four. Sessions are stored in each server's memory. What is the best long-term fix?
Need a nudge? A hint rules out a wrong answer.

Load balancing algorithms

AlgorithmHow it picksGood when
Round robinTakes turns: A, B, C, A, B, CRequests cost about the same, servers are identical
Weighted round robinTurns in proportion to weights (a 2x server gets 2 turns)Mixed server sizes, canary deploys (send 5% to the new version)
Least connectionsThe server with the fewest open requestsRequest durations vary a lot, long-lived connections like WebSockets
IP hashHash of the client IP picks the serverSimple stickiness without cookies
Consistent hashingHash of a key (user id, URL) picks a server on a ring; adding a server moves only a few keysRouting to caches or shards, so the same key hits the same warm server

Round robin falls apart when some requests are much heavier than others. Run this simulation: one request in three takes 9 seconds of work, and the rest take 1 second.

Pythonbalance.py
# Requests arrive one second apart. The number is how many seconds of work each needs.requests = [9, 1, 1, 9, 1, 1, 9, 1, 1, 1, 1, 1] def simulate(name, pick): free_at = [0, 0, 0] # when each of 3 servers finishes its queue waits = [] for t, work in enumerate(requests): s = pick(t, free_at) start = max(t, free_at[s]) waits.append(start - t) free_at[s] = start + work print(f"{name:<18} worst wait {max(waits):>2}s total wait {sum(waits):>2}s") round_robin = lambda t, free_at: t % 3least_busy = lambda t, free_at: min(range(3), key=lambda s: max(free_at[s], t)) simulate("round robin", round_robin)simulate("least connections", least_busy)
Output
Press Run (⌘ Enter) to see what happens.

Round robin keeps handing the heavy requests to the same server, so a queue builds behind it. Picking the least busy server keeps every queue short.

Predict the outputPython

Which servers get the first five requests?

servers = ["a", "b", "c"]
print([servers[i % 3] for i in range(5)])
Need a nudge? Hints walk you through it.
Match the pairs0/4 matched

Pick the best algorithm for each case.

Choose an item, then its match on the other side.

Least request and the power of two choices

Real request costs are never even. A search endpoint might take 5 ms for a cached query and 2 seconds for a cold one. A report export takes a minute. Round robin is blind to all of this: it counts turns, not work, so a server that drew three slow requests in a row keeps getting its share and builds a queue while its neighbours sit idle. Your p50 looks fine and your p99 is terrible.

Least request (least outstanding requests) fixes the blindness by sending each request to the server with the fewest requests in flight. It adapts to slow requests and to slow servers: a server stuck in a long garbage-collection pause stops finishing requests, its count climbs, and traffic flows around it.

Least request has its own trap at scale. You never run one load balancer. You run several LB nodes (or every client runs a sidecar proxy, as in a service mesh), and each one has only a stale view of backend load, refreshed every few hundred milliseconds. If every balancer picks "the least loaded server" from the same stale snapshot, they all pick the same server at once. It gets flooded, the next snapshot shows it overloaded, and the whole fleet swings to the next victim. This is called herding.

The fix is surprisingly simple: power of two choices (P2C). Pick two servers at random and send the request to the less loaded of the two. Randomness spreads the balancers across the fleet, and the comparison still steers away from busy servers. The maths behind it (from research on randomly placing balls into bins) shows that going from one random choice to two cuts the worst-case load dramatically, while going from two to three helps much less. Envoy's least-request balancer uses P2C by default, and Nginx and HAProxy both offer a "random two, least connections" mode.

Run three strategies against the same traffic. Each balancer sees server queues as they were up to 5 ticks ago.

Pythontwo_choices.py
import random SERVERS = 10TICKS = 2_000REFRESH = 5 # each LB sees server load as it was up to 5 ticks ago def run(name, choose): rng = random.Random(42) queue = [0] * SERVERS # requests waiting on each server snapshot = queue[:] # the stale view the balancers route on worst = 0 for tick in range(TICKS): if tick % REFRESH == 0: snapshot = queue[:] for _ in range(9): # 9 requests arrive per tick queue[choose(rng, snapshot)] += 1 queue = [max(0, q - 1) for q in queue] # each server finishes 1 per tick worst = max(worst, max(queue)) print(f"{name:<22} worst queue {worst:>3}") def random_pick(rng, snap): return rng.randrange(SERVERS) def least_loaded(rng, snap): return snap.index(min(snap)) def two_choices(rng, snap): a, b = rng.randrange(SERVERS), rng.randrange(SERVERS) return a if snap[a] <= snap[b] else b run("random", random_pick)run("least loaded (stale)", least_loaded)run("power of two choices", two_choices)
Output
Press Run (⌘ Enter) to see what happens.

"Least loaded" with stale data is the worst of the three: every request for 5 ticks lands on the one server that looked idle. Plain random is better, and two choices beats both by a wide margin. Try REFRESH = 1 and watch least loaded recover, which is the point: it only works with fresh, global information, and that is exactly what a distributed fleet of balancers does not have.

Quick check
You run 20 Envoy sidecars, each routing to the same 50 backends using its own slightly stale view of load. Why is power of two choices a better default than always picking the least loaded backend?
Need a nudge? A hint rules out a wrong answer.

Layer 4 vs layer 7

Load balancers work at one of two levels of the network stack.

  • Layer 4 (transport) sees only IP addresses and TCP/UDP ports. It forwards raw connections without reading them. It is extremely fast and handles millions of connections, and works for any protocol (databases, game servers, MQTT). AWS Network Load Balancer is L4.
  • Layer 7 (application) reads the HTTP request: path, headers, cookies. It can route /api/* to one pool and /images/* to another, terminate TLS, add headers, retry failed requests, and do cookie-based stickiness. AWS Application Load Balancer, Nginx, HAProxy, and Envoy all work at L7.
Quick check
You want /api/* to go to your Python service and /admin/* to a separate admin service, both on the same domain. Which load balancer do you need?
Need a nudge? A hint rules out a wrong answer.

TLS termination, re-encryption, and passthrough

To read a path or a cookie, a layer 7 balancer must first decrypt the request. Where that happens is a real design decision, and it comes up in security reviews.

  • TLS termination: the LB holds the certificate, decrypts, and forwards plain HTTP to the backends over the private network. Backends save CPU, certificates live in one place (often auto-renewed by the cloud provider), and the LB can inspect everything. The cost is that traffic inside your network is unencrypted.
  • Re-encryption (TLS bridging): the LB terminates the client's TLS, does its L7 work, then opens a new TLS connection to the backend. You keep L7 routing and still encrypt every hop. Compliance regimes like PCI DSS and most zero-trust policies push you here. Service meshes take it further with mutual TLS (mTLS), where each service proves its identity with its own certificate.
  • TLS passthrough: a layer 4 balancer forwards the encrypted bytes untouched and the backend terminates TLS. The LB never sees the plaintext, so it cannot route by path, add headers, or retry. Use it when the backend must own the key, or for non-HTTP protocols.

When the LB terminates TLS, the backend no longer sees the client's real IP or the original scheme. The LB passes them in headers: X-Forwarded-For (client IP chain), X-Forwarded-Proto (https), or the standard Forwarded header. Only trust these headers when the request came from your own LB, or any client can claim to be any IP and dodge your rate limits. For layer 4 balancers, the PROXY protocol carries the client address instead.

Reverse proxies and API gateways

A reverse proxy sits in front of your servers and handles requests on their behalf. A load balancer is one kind. Nginx is the classic: it terminates TLS, serves static files, compresses responses, buffers slow clients, and spreads requests across upstreams.

nginx.conf
upstream api {
    least_conn;
    server 10.0.1.11:8000;
    server 10.0.1.12:8000;
    server 10.0.1.13:8000 backup;
}
 
server {
    listen 443 ssl;
    server_name api.example.com;
 
    location /api/ {
        proxy_pass http://api;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

An API gateway is a reverse proxy with product features for APIs: authentication (checking API keys or JWTs), rate limiting, request validation, routing to many microservices, and usage metering. Examples are AWS API Gateway, Kong, and Apigee. Rule of thumb: an LB spreads load across copies of one service; a gateway is the single front door to many services.

The load balancer is itself a single point of failure unless you make it redundant. Managed LBs (AWS ALB, Google Cloud Load Balancing) run across several zones for you. Self-hosted ones run as an active/passive pair that share a floating IP.

Health checks, draining, and slow start

The health check in the first diagram looks simple, but most load-balancer outages at work come from getting its details wrong.

What the check tests. A shallow check (/healthz returns 200 if the process is up and can serve) answers "should this one server get traffic?" A deep check that also queries the database, the cache, and two downstream APIs sounds more thorough, but think about what happens when the database has a 10-second blip: every server fails its check at the same moment, the LB marks the whole pool unhealthy, and a small database hiccup becomes a total outage. Keep the LB's check about the instance itself. Report dependency health on a separate endpoint for dashboards and alerts.

Kubernetes makes the split explicit. A liveness probe asks "is this process stuck, should it be restarted?" A readiness probe asks "should it receive traffic right now?" A server can be alive but not ready, for example while it loads a cache at startup.

Thresholds. One failed probe proves nothing: a packet was dropped, a GC pause hit. LBs use an unhealthy threshold (say 3 failures in a row) and a healthy threshold (say 2 passes) before changing a server's state. Lower thresholds react faster but flap. Many managed LBs also fail open: if every target is unhealthy, AWS ALB sends traffic to all of them anyway, on the theory that a bad health check is more likely than a dead fleet. Know your LB's behaviour before you rely on it.

Connection draining. When you remove a server for a deploy or a scale-in, cutting it off instantly kills every request in flight. Instead the LB stops sending it new requests and gives existing ones time to finish. AWS calls this the deregistration delay (300 seconds by default, which is far too long for an API with 200 ms requests and far too short for a 20-minute upload). Your server has to cooperate too: on SIGTERM it should fail its readiness check, stop accepting new connections, finish current work, then exit.

Draining one server during a rolling deploy
DeployerLoad balancerServer Bderegister Server Bno new requestslast in-flight responseSIGTERM, deploy v2, startGET /healthz (2 passes)traffic ramps up over 60 s

The deploy starts with one server at a time, so the others keep serving.

1/6

Slow start. A freshly started server is slower than its neighbours: empty caches, cold connection pools, and for the JVM or .NET, code that has not been JIT-compiled yet. Least connections makes this worse, because the new server has zero connections and instantly looks like the best target. Slow start ramps its share up over a window (AWS ALB lets you set 30 to 900 seconds; Envoy and HAProxy have equivalents) so it warms up before it takes full load.

Quick check
Your health check endpoint runs SELECT 1 against the primary database and calls the payments API. During a 15-second payments API outage, what happens?
Need a nudge? A hint rules out a wrong answer.
Put it in order5 steps

Put the steps of safely replacing one server behind a load balancer in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

Global load balancing: GeoDNS vs anycast

Everything so far happens inside one region. When you run in several regions, something has to send a user in Tokyo to the Tokyo deployment and move them elsewhere when Tokyo is down. There are two main tools.

GeoDNS (Route 53 geolocation or latency routing, for example) answers the same DNS name with a different IP depending on where the query comes from. Simple and works with any backend. Its weaknesses all come from DNS:

  • It sees the location of the DNS resolver, not the user. A user on a public resolver may be routed by the resolver's location (the EDNS Client Subnet extension helps where it is supported).
  • Failover is limited by TTL caching. Lower the TTL to 60 seconds and some resolvers and clients still hold the old answer for longer.

Anycast announces the same IP from many locations over BGP, the internet's routing protocol. The network itself delivers each packet to the topologically nearest site. Failover is fast: a site withdraws its route and traffic shifts within seconds, with no DNS caches involved. Cloudflare, Google Cloud's global external load balancers, and AWS Global Accelerator all use anycast. It suits short connections and edge proxies best: if routes change mid-connection, packets can land at a different site, so anycast front ends usually terminate TCP at the nearest edge and then proxy to the origin over the provider's own network.

GeoDNSAnycast
How users are steeredDifferent IP per DNS answerSame IP, BGP picks the nearest site
Failover speedBounded by DNS TTLs and cachingSeconds (route withdrawal)
GranularityPer resolver locationPer network path
Effort to runLow, any DNS providerHigh to build yourself; usually bought as a service
Typical useMulti-region apps, active-passive regionsCDNs, DNS providers, global edge proxies

The two combine: anycast to the nearest edge, then the edge picks a healthy region. The DNS, CDNs, and Client Caching lesson goes deeper on the edge side.

Where load balancers fail

The load balancer is on the path of every request, so its failure modes are your failure modes.

The LB as a single point of failure. A self-hosted pair (HAProxy or Nginx with keepalived) runs active-passive: the active node holds a floating virtual IP, the passive node watches its heartbeat (VRRP), and takes the IP over when the heartbeat stops. Failover takes a second or two, and any connections on the old node drop. Managed LBs hide this: they run many nodes across zones and scale them for you. They still have limits. A sudden 10x traffic spike can arrive faster than a managed LB scales, which is why providers have historically offered pre-warming for planned launches. Check your provider's current guidance.

Long-lived connections pin load. Balancers balance connections, not requests. With HTTP request traffic that is fine because connections are short or carry many small requests. With WebSockets, gRPC streams, or database connection pools, a connection can live for hours. Scale out from 4 servers to 8 during a spike and the 4 new servers get nothing, because every existing client is still attached to the old ones. Deploys cause the reverse problem: drain one server and its 50,000 clients all reconnect within the same second, a thundering herd that can knock over the next server.

Fixes that teams actually use:

  • Give connections a maximum age (say 30 to 60 minutes, with random jitter) so clients reconnect gradually and rebalance onto new servers.
  • Make clients reconnect with exponential backoff and jitter, never in a tight loop.
  • For gRPC, balance per request on the client side or with an L7 proxy that understands HTTP/2 streams, rather than per connection.
  • Use least connections for WebSocket pools, combined with slow start.

Retry storms. L7 balancers can retry a failed request on another server. That is great for one flaky instance and terrible during an overload, where every retry adds load to a fleet that is already drowning. Cap retries (Envoy's retry budgets are a good model) and only retry idempotent requests.

Key terms
load balancer
Spreads incoming requests across a pool of identical backend servers and routes around failed ones.
health check
A periodic probe (e.g. GET /healthz) the LB uses to decide whether a server should get traffic.
stateless server
Keeps no user data in memory between requests, so any server can handle any request.
sticky session
Pinning a user to one server. Works, but skews load and loses sessions when that server dies.
L4 vs L7
L4 forwards TCP/UDP connections by IP and port; L7 reads HTTP and can route by path, header, or cookie.
API gateway
The front door to many services: routing, auth, rate limiting, and metering in one place.
power of two choices
Pick two backends at random and send the request to the less loaded one. Avoids herding when balancers share stale load data.
connection draining
Stop sending new requests to a server but let in-flight ones finish before it is removed.
slow start
Ramping a newly healthy server's share of traffic up gradually so it can warm caches and JIT before full load.
anycast
Announcing one IP address from many sites so the network routes each user to the nearest one.