Design a Load Balancer
medium 45 minSpread a shop's 100,000 requests a second over many servers.
See it run
One proxy and three servers: choosing, counting, hashing, probing and stopping a server gently.
Operations
Round robin request
From the name to the reply, with the next server in turn.
Step 1 of 6
Find the address
DNS
one address
DNS answers shop.example with one address. The client remembers it.
Step 1: Find the address
def handle(request): server = healthy[index % len(healthy)] index += 1 conn = pools[server].borrow() request.headers["X-Forwarded-For"] = client_ip response = conn.send(request, timeout=1.0) pools[server].give_back(conn) return response- Choice
- O(1)
- Keeps
- an index
Weights 3, 2 and 1 send half, a third and a sixth of the requests.
In the real world
The same design a load balancer doing real jobs. Pick one and step through it.
The balancer of balancers fails too.
Step 1 of 4
A flow through A
The router sends this client's packets to node A, whose table says proxy 2.
Step 1: A flow through A
Common mistakes
The bugs interviewers watch for, with the fix beside each.
One balancer in front of many servers
criticalIt is now the single point of failure.
Wrongshop.example A 203.0.113.10 # one proxyRightshop.example A 203.0.113.10 # address announced # by three layer 4 nodesConnection counts in a remote store
majorTwo writes and a trip for each request, and a new dependency.
Wrongredis.incr("conns:" + server)Rightserver.in_flight += 1 # this proxy's memoryRetrying everything
criticalA repeated payment is a second payment, and retries multiply an outage.
Wrongexcept ConnectionReset: return send(request)Rightif request.idempotent and budget.take(): return send(request, other_server)A ready check that asks every dependency
criticalOne slow database removes all servers at the same moment.
Wrongdef ready(): return database.ping() and search.ping()Rightdef ready(): return warmed_up and queue_len < LIMITTrusting X-Forwarded-For from a client
majorAnyone can write any address there.
Wrongip = request.headers["X-Forwarded-For"]Rightip = connection.peer_address# trust the header only from our own proxies
Interview tips
Lead with numbers
- 100K a second at peak, 33K average.
- Nine proxies and thirty servers in three zones.
- 1.6 Gb/s in, 8 out.
Separate the planes
- Requests never wait for the control plane.
- Versions, slow rollout, one-step rollback.
- Last good version if cut off.
Plan the failure
- Server: ejected in about a second.
- Proxy: layer 4 bypasses it.
- Zone: six of nine remain.
Change gently
- Drain, then stop.
- Slow start, then full weight.
- Retries within a budget.