Courses / System Design Interview / Chapter 7
Module 2 · Building Blocks I: Names, Traffic and Data · Chapter 7 of 49
Load Balancers
Builds on Core Concepts: RPCs, Consistency, Failures and Time, Non-Functional Requirements: Availability, Scale, Latency and More, Building Blocks: The Parts Every Design Reuses and DNS: Turning Names into Addresses. Next up: Databases: Choosing, Replicating and Partitioning.
Part 1 · Why load balancers exist and where they sit
One address, many servers
A single server has a ceiling on how many requests it can handle, and when it fails the service is gone. A load balancer is the component that spreads incoming requests over a group of servers, so that clients see one address and the group behaves like one bigger, more reliable machine.
Three things make a balancer worth its extra hop. It lets you add capacity by adding servers behind it instead of buying a bigger one. It hides a failed server: when one stops answering, the balancer stops sending it requests and users do not notice. And it lets you deploy a new version one server at a time, by taking a server out of rotation, updating it, and putting it back.
The group behind a balancer is usually called a pool or a backend, and each member is a target. For the balancer to treat the targets as interchangeable, the servers should be stateless, as the non-functional chapter explained: a request can go to any of them because no server holds something the others lack. State, such as a user's cart, lives in a database or cache that every server can reach.
Balancers appear at more than one place in a design, and each place has its own job.
| Place | Sits between | Why it is there |
|---|---|---|
| Front door | Clients and the web servers | One public address, TLS, spreading internet traffic |
| Between tiers | Web servers and app servers | Lets each tier scale and fail on its own |
| In front of data | App servers and read replicas | Spreads reads across copies of a database |
| Global |
Layer 4 and layer 7
A balancer can look at a request on two different levels. The names come from a model of networking in layers. Layer 4 is the transport layer: TCP and UDP connections, seen as addresses and port numbers. Layer 7 is the application layer: HTTP requests, seen as a method, a path, headers and cookies.
A layer 4 balancer decides from the connection alone. It picks a target when a connection opens and then passes the bytes through, without reading them. It is simple and fast, and it works for any protocol built on TCP or UDP. A layer 7 balancer reads each HTTP request before choosing a target. That costs more work per request, and it buys useful powers.
| Layer 4 | Layer 7 | |
|---|---|---|
| Sees | Addresses, ports, connection | Method, path, headers, cookies, body |
| Can route by | Which connection | URL path, host name, header, cookie |
| Can end TLS | Some can, but they still route by connection | Yes, and then read the plain request |
| Can retry on another target | Only if the connection to a target fails to open | Yes, a whole request at a time |
| Cost per request | Low | Higher |
A layer 7 balancer can send /api/ to one pool and /images/ to another, add a header, or retry a failed request on a second target. A layer 4 balancer cannot, but it can carry traffic that is not HTTP at all, such as a database protocol or a game. Many designs use both: a layer 4 balancer at the edge handles raw volume and hands traffic to a layer 7 tier that does the routing.
The two layers in code
The difference is easy to see with two tiny balancers in front of two pools, api and images. The layer 4 one picks a pool the moment a connection opens, taking turns, and then copies bytes both ways without reading them. The layer 7 one reads the request line first and picks the pool from the path. A TCP relay that never parses the bytes stands in for layer 4 here; production layer 4 balancers often work on packets instead, but they make the same choice with the same information. The program runs on Python 3.12.10 with backends on ports 55446 and 55447 and the two balancers on 55448 and 55449.
import asyncio import itertools POOLS = {"api": 55446, "images": 55447} turn = itertools.cycle(POOLS) async def backend(name): async def handle(r, w): await r.readline() w.write(name.encode()) # say which pool answered await w.drain() w.close() return await asyncio.start_server(handle, "127.0.0.1", POOLS[name]) async def pipe(src, dst): while data := await src.read(4096): dst.write(data) dst.write_eof() # pass the end of the stream along async def relay(r, w, pool, first=b""): br, bw = await asyncio.open_connection("127.0.0.1", POOLS[pool]) bw.write(first) await asyncio.gather(pipe(r, bw), pipe(br, w)) bw.close() w.close()
layers.py, part 1: two pools and a relay that copies bytes
async def layer4(r, w): # chooses when the connection opens await relay(r, w, next(turn)) async def layer7(r, w): # reads the request line, then chooses line = await r.readline() path = line.split()[1] pool = "images" if path.startswith(b"/images/") else "api" await relay(r, w, pool, first=line) async def get(port, path): r, w = await asyncio.open_connection("127.0.0.1", port) w.write(f"GET {path} HTTP/1.1\r\n".encode()) w.write_eof() return (await r.read()).decode() async def main(): servers = [await backend(n) for n in POOLS] servers += [await asyncio.start_server(layer4, "127.0.0.1", 55448), await asyncio.start_server(layer7, "127.0.0.1", 55449)] for path in ["/api/orders", "/api/cart", "/images/logo.png", "/images/banner.png"]: print(f"{path:19} layer 4 -> {await get(55448, path):7}" f" layer 7 -> {await get(55449, path)}") for s in servers: s.close() asyncio.run(main())
layers.py, part 2: the two ways to choose, and four requests
/api/orders layer 4 -> api layer 7 -> api /api/cart layer 4 -> images layer 7 -> api /images/logo.png layer 4 -> api layer 7 -> images /images/banner.png layer 4 -> images layer 7 -> images
One real run. The output is the same on every run.
Part 2 · Round robin and weighted round robin
A proxy and three backends
The simplest rule for choosing a target is round robin: send each request to the next server in a fixed order, and start over at the end. It needs no information about the servers, which is why many balancers use it by default. The nginx documentation says it is what you get when no method is configured.
To see it work, the programs in this chapter build a small layer 7 proxy with Python's asyncio. The programs run on Python 3.12.10, with three local backends on ports 55442 to 55444 and the proxy on 55445. The first file holds the three backends, each a tiny HTTP server that waits a set delay and answers ok, and a counter of how many requests each served.
import asyncio from collections import Counter hits, active = Counter(), Counter() PORTS = {"a": 55442, "b": 55443, "c": 55444} async def start_backend(name, delay): async def handle(r, w): await r.readline() await asyncio.sleep(delay) hits[name] += 1 w.write(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok") await w.drain() w.close() return await asyncio.start_server(handle, "127.0.0.1", PORTS[name])
mini.py, part 1: the shared counters and one backend
The second part is the proxy. A client connects to it, it asks a function pick which backend should serve this request, forwards the request line over a new connection and relays the reply. If the backend refuses the connection, the proxy answers 502 Bad Gateway. It also keeps a count of requests in flight per backend, which a later lesson uses. A small get function is the client.
async def start_proxy(pick, port=55445): async def handle(r, w): line = await r.readline() name = pick() active[name] += 1 try: br, bw = await asyncio.open_connection( "127.0.0.1", PORTS[name]) bw.write(line + b"\r\n") w.write(await br.read()) except OSError: w.write(b"HTTP/1.1 502 Bad Gateway\r\n" b"Content-Length: 0\r\n\r\n") active[name] -= 1 await w.drain() w.close() return await asyncio.start_server(handle, "127.0.0.1", port) async def get(port=55445): r, w = await asyncio.open_connection("127.0.0.1", port) w.write(b"GET / HTTP/1.1\r\n\r\n") return (await r.readline()).split()[1].decode()
mini.py, part 2: the proxy, and a client function
Taking turns, and weights
With the proxy in place, round robin is one line: an endless cycle over the backend names. The script starts three backends that each take 10 ms, sends nine requests through the proxy and counts where they landed.
import asyncio import itertools from mini import * async def main(): servers = [await start_backend(n, 0.01) for n in "abc"] order = itertools.cycle("abc") proxy = await start_proxy(lambda: next(order)) codes = [await get() for _ in range(9)] print("statuses:", dict(Counter(codes))) print("per backend:", dict(sorted(hits.items()))) for s in servers + [proxy]: s.close() asyncio.run(main())
rr.py: nine requests, three backends
statuses: {'200': 9}
per backend: {'a': 3, 'b': 3, 'c': 3}On this machine, Python 3.12.10, with asyncio and three local backends on ports 55442 to 55444 and the proxy on 55445.
Each backend served three requests, which is what the rule promises. Round robin treats every request as the same size and every server as the same strength. When the servers differ, give the stronger one a larger share with a weight. In nginx every server has a weight, 1 by default. With weights 3, 1 and 1, three of every five requests go to the first server and one to each of the others.
The same effect needs only a longer cycle. This variant of rr.py replaces the cycle with aaabc, so server a appears three times in five, and sends ten requests.
order = itertools.cycle("aaabc")weighted.py: the one changed line; the rest is rr.py
statuses: {'200': 10}
per backend: {'a': 6, 'b': 2, 'c': 2}Server a served six of the ten requests and the others two each, which matches the 3-1-1 split. The fixed cycle has a flaw: a receives three requests in a row, then none for two.
Spreading the heavy server out
A fixed cycle such as aaabc gets the shares right but bunches the heavy server's turns. A better order spreads them out. One common way is smooth weighted round robin: on every pick each server adds its weight to a running score, the highest score wins, and the winner gives back the total of all weights.
def smooth(weights, n): """Smooth weighted round robin: spread the heavy server out.""" current = dict.fromkeys(weights, 0) total = sum(weights.values()) for _ in range(n): for name, w in weights.items(): current[name] += w # everyone earns its weight best = max(current, key=current.get) current[best] -= total # the winner pays the total yield best print("fixed cycle:", "aaabc" * 2) print("smooth :", "".join(smooth({"a": 3, "b": 1, "c": 1}, 10)))
swrr.py: smooth weighted round robin against the fixed cycle
fixed cycle: aaabcaaabc smooth : abacaabaca
Python 3.12.10. No randomness, so the same on every run.
Both orders give a six picks out of ten, but the smooth one never gives it more than two in a row, and b and c come up between. Over a long run the shares are exactly the weights; over a short burst no server is hit harder than its weight implies.
Round robin gives each of three backends one third of the requests. When is that unfair?
- When the servers differ in power, or the requests differ in cost. A weak server receives as much as a strong one.
- Weights fix the first case, and least connections, in the next lesson, helps with the second.
With weights a=3, b=1, c=1 and ten requests, how many requests does a serve?
- Six: three of every five requests go to a, and ten requests are two rounds.
- The run above printed
a: 6, b: 2, c: 2.
A new server is twice as powerful as each of the two old ones. What weights do you give, and what order would smooth weighted round robin produce?
- Weights 2, 1 and 1, so the new server gets half of the requests.
Part 3 · Least connections and two random choices
When requests differ in cost
Round robin spreads requests, but it does not spread work. If some requests take 20 ms and a few take 300 ms, a server that happens to receive several slow ones falls behind while its neighbours sit idle. A rule that watches the real load does better.
Least connections sends each new request to the target with the fewest requests in flight. A server that is slow, because its requests are slow or because it is weaker, holds its requests longer, so its count stays high and it is picked less often. nginx names this method least_conn and says it tries not to overload a busy server.
The cost is that the balancer must keep a count per target, and keep it correct as requests finish. The proxy in this chapter does that in active. A related rule, least request, counts requests rather than connections, which differs when a connection carries many requests.
Watch for the counts: the balancer tracks requests in flight per server
Read it as steps
A model of the counts: server 1 is busy with long requests, so least connections sends new requests to the servers with fewer in flight.
Comparing the rules on a slow server
The experiment sends 30 requests, one every 20 ms, through the proxy while server c takes 300 ms per request and a and b take 20 ms. It repeats the run with round robin, with least connections and with a third rule explained below, and prints where requests went and the mean and maximum time per request.
import asyncio import itertools import random import statistics import time from mini import * async def timed(delay): await asyncio.sleep(delay) t = time.perf_counter() await get() return (time.perf_counter() - t) * 1000 async def run(label, pick): hits.clear() delays = {"a": 0.02, "b": 0.02, "c": 0.3} # c is slow servers = [await start_backend(n, delays[n]) for n in "abc"] proxy = await start_proxy(pick) ms = await asyncio.gather(*[timed(i * 0.02) for i in range(30)]) print(f"{label:12} {dict(sorted(hits.items()))} " f"mean {statistics.mean(ms):.0f} ms, max {max(ms):.0f} ms") for s in servers + [proxy]: s.close()
least.py, part 1: the harness
order = itertools.cycle("abc") asyncio.run(run("round robin", lambda: next(order))) asyncio.run(run("least conns", lambda: min("abc", key=lambda n: active[n]))) random.seed(7) asyncio.run(run("two choices", lambda: min(random.sample("abc", 2), key=lambda n: active[n])))
least.py, part 2: the three rules
round robin {'a': 10, 'b': 10, 'c': 10} mean 126 ms, max 321 ms
least conns {'a': 20, 'b': 10} mean 32 ms, max 33 ms
two choices {'a': 15, 'b': 12, 'c': 3} mean 60 ms, max 309 msOn this machine, Python 3.12.10, with asyncio and three local backends on ports 55442 to 55444 and the proxy on 55445. Timings and splits vary between runs.
Round robin gave each server 10 requests, so a third of all requests waited 300 ms and the mean was 126 ms. Least connections served 20 requests from a and 10 from b, and none from c. When a request arrived, a was usually free, and the rule takes the first lowest count, so a won every tie; b took the requests that came while a was still busy. The mean fell to 32 ms, and the maximum from 321 ms to 33 ms. The run was repeated four times on this machine. Three runs looked like this one; in the fourth, least connections sent one request to c at a moment when a and b were both busy, and that request took 320 ms.
Power of two choices
The third rule is power of two choices. It picks two targets at random and sends the request to the one with fewer requests in flight. Envoy's documentation says its least request balancer does this by default, sampling two hosts. The slow server is not shut out, since the sample can include it, but three of the 30 requests landed on c instead of ten. The maximum stayed high because those three still waited, and the mean, 60 ms, sat between the other two rules. In return the balancer looks at two counters instead of all of them, which matters when the pool has hundreds of targets or when several balancers share a pool and would otherwise all choose the same lowest server at the same moment.
In the run shown, least connections never picked server c, yet in another run it picked c once. What explains both?
- The rule reacts to counts at the moment a request arrives. Usually
aorbhad fewer requests in flight thanc, so they won. - Once, both were busy at that instant,
chad the lowest count, and the request landed on the slow server.
What does power of two choices save compared with least connections?
- It reads two counters per request instead of scanning every target.
- It also avoids several balancers all picking the same lowest server at once.
Which request counts does least connections need to keep correct?
- The number of requests in flight for each target, going up when a request is sent and down when it finishes.
- If it forgets to decrement after a failure, a server looks busier than it is.
Part 4 · Health checks
Active and passive checks
A balancer that keeps sending requests to a dead server turns one failure into many failed requests. It needs to know which targets are alive. There are two ways to learn that, and good setups use both.
An active health check is a probe the balancer sends on a timer, such as GET /healthz every few seconds. A target that fails several probes in a row is taken out of rotation, and one that passes again is put back. A passive health check watches real traffic instead. If requests to a target fail or time out, the balancer counts the failures and ejects the target when they pile up. Open-source nginx works this way. Its max_fails setting is the number of failed attempts within a window set by fail_timeout that mark a server unavailable, and the server then stays out for that same window. The defaults are one failure and 10 seconds. Periodic active checks are part of nginx's commercial subscription.
| Active | Passive | |
|---|---|---|
| How it learns | Probes on a timer | Watches real requests |
| Speed to notice | The probe interval times the failures needed | As soon as enough real requests fail |
| Extra load | A steady trickle of probes | None |
| Can bring a target back | Yes, probes keep running | Needs a probe or a timer to try again |
In Kubernetes (Pods behind a Service) the same split exists. A readiness probe decides whether a Pod receives traffic, and a failing probe removes the Pod's address from the Service's endpoints without restarting it. A liveness probe decides whether to restart the container. Keep the two apart: a server that is merely busy should fail readiness, not liveness. For a server that is slow to start, Kubernetes has a third kind, the startup probe: until it succeeds, the liveness and readiness probes do not run, so a slow start is not mistaken for a hang.
A backend that dies mid-run
The proxy needs a pool that can eject and readmit a target. The first file keeps a list of healthy backends, picks round robin over that list, counts failures per backend, and ejects one after its third failure. It also defines an active probe that simply tries to connect.
import asyncio import itertools from mini import * healthy, fails, ring = ["a", "b", "c"], Counter(), itertools.count() def pick(): pick.last = healthy[next(ring) % len(healthy)] return pick.last async def probe(name): # active check: can we connect? try: _, w = await asyncio.open_connection("127.0.0.1", PORTS[name]) w.close() return True except OSError: return False def passive(i, status): # passive check: count real failures if status != "502": return fails[pick.last] += 1 if fails[pick.last] == 3: healthy.remove(pick.last) print(f"request {i}: {pick.last} ejected after 3 failures")
health.py: the pool, a probe and the passive check
The second file drives it. It sends 24 requests one after another. At request 6 backend c is shut down, at request 16 it is started again, and every fourth request the program probes c if it is out of the pool.
import asyncio from health import * async def main(): servers = {n: await start_backend(n, 0.005) for n in "abc"} proxy = await start_proxy(pick) statuses = Counter() for i in range(1, 25): if i == 6: servers["c"].close() print("request 6: c goes down") if i == 16: servers["c"] = await start_backend("c", 0.005) print("request 16: c is back") status = await get() statuses[status] += 1 passive(i, status) if i % 4 == 0 and "c" not in healthy and await probe("c"): healthy.append("c") fails.clear() print(f"request {i}: probe ok, c readmitted") print("client saw:", dict(statuses)) for s in [*servers.values(), proxy]: s.close() asyncio.run(main())
health_run.py: kill c, bring it back
request 6: c goes down request 12: c ejected after 3 failures request 16: c is back request 16: probe ok, c readmitted client saw: {'200': 21, '502': 3}
On this machine, Python 3.12.10, with asyncio and three local backends on ports 55442 to 55444 and the proxy on 55445.
Backend c went down at request 6. The next requests that the rotation sent to c failed with a 502, and after the third failure, at request 12, it was ejected. The three failed requests are the price of passive checking: a user saw each of them. Of the 24 requests the client sent, 21 got a 200 and 3 got a 502. After c restarted at request 16 the probe at the same step found it, and it rejoined.
Part 5 · Sticky sessions, hashing and TLS
Keeping a client on one server
Stateless servers make balancing easy, but some designs keep state on the server for a while: a login session in memory, a half-uploaded file, a game room. The next request from that user must then reach the same server. Making that happen is session affinity, also called sticky sessions.
There are two common ways. The balancer can add a cookie that names the target and follow it on later requests. Or it can compute the target from the client's address: nginx's ip_hash uses the client's address as a hashing key, so requests from the same client go to the same server unless that server is unavailable. Read the detail: for IPv4 it hashes only the first three parts of the address, so every client in one /24 block, such as a whole office behind one gateway range, lands on the same server.
Stickiness has a cost. A busy user pins load to one server, and the balancer can no longer even out the work. When the server dies the session is lost unless it was also stored elsewhere. Most designs prefer to keep sessions in a shared store, so that any server can handle any request, and use stickiness only where state is expensive to move.
Hashing by key is the general form of this idea. If you pick the target from a hash of the key, the same key always goes to the same server, which is also how a cache tier is spread. The question is what happens when the pool changes.
What hashing does when a server leaves
The simplest scheme is hash(key) mod N, where N is the number of targets. It works until N changes. Removing one server of three changes the divisor, and almost every key lands on a different server. For a cache tier that is a flood of misses.
Consistent hashing avoids the reshuffle. Each target is placed at many points on a ring, using a hash of its name and a number. A key is hashed onto the same ring and belongs to the next point clockwise. If a target leaves, only the keys that belonged to its points move, to their next neighbours. Envoy's ring hash balancer is this scheme, and its documentation says that adding or removing one host from a set of N affects only 1/N of the requests.
The program places 10,000 client addresses on both schemes with three servers, removes server c, and counts how many clients change server. It uses 100 points per server on the ring.
import bisect import hashlib def h(s): return int(hashlib.md5(s.encode()).hexdigest(), 16) def build(nodes, vnodes=100): points = sorted((h(f"{n}#{i}"), n) for n in nodes for i in range(vnodes)) return [p for p, _ in points], [n for _, n in points] def owner(ring, key): keys, names = ring return names[bisect.bisect(keys, h(key)) % len(keys)] users = [f"10.0.{i // 250}.{i % 250}" for i in range(10_000)] mod3 = {u: ["a", "b", "c"][h(u) % 3] for u in users} mod2 = {u: ["a", "b"][h(u) % 2] for u in users} r3, r2 = build("abc"), build("ab") ring3 = {u: owner(r3, u) for u in users} ring2 = {u: owner(r2, u) for u in users} moved = lambda x, y: sum(x[u] != y[u] for u in users) / len(users) print(f"hash mod N, c leaves: {moved(mod3, mod2):.0%} of clients move") print(f"hash ring, c leaves: {moved(ring3, ring2):.0%} of clients " "move") strays = sum(ring3[u] != ring2[u] and ring3[u] != "c" for u in users) print(f"ring movers that were not on c: {strays}")
ring.py: hash mod N against a hash ring
hash mod N, c leaves: 66% of clients move hash ring, c leaves: 33% of clients move ring movers that were not on c: 0
Python 3.12.10. The hash is MD5, so the output is the same on every run.
With mod N, 66 percent of the clients moved, about two thirds. That is what the arithmetic predicts: a key keeps its server only when its hash gives the same answer mod 3 and mod 2, which happens for two of every six values. With the ring, 33 percent moved, and the last line checks that every one of them had been on c. Only the clients that had to move did. This is the property that makes the ring useful for caches and for any pool where servers come and go. MD5 is used here only to spread keys evenly; it is not doing any security work.
Ending TLS at the balancer
Most traffic is encrypted with TLS. A balancer can pass the encrypted stream straight through to the servers, or it can end TLS itself: it holds the certificate, decrypts the request, and forwards plain HTTP, or opens a fresh encrypted connection to the server. Ending TLS at the balancer is TLS termination.
It has clear benefits. The certificate and its private key live in one place instead of on every server. The expensive handshake is done once, at the edge. And a layer 7 balancer needs the plain request to route by path or header, which is only possible after decryption. The cost is that the traffic behind the balancer is not encrypted unless you re-encrypt it, so the network between balancer and servers must be trusted, or the second hop must use TLS as well.
| Term | Meaning |
|---|---|
| Load balancer | A component that spreads requests over a pool of servers |
| Layer 7 balancer | One that reads the HTTP request before choosing a target |
| Health check | A probe or a failure count used to decide if a target may get traffic |
| Sticky session | Routing a client's requests to the same server |
| Consistent hashing | A scheme where a change of pool moves only a small share of keys |
| TLS termination | Decrypting at the balancer instead of at each server |
Why does hash(key) mod N move so many keys when N changes from 3 to 2?
- The divisor changes for every key, so most keys map to a new server. The run moved 66 percent of the clients.
- A ring moves only the keys that belonged to the removed server.
Part 6 · Global balancing and the balancer as a single point of failure
Local and global balancing
Everything so far spreads requests among servers in one place. Local balancing works inside one data centre or region. Global balancing decides which region a user goes to in the first place, using the user's location, the health of each region and sometimes its load.
| Local | Global | |
|---|---|---|
| Chooses between | Servers in one site | Whole sites or regions |
| Typical tools | Layer 4 and layer 7 balancers | DNS answers, anycast routing |
| Reacts in | Seconds, to a failed probe | Up to the TTL with DNS; as fast as routes change with anycast |
| Main goal | Even load, hidden failures | Low latency, surviving a region outage |
DNS is the usual global tool, because an answer can differ by the asker's location and can leave out a region that failed its checks. Its weakness, covered in the dns chapter, is that cached answers keep sending users to the old address for a while. Anycast routing sends each user's packets to the nearest site, in routing terms, that announces the same address, and moves them when a site stops announcing it.
Who balances the balancer
A balancer in front of ten servers is itself a server. If it fails, all ten become unreachable, so a single balancer turns a redundant design back into a single point of failure. The standard answer is to run more than one.
In an active-passive pair, two balancers share a virtual address. The active one serves traffic and the passive one watches it. If the active balancer stops answering, the passive one takes over the address. A standard protocol for this, VRRP (RFC 5798), has the active machine send regular announcements; the standby takes over when they stop. The standby is idle most of the time, and failover takes as long as the standby needs to be sure the active one is gone. In an active-active setup, several balancers all serve traffic, with the network or DNS spreading clients across them. Maglev takes this route: routers spread packets over many Maglev machines, and each machine combines connection tracking with consistent hashing, which the paper describes as limiting the disruption that failures cause to existing connections.
Two more habits keep the balancer from becoming the bottleneck. Keep its work small: a layer 4 tier is far cheaper per request than a layer 7 tier. And watch it as you watch any service, with its own health checks, its own capacity limits and an alert before it saturates.
A standby in code
The program below models an active-passive pair on this machine. One port stands in for the pair's shared address. Balancer lb1 answers on it; a standby checks every 100 ms whether the port still answers, and after three missed checks in a row it starts lb2 on the same port. A client sends a request every 50 ms with a 200 ms timeout, and lb1 is stopped half a second in. Python 3.12.10, port 55450.
import asyncio import time SHARED = 55450 # stands in for the pair's shared address t0 = time.perf_counter() now = lambda: time.perf_counter() - t0 async def balancer(name): async def handle(r, w): await r.readline() w.write(f"{name}\n".encode()) await w.drain() w.close() return await asyncio.start_server(handle, "127.0.0.1", SHARED) async def reachable(timeout): try: conn = asyncio.open_connection("127.0.0.1", SHARED) _, w = await asyncio.wait_for(conn, timeout) w.close() return True except (OSError, asyncio.TimeoutError): return False
standby.py, part 1: a balancer and a check
async def standby(): misses = 0 while misses < 3: # 3 missed checks in a row await asyncio.sleep(0.1) # check every 100 ms misses = 0 if await reachable(0.1) else misses + 1 print(f"{now():.2f} s standby: 3 checks missed, takes the address") return await balancer("lb2") async def client(results): for _ in range(30): try: conn = asyncio.open_connection("127.0.0.1", SHARED) r, w = await asyncio.wait_for(conn, 0.2) w.write(b"GET /\n") reply = (await r.readline()).decode().strip() results.append(reply or "dropped") w.close() except (OSError, asyncio.TimeoutError): results.append("no answer") await asyncio.sleep(0.05)
standby.py, part 2: the standby and the client
async def main(): active, results = await balancer("lb1"), [] watch = asyncio.create_task(standby()) asking = asyncio.create_task(client(results)) await asyncio.sleep(0.5) active.close() # the active balancer dies print(f"{now():.2f} s lb1 stops answering") lb2 = await watch await asking start = 0 for i in range(1, len(results) + 1): if i == len(results) or results[i] != results[start]: span = f"{start + 1}-{i}" if i > start + 1 else f"{i}" print(f"requests {span:5}: {results[start]}") start = i lb2.close() asyncio.run(main())
standby.py, part 3: the failure, and a summary of what the client saw
0.51 s lb1 stops answering 1.08 s standby: 3 checks missed, takes the address requests 1-9 : lb1 requests 10 : dropped requests 11-13: no answer requests 14-30: lb2
One real run. The exact request numbers vary by one or two between runs.
Tuning the failover
The numbers in the program are the design's dials. Checking more often, or giving up after fewer misses, shortens the gap, but it raises the chance that a brief pause on a healthy active balancer is taken for a failure, and then both machines claim the address, the split brain described in the core concepts chapter. Real pairs guard against that with a clear priority between the two and with announcements on a network the two share.
A common shape is DNS or anycast to pick the region, a layer 4 tier for raw volume, a layer 7 tier for routing and TLS, and servers behind that, each with health checks.
In the run, three requests timed out and one was dropped during the failover. How would you shorten that gap, and what does it risk?
- Check more often or take over after fewer misses. Here three checks of about 200 ms each set a gap of about 0.6 seconds.
- The risk is a false takeover: a healthy but briefly slow active balancer is declared dead, and both claim the address.
Why is DNS a slow way to remove a failed region?
- Resolvers and clients cache the old answer until its TTL expires, so some users keep trying the failed region.
- Anycast withdraws the route, which reacts faster.
A pool of 10 servers sits behind one balancer. What is the availability limit of the whole service?
- The balancer's own availability, since every request passes through it and the servers cannot make up for it.
- Two balancers in parallel raise that ceiling.