To design a load balancer is to decide how a stream of connections and requests is spread over many servers, how the balancer notices a sick server, how it changes its configuration without dropping traffic, and how it survives its own failures. A good answer separates the data plane (the path every request takes) from the control plane (the rules that change slowly), and uses numbers to justify each choice.

This lesson designs the balancer for BusTrack, the bus tracking app from Load Balancing: Introduction, after it grows from one city to the whole country. Six runnable programs in Java, with Python and C++ versions, test the decisions that interviewers usually probe: choosing a backend without moving flows around, health checks, retries, the routing table, losing a balancer node, and finally the whole design under failure. Capacities and timings in the programs are assumptions chosen to make the comparisons clear, not benchmarks of a real product.

Key takeaways

  • A Maglev lookup table balanced 8 backends to within one slot (8,192 to 8,193 of 65,537), and when one backend left only 12.6% of flows moved. Hashing with modulo moved 87.4%.

  • If health checks fail by chance, a balancer that removes failing backends can empty its own pool. At a 50% chance of failed probes, it dropped 31.4% of requests with no safety rule and 10.5% with a panic rule that uses every backend when too few look healthy.

  • The panic rule backfires when backends really are dead: with 4 of 10 dead it dropped 40.0% against 14.9% without it. Panic is a trade, not a fix.

  • Retrying every failure turned a 20 second dip into an outage that never ended (46.3% served, 80 seconds still over capacity afterwards). A retry budget of 10% of new requests served 96.4%.

  • A routing trie needed 3.8 steps per request against 2,241 for a scan of 2,241 rules.

  • When a balancer node failed, plain hash-modulo ECMP moved 83.2% of flows. Resilient hashing moved 16.8%, and none from healthy nodes.

  • In the full run, the designed balancer matched the naive one on requests served (98.9%) but sent 5 attempts to a dead backend instead of 914, and removing the ejection limit dropped served requests to 90.9%.

1. Clarifying Requirements

Start by agreeing on scope with the interviewer. For BusTrack the answers might look like this.

Functional requirements

  • Spread HTTPS requests and long-lived WebSocket connections over a pool of API servers.

  • Detect unhealthy servers and stop sending them traffic, then bring them back when they recover.

  • Route by path (for example /v1/trips/... and /v1/stops/...) to different pools.

  • Let operators add, drain and remove servers and change rules without dropping connections.

  • Terminate TLS so the servers see plain traffic.

Non-functional requirements

  • 120,000 requests per second at peak, plus 300,000 open tracking sockets.

  • No single point of failure, including the balancer itself, and the loss of any one balancer node must not overload the others.

  • A few milliseconds of added latency at most.

  • A bad configuration must be easy to undo.

Say out loud what is out of scope, for example global traffic steering (that is Anycast Routing and DNS Load Balancing) and web application firewall rules.

2. Back-of-the-Envelope Estimation

These are assumptions you state, then check. Change any of them and the answer changes.

  • Traffic: peak 120,000 requests per second. At 200 requests per second per server that is 600 servers.

  • Bandwidth: a request is about 1.5 KB and a response about 6 KB (a bus position list). Ingress is 120,000 × 1.5 KB = 180 MB/s, or 1.44 Gbit/s. Egress is 120,000 × 6 KB = 720 MB/s, or 5.76 Gbit/s. A pair of 10 Gbit/s links per balancer node is plenty, so bandwidth is not the constraint.

  • Connections: an API call lasts about 80 ms, so about 120,000 × 0.08 = 9,600 are in flight. The 300,000 tracking sockets at 400 bytes of state each are 120 MB across the fleet, a small number.

  • Health checks: 6 balancer nodes probing 600 servers every 5 seconds is 720 probes per second, 0.6% of the request rate.

  • Node count: if one layer 7 node handles 25,000 requests per second with TLS, 120,000 needs 4.8, so 5 nodes at 96%. One failure then pushes the other four to 120%, so plan 6 nodes (80% normally, 96% after a failure), and 7 if you want to survive a failure during a deploy.

The conclusion matters more than the arithmetic: the design is limited by CPU for TLS and by failure headroom, not by bandwidth or memory, and the control plane carries almost no traffic.

3. Core APIs

The data plane has no API: it is the traffic itself. The control plane needs a small, safe interface. Two ideas keep it safe: send the whole desired state as a numbered version, and let a node switch to a new version in one step.

Replace a pool: PUT /v1/pools/bustrack-api

{
  "version": 41,
  "algorithm": "power_of_two",
  "members": [
    {
      "id": "hyd-api-1",
      "address": "10.20.4.11:8443",
      "weight": 1
    },
    {
      "id": "hyd-api-2",
      "address": "10.20.4.12:8443",
      "weight": 1
    }
  ],
  "health": {
    "probe_every_s": 5,
    "fail_after": 3,
    "recover_after": 3
  },
  "ejection": {
    "max_out_of_rotation_pct": 25,
    "count": "hard_errors"
  },
  "retry": {
    "budget_pct": 10,
    "max_attempts": 4
  }
}

The server accepts the request only if version is exactly the current version plus one (a compare-and-set). That prevents two operators from silently overwriting each other. The response is 202 Accepted with {"version": 41, "state": "staged"}.

  • POST /v1/pools/bustrack-api/versions/41:activate makes the staged version live on every node. :rollback with an older version number reverts.

  • POST /v1/pools/bustrack-api/members/hyd-api-7:drain stops new connections to one server and lets existing ones finish, up to a deadline you give.

  • GET /v1/pools/bustrack-api/members returns each member with a state (up, down by probe, ejected by traffic, draining), the reason and the time it began. Operators need the reason more than the state.

  • PUT /v1/routes replaces the path routing table, with the same version rule.

4. High-Level Design

Traffic passes through two tiers. A layer 4 tier receives connections from the router and spreads them across layer 7 nodes without looking inside them. A layer 7 tier terminates TLS, reads the request, applies routing rules and picks a server. The tiers scale and fail independently.

The control plane stores the versioned configuration, and every node keeps a read-only snapshot of it in memory. A request reads the current snapshot without taking a lock; when a new version is activated, the node builds the new snapshot on the side and swaps one pointer. Requests that started on the old snapshot finish on it. A separate health checker feeds states into the next snapshot.

The rest of the lesson goes deep into the parts an interviewer is most likely to challenge.

5. Choosing a Backend Without Moving Flows

The layer 4 tier must send every packet of a connection to the same layer 7 node, and the layer 7 tier sometimes needs a server to see the same client again (for caches or sessions). The usual tool is hashing the connection's addresses and ports. The simple form, hash mod N, has a flaw: when N changes almost every flow moves.

Maglev hashing, described by Google for its software load balancer, fixes this with a lookup table. The table has a prime number of slots (we use 65,537). Each backend has its own pseudo-random order in which it would like to claim slots. The backends take turns, each claiming its next unclaimed slot, until the table is full. A flow hashes to a slot and uses the backend in it.

The first program builds the table for 8 backends and compares three schemes on 100,000 flows. The hash is 32-bit FNV-1a followed by the murmur3 finalizer, written with plain integer arithmetic so all three languages agree.

Output

A Maglev table with 65537 slots over 8 backends: fewest slots 8192, most 8193 (ideal 8192).

100000 flows. What happens when the pool changes (flows on a surviving backend that are moved anyway are the damage):
change                      scheme               flows moved   moved from a surviving backend
remove hyd-api-4 (8 to 7)   modulo (hash mod N)  87.4%         75.0%
                            ring, 100 points     12.8%         0.0%
                            Maglev table         12.6%         0.1%
add hyd-api-9 (8 to 9)      modulo (hash mod N)  88.8%         77.7%
                            ring, 100 points     10.7%         0.0%
                            Maglev table         11.1%         0.2%

share of the 100000 flows each backend gets (8 backends)
scheme               lightest   heaviest   heaviest vs fair share
modulo (hash mod N)  12.3%      12.6%      101.0%
ring, 100 points     11.1%      15.1%      121.0%
Maglev table         12.4%      12.6%      101.3%
  • The table balanced exactly: every backend got 8,192 or 8,193 of 65,537 slots.

  • Removing hyd-api-4 moved 87.4% of flows with modulo (75.0% of all flows were moved even though their backend was fine), 12.8% with a 100-point hash ring and 12.6% with Maglev (0.1% extra).

  • Adding a ninth backend moved 88.8% with modulo, 10.7% with the ring and 11.1% with Maglev.

  • Balance is where Maglev beats the ring: the heaviest backend got 101.3% of its fair share, against 121.0% for the ring and 101.0% for modulo.

The cost is rebuilding the table when the pool changes (65,537 slots is cheap, and it is done off the request path). Pair the table with a small connection table that remembers where each established flow went, so even the few flows that would move keep their backend.

6. Health Checks, Ejection and the Panic Rule

A balancer finds out about a sick server in two ways. Active health checks probe each server on a timer. Passive checks (also called outlier detection) watch real traffic and eject a server that returns errors. Both can be wrong, and the damage from a wrong decision grows with the number of servers removed.

The second program has 10 servers that each handle 1,000 requests per second under a load of 7,000. A probe every 5 seconds removes a server after 2 failures in a row and returns it after 2 good probes. First, every server is really fine but a shared dependency makes probes fail by chance. A panic rule says: if fewer than a set share of servers look healthy, ignore the health state and use all of them.

Output

10 backends, each serves up to 1000 requests/s. Load 7000 requests/s. Probes every 5 s for 600 s.
A backend leaves the pool after 2 failed probes in a row and returns after 2 good ones in a row.

A shared dependency makes probes fail by chance. Every backend is really fine.
probe failure chance   avg healthy   fewest healthy   dropped: no panic   panic below 50%   panic below 70%
5%                     9.9           9                0.0%                0.0%              0.0%
20%                    9.3           7                0.0%                0.0%              0.0%
35%                    8.0           4                2.0%                1.6%              0.0%
50%                    4.8           1                31.4%               10.5%             0.0%
65%                    2.5           0                64.5%               1.4%              0.0%

Some backends are really dead (probes also fail by chance 5% of the time).
really dead   dropped: no panic   panic below 50%   panic below 70%
0             0.0%                0.0%              0.0%
1             0.0%                0.0%              0.0%
2             0.1%                0.1%              0.1%
3             0.7%                0.7%              1.2%
4             14.9%               14.9%             40.0%
5             28.9%               29.1%             50.0%
  • At a 5% or 20% chance of a failed probe nothing was dropped. At 35%, 2.0% was dropped without the rule and 0% with panic below 70%.

  • At 50% the pool averaged only 4.8 healthy servers and got down to 1; the no-rule balancer dropped 31.4% of requests. Panic below 50% dropped 10.5% and panic below 70% dropped 0%.

  • At 65% the pool sometimes had no healthy server at all (64.5% dropped without a rule).

  • In the second table some servers are really dead. With 3 dead, no policy dropped more than 1.2%. With 4 dead, the no-rule balancer dropped 14.9% (6 servers had to carry the load) but panic below 70% dropped 40.0%, because it sent traffic to the dead servers too. With 5 dead it dropped 28.9% against 50.0%.

The lesson is to treat ejection as dangerous. Never let health decisions take more than a fraction of the pool out of rotation (a quarter, in our final design), and decide the panic threshold from how likely a false alarm is compared with a real failure. Count only hard errors, such as refused connections, toward ejection: an overloaded but alive server returning busy answers is already telling you something different.

7. Retries and the Retry Budget

When a request fails, trying a different server is often right, because the failure may be a single bad server. But every retry is more load. If the pool is already short of capacity, retries make it worse, and the extra load can keep it overloaded after the original cause has gone. This is called a metastable failure: the system is stuck in a bad state that the trigger no longer explains.

The third program has 6 servers at 1,000 requests per second each and 5,400 new requests per second. For 20 seconds one server is out for a deploy and capacity falls to 5,000. An overloaded pool wastes work, so it serves capacity × capacity ÷ attempts (an assumption that captures queueing and timeouts).

Output

6 backends x 1000 requests/s. 5400 new requests/s for 120 s. One backend is out from second 20 to 40.
A failed attempt can be retried in the next second, up to 3 retries. Overload wastes capacity (it serves capacity x capacity / attempts).

policy                          requests served   attempts per request   busiest second   seconds over capacity after the deploy   last 10 s success
no retries                      97.6%             1.00                   5400             0 s                                      100.0%
up to 3 retries                 46.3%             2.94                   19582            80 s                                     36.2%
3 retries, budget 10% of new    96.4%             1.01                   5940             0 s                                      100.0%
  • With no retries 97.6% of requests were served. The pool recovered the moment the deploy ended.

  • With up to 3 retries for every failure, only 46.3% were served. The busiest second had 19,582 attempts, and 80 seconds after the deploy the pool was still over capacity, with the last 10 seconds serving only 36.2%.

  • With the same 3 retries but a budget of 10% of new requests per second, 96.4% were served, with 1.01 attempts per request and recovery as soon as the deploy ended.

Cap retries as a share of the traffic (10% is a common starting point), retry on a different server, and do not retry requests that are not safe to repeat unless they carry an idempotency key.

8. The Routing Table

A layer 7 balancer matches each request against routing rules, usually by host and path prefix. The longest matching prefix wins. With a handful of rules a loop is fine; with thousands it becomes a cost on every request.

The fourth program has 2,241 rules (40 services, 50 resources each, some with a /search rule, and a default) and 2,000 requests. It compares scanning every rule, scanning from the most specific rule and stopping at the first match, and walking a trie where each node is one path segment.

Output

BusTrack's gateway has 2241 path rules: 40 services x 50 resources, some with a /search rule, and a default rule.
The trie has 2242 nodes. 2000 requests, for example /v1/svc7/res12/item4821 or /v1/svc7/res55/search (that resource has no rule, so the service rule applies).

lookup method                         rules or nodes examined per request   worst case   total for 2000 requests
scan every rule, keep the longest     2241.0                                2241         4482000
scan most specific first, stop at hit 1396.5                                2240         2793156
trie of path segments                 3.8                                   5            7660

requests where the three methods chose different rules: 0
  • Scanning every rule examined 2,241 rules per request.

  • Scanning the most specific first and stopping early examined 1,396.5 on average, and 2,240 in the worst case (a request that matches only a service-level rule has to pass all the longer rules first).

  • The trie walked 3.8 nodes on average and 5 at most. All three methods chose the same rule for every request.

The trie is built when a snapshot is activated, then never changed, which fits the lock-free swap from section 4. A new rule version builds a new trie.

9. Surviving the Loss of a Balancer Node

The router in front of the layer 4 nodes spreads flows over them with ECMP (equal-cost multipath), normally by hashing the flow's addresses and ports. If a node fails and the router recomputes hash mod N, almost every flow changes node, and each moved connection is reset. Resilient hashing keeps a fixed table of buckets and only reassigns the buckets of the node that left.

The fifth program uses 6 nodes and 100,000 flows with 256 buckets. It also adds a seventh node, then prints the sizing table from section 2.

Output

6 layer 4 balancer nodes behind a router that spreads 100000 flows with ECMP.

event                           router hashing         flows moved   moved although their node was fine
node 3 fails (6 to 5)           plain, hash mod N      83.2%         66.6%
                                resilient, 256 buckets 16.8%         0.0%
a seventh node joins (6 to 7)   plain, hash mod N      85.6%         71.3%
                                resilient, 256 buckets 14.0%         0.0%

Sizing: peak 120000 requests/s, one node serves 25000 requests/s, 300000 live sockets held at 400 bytes each.
nodes   load normally   after 1 node fails   after 2 nodes fail   sockets per node   socket memory per node
5       96.0%           120.0% over          160.0% over          60000              24 MB
6       80.0%           96.0%                120.0% over          50000              20 MB
7       68.5%           80.0%                96.0%                42857              17 MB
8       60.0%           68.5%                80.0%                37500              15 MB
9       53.3%           60.0%                68.5%                33333              13 MB
  • When node 3 failed, plain ECMP moved 83.2% of flows, 66.6% of them from healthy nodes. Resilient hashing moved 16.8%, all of them from the failed node.

  • When a seventh node joined, plain ECMP moved 85.6% and resilient hashing 14.0%, again without disturbing any flow that did not move to the new node.

  • With 5 nodes the load was 96.0% normally and 120.0% after a failure (over capacity). Six nodes survived one failure at 96.0%, seven survived two at 96.0%.

  • Sockets are cheap: 300,000 sockets over 5 nodes is 60,000 each, 24 MB per node.

Resilient hashing protects flows that were healthy, but a connection on the failed node is lost. If those connections matter, the nodes need to share connection state, or the client needs to reconnect and resume cheaply.

10. Putting It Together

The sixth program runs the decisions together on a scaled-down pool: 8 backends of 100 requests per second each and 640 new requests per second for 120 seconds. At second 30 hyd-api-6 dies. From second 60 to 100 hyd-api-3 is slow (20 requests per second) but still answers its health probe. Four balancers are compared.

  • Naive: round robin over backends that pass a probe (3 misses to leave, every 5 seconds), and every failed attempt retried up to 3 times.

  • Smart, no ejection limit: power of two choices on requests in flight, passive ejection after 5 failures in a row, a 10% retry budget, retries to a different backend, and a panic rule.

  • Smart, 25% limit: the same, but no more than a quarter of the pool may be out of rotation at once.

  • Designed: the 25% limit, and only hard errors count toward ejection.

Output

8 backends x 100 requests/s, 640 new requests/s for 120 s (a scaled-down pool; the ratios are what matter).
Second 30: hyd-api-6 dies. Seconds 60 to 100: hyd-api-3 is slow (20 requests/s) but still passes its health probe.

balancer                     served   lost     attempts   sent to the dead  lost in s 30-45  lost in s 60-100
naive                        98.9%    800      1.08       914               0.0%            3.1%
smart, no ejection limit     90.9%    6914     1.05       8166              0.0%            20.9%
smart, 25% limit             98.0%    1520     1.03       5                 0.0%            5.9%
designed (hard errors only)  98.9%    830      1.03       5                 0.0%            3.2%
  • The naive balancer served 98.9% and lost 800 requests, but sent 914 attempts to the dead backend before the probes removed it, and averaged 1.08 attempts per request.

  • Smart without an ejection limit served only 90.9%. Once the slow backend made the pool tight, healthy but overloaded backends were ejected one after another until the pool was empty. The panic rule then sent traffic to everything, including the dead backend (8,166 attempts).

  • A 25% limit brought it to 98.0%, with 5 attempts to the dead backend.

  • The designed balancer served 98.9%, the same as the naive one, with 5 attempts to the dead backend and 1.03 attempts per request. Both are at the limit of what a pool can do here: with two backends impaired there is not enough capacity for every request.

Be honest about the limits of these results. At a lighter load of 600 new requests per second every policy served 99.2% or more, and the naive balancer was slightly ahead of the designed one (100.0% against 99.2%). The designed balancer does not win everywhere. It is built for the bad days: it wastes little work on a dead server and cannot talk itself into an outage.

11. Layer 4 or Layer 7?

NeedLayer 4 nodeLayer 7 node
ProtocolsAny TCP or UDPHTTP, gRPC, WebSocket
SpeedHighest, flow hashing onlyLower, parses requests
TLS terminationNo, passes throughYes
Path routing and retriesNoYes
Backend choiceMaglev table, resilient ECMPPower of two choices, trie
Typical failureReset connections on a node lossRetry storm, ejection cascade

12. Trade-offs to Mention

  • Hashing keeps flows in place but cannot see load; power of two choices sees load but forgets history. Layer 4 uses hashing, layer 7 uses load.

  • Strict health checks react fast but risk emptying the pool; lenient ones are safe but slow. Limits and panic rules decide how the system fails.

  • Retries raise success for isolated failures and endanger overloaded pools. A budget keeps the benefit and removes the danger.

  • Immutable snapshots make the data plane simple and fast, at the price of rebuilding structures on each change.

  • More nodes buy failure headroom and cost money. Choose the number from the failures you must survive.

13. Common Mistakes

  • Using hash mod N where the pool changes often.

  • Letting health checks or outlier detection remove any number of servers.

  • Retrying every failure, or retrying on the same server.

  • Sizing the balancer tier for the average and not for the loss of a node.

  • Changing configuration by editing live state in place instead of swapping a validated, versioned snapshot.

  • Forgetting to drain a server before removing it.

14. Interview Questions

  • How would you spread connections so that adding a server moves few flows? Use consistent hashing such as a Maglev table, plus a connection table for established flows.

  • How do you update the configuration of a running balancer? Build a new immutable snapshot, validate it, and swap one pointer, keeping the old version for rollback.

  • What can go wrong with health checks? Flapping and cascades. Limit how much of the pool can be out, count only hard errors, and add a panic rule you have tested.

  • Why are retries dangerous? They add load exactly when capacity is short and can hold a system in a failed state. Use a retry budget and different servers.

  • What happens when one balancer node dies? With resilient ECMP only that node's flows move. Size the tier so the rest can carry the load.

Summary

  • Split the design into a data plane that only reads immutable snapshots and a control plane that changes them by version.

  • Use Maglev and resilient hashing so pool changes disturb few flows.

  • Limit ejection, count hard errors, and test the panic rule against real failures.

  • Spend retries from a budget.

  • Use a trie for routes and a pointer swap for updates.

  • Size the tiers for the failures you must survive, then prove the design under failure.

Conclusion

A load balancer looks simple until it has to be right during failures. The design above stays calm in them because every decision limits its own blast radius: hashing moves few flows, ejection is capped, retries are budgeted, and configuration changes are atomic. Use the same habit in the interview: for each component, say what can go wrong and how far the damage can spread.

Previous topic: Anycast Routing. Next topic: Design API Gateway.

References and further reading