Summary#
A load balancer (LB) sits in front of a group of servers and spreads requests across them, skipping unhealthy ones. L4 load balancers route TCP/UDP connections by IP and port; L7 load balancers understand HTTP and route by path, header or cookie. Pick an algorithm by workload: round robin for uniform requests, least connections or least response time for uneven ones, hashing when the same key must reach the same server. Health checks, connection draining and a redundant LB pair keep it from becoming the new single point of failure.
Why It Exists#
As soon as you run more than one server, something has to decide which server gets each request. A load balancer does that and adds three more benefits:
- Scalability: add servers behind one stable address to raise capacity. See Vertical vs Horizontal Scaling.
- Availability: unhealthy servers are removed automatically, so a crash does not become an outage.
- Operability: you can deploy, drain and replace servers with no downtime, and centralise TLS, logging and some security controls.
This page builds on HTTP and HTTPS, since L7 balancing works at the HTTP level.
How It Works#
Scale up first, then out#
Before adding a load balancer, ask whether one bigger machine would do. Modern servers are very powerful: a single box with 64+ cores, hundreds of GB of RAM and a 25-100 Gbps network card can serve tens of thousands of simple HTTP requests per second. Vertical scaling (a bigger server) keeps the design simple: no shared session store, no coordination, no extra hop. Many teams scale out far earlier than they need to.
Still, most real systems and almost every interview design end up with horizontal scaling (more servers), for three reasons: one machine is a single point of failure, there is a ceiling on how big a machine gets, and many small commodity machines are often cheaper per unit of capacity than one huge one. The moment you have more than one server, clients need to know which one to talk to. That is the load balancer's job.
Scaling out has costs that the load balancer does not remove:
- Servers must be stateless. If server 3 keeps a user's session or uploaded file in memory or on local disk, the next request may land on server 7 and find nothing. Keep sessions in a shared store such as Redis or a database, or in a signed token the client carries. Keep files in object storage.
- Downstream systems see more connections. Twenty app servers each holding a pool of 50 database connections means 1,000 connections to the database. Databases like PostgreSQL handle that poorly, which is why connection poolers such as PgBouncer exist (see TCP and UDP).
- Deploys and debugging get harder. A bug may only show on one server out of twenty. You need centralised logs and request IDs to follow a request.
Where the balancing decision happens#
There are two broad places to make the "which server?" decision: in the client itself, or in a dedicated load balancer that sits in the middle. A third option, the sidecar proxy, is a hybrid: a dedicated proxy that runs next to every client.
Client-side load balancing. The client fetches the list of servers from a service registry (a directory of live instances, such as Consul, etcd, ZooKeeper or Kubernetes endpoints) and picks one itself for each request. It must refresh that list, either by polling every few seconds or by receiving pushed updates. The big win is speed: there is no extra network hop on every request, and no central box to scale or to fail. The client can also use its own view of latency to pick the fastest server.
Two well-known examples:
- Redis Cluster. Nodes gossip with each other, so every node knows the full cluster map: which nodes exist and which hash slots each one owns. A client connects to any node, downloads that map, then hashes each key and sends the command straight to the owning node. If the map is stale and the client asks the wrong node, the node replies with a
MOVEDredirect naming the right one, and the client updates its map. - DNS. A name can return several IP addresses, and resolvers rotate their order, so different clients try different servers first. That is crude client-side balancing. It is also the standard way to avoid a single load balancer being a single point of failure: run two or more load balancers, ideally in different zones or regions, and publish all of their addresses in DNS. If one dies, clients retry the next address. See DNS.
Client-side balancing works well in two situations:
- A small number of clients that you control, such as your own microservices. gRPC has client-side balancing built in, and pushing membership changes to a few hundred service instances is easy.
- A huge number of clients that can tolerate slow updates, such as DNS. Updating millions of resolvers takes time, and the TTL puts a floor on how quickly a change takes effect, but for picking a region that is acceptable.
It works badly when you have many clients you do not control (browsers, mobile apps, partner integrations) and you need changes to take effect within seconds. The time to propagate a change grows with the number of clients, and you cannot ship new balancing logic to an old app version.
Dedicated load balancer. A separate server, appliance or managed service sits between clients and servers. Clients know one stable address and nothing about the fleet behind it. The cost is one extra hop per request, typically well under a millisecond inside a data center, plus a component that must itself be scaled and made redundant. The benefits are that membership changes take effect immediately, you get fine-grained routing control in one place, and clients stay simple.
Sidecar or service mesh. Each application instance gets a local proxy, usually Envoy, that does client-side balancing on its behalf. A control plane (Istio, Consul, or a custom xDS server) pushes server lists, weights and policies to every sidecar. You get the no-central-bottleneck property of client-side balancing without putting the logic into every language's client library. The cost is an extra local hop (tens to hundreds of microseconds), memory per sidecar, and a complex control plane.
| Placement | Extra hop | Update speed | Who must implement logic | Good fit |
|---|---|---|---|---|
| Client library | None | Seconds (push) to minutes (poll) | Every client | Internal services, Redis Cluster, Cassandra drivers |
| DNS | None per request | TTL bound, minutes | Resolvers and OS | Choosing a region or a load balancer |
| Dedicated LB | One network hop | Immediate | The LB only | Public traffic, clients you do not control |
| Sidecar proxy | One local hop | Seconds | The mesh | Large microservice fleets, polyglot stacks |
In an interview, the lines between internal services on your diagram are usually assumed to "just work". If asked how service A reaches service B, client-side balancing (or a mesh) is the strong answer. For traffic from the internet, use a dedicated load balancer.
L4 vs L7#
| L4 (transport) | L7 (application) | |
|---|---|---|
| Sees | IPs, ports, protocol | Full HTTP request: method, path, headers, cookies |
| Routes | Connections | Individual requests |
| TLS | Passthrough, or termination | Terminates TLS to read HTTP |
| Features | Very fast, protocol-agnostic, preserves client IP easily | Path/host routing, retries, header rewrites, compression, auth hooks, WAF |
| Cost | Very low per request | More CPU per request |
| Examples | AWS NLB, Google TCP/UDP LB, HAProxy (TCP mode), IPVS | AWS ALB, Nginx, Envoy, HAProxy (HTTP mode), Traefik |
A common layout is L4 at the edge for raw throughput and DDoS resilience, then L7 behind it for smart routing.
How an L4 load balancer forwards packets#
An L4 load balancer never reads the request. It looks at the packet headers (source IP, source port, destination IP, destination port, protocol), picks a backend for that flow (one TCP connection or one UDP conversation), and then forwards every later packet of the same flow to the same backend. From the client's point of view, it is as if it had opened a TCP connection straight to one randomly chosen server. That is why L4 balancing suits protocols that keep a connection open, such as WebSockets, MQTT, database protocols and game traffic: once the connection is placed, nothing moves it.
To keep packets of a flow together, the LB keeps a connection table that maps the 5-tuple to the chosen backend. A table entry is small (tens to a couple of hundred bytes), so even millions of concurrent flows fit in memory. If the table is lost, for example when an LB node restarts, the LB must be able to recompute the same choice, which is why large L4 balancers use consistent hashing on the 5-tuple as a fallback.
There are three common ways to get the packet to the backend and the reply back:
| Mode | How the packet reaches the backend | How the reply returns | Client IP visible to backend? | Notes |
|---|---|---|---|---|
| NAT (full proxy of addresses) | LB rewrites destination IP (and often source IP) | Through the LB, which rewrites back | Only if source is not rewritten, or via PROXY protocol | Simple, works across subnets, LB carries both directions |
| Direct server return (DSR) | LB rewrites only the destination MAC on the same L2 network | Straight from backend to client | Yes | Backends must own the virtual IP on a loopback interface |
| Tunnelling | LB wraps the packet in IP-in-IP, GRE or GUE | Straight from backend to client | Yes | Works across subnets; used by Maglev, Katran and GitHub's GLB |
Why DSR matters. Responses are usually much bigger than requests. A video request might be 500 bytes in and 5 MB out. With DSR or tunnelling the LB only carries the small inbound side, so one LB node can front far more traffic. The cost is that the LB never sees the response, so it cannot measure latency or status codes, and backends need special network setup.
Keeping the client IP. When an L4 or L7 proxy rewrites the source address, the backend sees the LB's IP, which breaks rate limiting, geo rules and logs. Two fixes are common. The PROXY protocol (designed by HAProxy) prepends a short header with the original client address to the TCP stream; the backend must be configured to expect it. At L7, the proxy adds X-Forwarded-For and X-Forwarded-Proto headers, or the standard Forwarded header. Only trust these headers when they were set by your own proxy, since clients can forge them (see HTTP and HTTPS).
What an L7 load balancer does per request#
An L7 load balancer is a full proxy. It accepts the client's TCP connection, completes the TLS handshake, parses each HTTP request, decides where it goes, and sends it over a separate connection that it keeps open to the chosen backend. The two connections are independent: the client might speak HTTP/2 over TLS 1.3 from a phone, while the LB talks HTTP/1.1 or HTTP/2 over a pooled, long-lived connection to the backend.
Because it sees every request, an L7 LB can do much more than spread load:
- Content-based routing by host name, path, method, header, query parameter or cookie. For example,
/video/*goes to servers with fast disks and large caches, while/billing/*goes to a hardened, separately audited pool. - Per-request balancing on a multiplexed connection. This matters for HTTP/2 and gRPC, where one client connection carries thousands of requests. An L4 balancer would pin all of them to one backend.
- Retries and timeouts for idempotent requests, hiding a single bad backend from clients.
- Request and header rewriting, such as adding request IDs, removing internal headers, or rewriting paths.
- Buffering. The LB can read a slow client's whole request before passing it on, so a client on a bad mobile link does not tie up an application thread. This also blunts slow-request attacks like Slowloris.
- Security and policy hooks: web application firewall rules, authentication checks, rate limits, and IP allow-lists. At this point an L7 LB starts to overlap with an API gateway (see Proxies and Reverse Proxies).
- Observability: per-route latency, status codes and traces, since it sees every request and response.
The price is CPU and latency. The LB must decrypt TLS, parse HTTP and copy bytes between two connections. A well-tuned software L7 proxy adds roughly 0.2-1 ms per request inside a region, compared with microseconds for an L4 forwarder. On modern hardware the per-request cost is small enough that L7 is the default for HTTP services, but at very high volumes it shows up as a real line item on the bill.
WebSockets and other long connections. A WebSocket starts as an HTTP request with an Upgrade header. Many L7 balancers (Nginx, HAProxy, Envoy, AWS ALB) support the upgrade and then just pipe bytes for the life of the connection. Even so, the balancing decision happens only once, at connect time, so L7 brings few benefits after that. A common rule of thumb: put WebSocket and other persistent-connection traffic behind an L4 balancer (or an L7 one in pass-through mode) and route by connection count, and use L7 for request-response HTTP, including long polling and Server-Sent Events, which look like ordinary HTTP requests. See Real-time Communication.
| Question | Lean L4 | Lean L7 |
|---|---|---|
| Is the protocol HTTP or gRPC? | No | Yes |
| Do you need path, host or header routing? | No | Yes |
| Do you need per-request balancing on HTTP/2 or gRPC? | No | Yes |
| Are connections long-lived (WebSockets, MQTT, game sessions)? | Yes | Possible, with upgrade support |
| Must the backend terminate TLS itself (compliance, client certs)? | Yes, passthrough | Only with re-encryption |
| Is raw packet throughput the main concern? | Yes | No |
Algorithms#
| Algorithm | How it works | Best for | Weakness |
|---|---|---|---|
| Round robin | Next server in turn | Similar servers, similar requests | Ignores current load |
| Weighted round robin | Turns in proportion to weights | Mixed server sizes; canaries (5% weight) | Static weights |
| Least connections | Server with fewest open connections | Long or uneven requests, WebSockets | Connection count is not always load |
| Least response time | Lowest recent latency (often with fewest connections) | Servers with different speeds or noisy neighbours | Needs latency tracking; can herd onto one fast server |
| Power of two random choices | Pick two at random, send to the less loaded | Large fleets, many LB instances | Slightly less optimal than global view |
| IP hash | Hash of client IP picks the server | Simple affinity without cookies | Uneven behind NAT; reshuffles when servers change |
| Consistent hashing | Hash of a key (user ID, cache key) on a ring | Caches and stateful shards: same key, same server | Hot keys still overload one node |
Consistent hashing matters when servers hold data: when a server is added or removed, only about 1/N of keys move instead of almost all. See Consistent Hashing.
Static algorithms in depth: round robin, random and weights#
Round robin hands requests to servers in a fixed cycle: A, B, C, A, B, C. Random picks a server uniformly at random. Both ignore load, and for most stateless services that is fine. If every request costs about the same and every server is the same size, each server gets about 1/N of the work. Both also have a useful property for scaling: a newly added server starts getting its fair share on the very next request, with no warm-up logic.
They break down in three cases. First, when request costs vary a lot (a search that takes 2 s next to a lookup that takes 2 ms), one server can end up with several slow requests at once while others sit idle. Second, when servers differ in size or health. Third, when connections are long-lived. Round robin spreads new connections evenly, but if a server restarts it comes back empty while the others keep their old connections. Over time connections pile up on whichever servers have been up longest.
Weighted round robin fixes the size problem. Give a 16-core server weight 2 and an 8-core server weight 1, and the big one gets two turns for every one turn of the small one. Weights are also the standard tool for canary releases: give the new version weight 1 against 19 for the old, and it receives 5% of traffic.
A naive weighted scheme sends bursts: with weights A=5, B=1, C=1 it would send A, A, A, A, A, B, C. Nginx uses a smooth weighted round robin that interleaves instead. Each server keeps a running score. On every pick, add each server's weight to its score, choose the server with the highest score, then subtract the total weight (here 7) from the winner's score.
| Pick | Scores after adding weights (A, B, C) | Chosen | Scores after subtracting 7 |
|---|---|---|---|
| 1 | 5, 1, 1 | A | -2, 1, 1 |
| 2 | 3, 2, 2 | A | -4, 2, 2 |
| 3 | 1, 3, 3 | B | 1, -4, 3 |
| 4 | 6, -3, 4 | A | -1, -3, 4 |
| 5 | 4, -2, 5 | C | 4, -2, -2 |
| 6 | 9, -1, -1 | A | 2, -1, -1 |
| 7 | 7, 0, 0 | A | 0, 0, 0 |
The sequence is A, A, B, A, C, A, A: still 5:1:1, but B and C are spread out and the scores return to zero after one cycle.
Dynamic algorithms in depth: least connections, least time and two choices#
Dynamic algorithms look at the current state of each server.
Least connections sends each new request or connection to the server with the fewest open ones. Open connections are a cheap stand-in for "how busy is this server". It is the right default for long-lived connections such as WebSockets and SSE streams, because it pushes new connections toward servers that have fewer, including freshly started ones, so the fleet evens out over time. Worked example: three chat servers hold 9,000, 9,000 and 0 connections after the third one restarts. Round robin would send it only a third of new connections, so it stays nearly empty for hours. Least connections sends it every new connection until it catches up.
That same behaviour has a sharp edge. A brand-new server with zero connections gets all new connections at once, before its caches, JIT compiler and connection pools are warm. This "new server rush" can knock it straight over. The fix is slow start: ramp a new server's effective weight from near zero to full over 30-120 seconds. HAProxy (slowstart), Envoy (slow start mode) and AWS ALB (slow start duration) all support it.
Least response time prefers the server that has recently answered fastest, usually combined with outstanding requests. A popular form is peak EWMA, used by Twitter's Finagle and by Linkerd: keep an exponentially weighted moving average of latency that jumps up immediately on a slow response and decays slowly, multiply by the number of outstanding requests, and pick the lowest score. This reacts quickly to a server that has started a long garbage-collection pause or sits on a noisy host. The risk is herding: if many balancers all see the same server as fastest, they all pile onto it and make it slow.
Power of two random choices is the most important algorithm most people have not heard of. Pick two servers at random and send the request to the less loaded of the two. It needs almost no shared state and almost no coordination, yet it performs nearly as well as checking every server.
The intuition comes from the classic "balls into bins" problem. Throw n requests at n servers completely at random and the busiest server ends up with about ln n / ln ln n requests. For n = 1,000 that is roughly 3.6 on average, and much worse in an unlucky run. With two choices, the busiest server has about ln ln n / ln 2, roughly 2.8 for n = 1,000. More importantly, the gap grows as the fleet grows: the two-choice bound grows exponentially more slowly. This result comes from Azar, Broder, Karlin and Upfal ("Balanced Allocations", 1994) and was developed for load balancing in Michael Mitzenmacher's 1996 PhD thesis, "The Power of Two Choices in Randomized Load Balancing". Envoy, HAProxy (random(2)) and Nginx (random two least_conn) all offer it.
Why not just always pick the single least-loaded server? Because in a real system each balancer's view is slightly stale. If 50 balancer nodes all read "server 7 has the fewest connections" from the same snapshot, they all send their next request there, and server 7 is suddenly the busiest. Mitzenmacher's later paper "How Useful Is Old Information?" (2000) showed that with stale load data, picking the global minimum can be worse than random, while choosing between two random servers stays robust.
| Algorithm | State needed | Reacts to slow servers? | Stale-data safe? | Typical use |
|---|---|---|---|---|
| Round robin or random | None | No | Yes | Uniform stateless requests |
| Weighted round robin | Static weights | No | Yes | Mixed sizes, canaries |
| Least connections | Count per server | Partly | Herds if many LBs | WebSockets, SSE, uneven requests |
| Peak EWMA or least time | Latency per server | Yes, fast | Can herd | Latency-sensitive RPC |
| Two random choices | Count per server | Partly | Yes | Large fleets, many LB nodes |
| Consistent hashing | Ring or table | No | Yes | Caches, stateful servers |
Hashing algorithms in depth: from modulo to consistent hashing#
Sometimes the goal is not just even load but affinity: the same key should always reach the same server. A cache node is only useful if requests for key "user:42" keep going to the node that holds it. A chat server can only deliver a message if you know which server holds the recipient's connection.
The obvious approach is modulo hashing: server = hash(key) % N. It spreads keys evenly and needs no state. The trouble starts when N changes. A key keeps its server only if hash mod N equals hash mod (N+1), which happens for only about 1 in N+1 keys. Going from 3 to 4 servers moves 75% of keys. Going from 10 to 11 moves about 91%. Losing one of 10 servers is just as bad. For a cache this means the hit rate collapses to near zero and every request falls through to the database at once. For a database it means migrating almost the whole dataset.
Consistent hashing fixes this. Picture the output range of the hash function, say 0 to 2^32 - 1, bent into a circle. Hash each server's name to place it at a point on the circle. To find a key's server, hash the key to a point and walk clockwise until you meet a server. Each server owns the arc between its predecessor and itself.
Worked example on a small ring of 0-999. Servers sit at 100 (S1), 400 (S2) and 700 (S3). A key hashing to 250 walks clockwise and lands on S2; a key at 820 wraps past 999 to S1. Now add S4 at 550. Only keys in 401-550, which used to belong to S3, move to S4. Everything else stays put: about 15% of keys move, all of them from one server. Remove S2 instead, and only S2's keys (101-400) move, all to S3.
The idea comes from Karger, Lehman, Leighton, Panigrahy, Levine and Lewin, "Consistent Hashing and Random Trees: Distributed Caching Protocols for Relieving Hot Spots on the World Wide Web" (STOC 1997). That work was the basis of Akamai's CDN.
Virtual nodes. With one point per server, arcs come out very uneven: some servers own twice the average and some half. Worse, when a server dies its whole arc lands on a single neighbour, which suddenly has double the load. The fix is to place each server at many points, by hashing "S1#0", "S1#1" and so on. With 100-200 virtual nodes per server, each server's share stays within a few percent of the average, and a failed server's keys are spread across all the survivors rather than dumped on one. Virtual nodes help with additions too: a new server takes a small slice from many existing servers rather than a big slice from one. They also allow weighting: a server with twice the capacity gets twice the virtual nodes. Cassandra once used 256 tokens per node by default and lowered that to 16 in version 4.0, paired with a smarter token allocator, because very many tokens made repair and streaming slower.
Hot keys are a different problem. Consistent hashing spreads keys evenly, not traffic. If one key is 100 times more popular than the rest (the ticket page for the biggest concert of the year, a viral post), its single owner gets hammered no matter how good the ring is. Virtual nodes fix structural imbalance (uneven key ranges). Hot keys need workload fixes:
- Replicate hot keys to several nodes and spread reads across the copies. This is the most common fix.
- Split the key: store a hot counter as "post:99:shard0" through "post:99:shard7", so writes spread over eight nodes, and add them up on read.
- Adaptive rebalancing: watch traffic and split or move hot ranges automatically. DynamoDB does this behind the scenes. It is powerful but complex to build.
- Cache in front: a small in-process cache on the clients absorbs most reads for the hottest few keys.
Membership changes vs failures. Consistent hashing says where data should live; it does not move bytes. Real databases pair it with replication so that a node failure needs no data movement at all. Cassandra stores each key on the next N distinct nodes clockwise, so if one dies, reads go to the replicas. DynamoDB keeps each partition on replicas in three availability zones and promotes a replica through a consensus protocol when a leader fails. Bulk data movement happens only on planned changes, such as adding capacity or replacing a dead node to restore the replica count, and consistent hashing keeps that to roughly 1/N of the data.
Not every system uses a ring. Redis Cluster splits the key space into 16,384 fixed hash slots (CRC16 of the key, mod 16,384) and assigns ranges of slots to nodes. Moving capacity means moving whole slots, which is easier to reason about and to observe, but requires an explicit rebalancing step. As Martin Kleppmann notes in Designing Data-Intensive Applications, the name "consistent hashing" is used loosely; what matters is the property of moving only a small fraction of keys when membership changes. See Consistent Hashing for full detail.
| Scheme | Keys moved when one of N servers is added | Lookup cost | Memory | Used by |
|---|---|---|---|---|
| Modulo | About N/(N+1), nearly all | O(1) | None | Small fixed pools only |
| Ring with virtual nodes | About 1/(N+1) | O(log of ring size) | Ring of N x V points | Cassandra, many caches |
| Fixed hash slots | About 1/(N+1), moved slot by slot | O(1) | Slot table | Redis Cluster |
| Rendezvous (highest random weight) | About 1/(N+1) | O(N) per lookup | None | Small pools, some CDNs |
| Jump hash | About 1/(N+1) | O(log N) | None | Sharded storage with numbered buckets |
| Maglev table | Close to 1/(N+1) | O(1) | Fixed table, for example 65,537 entries | Google Maglev, L4 balancers |
Health checks#
The LB checks each server regularly:
- Active checks: request
/healthzevery 5-10 seconds; after 2-3 failures, stop sending traffic; after 2 successes, add it back. - Passive checks (outlier detection): watch real traffic and eject servers that return many errors or time out.
A good health check is cheap and reflects whether the server can do useful work. It should not deeply check every dependency, or one slow database makes the LB eject every server at once. Pair checks with connection draining: when a server is removed for a deploy, stop new requests but let in-flight ones finish (typically 30-60 seconds).
Health checks in depth#
Health checking is what turns a traffic spreader into an availability tool. If a server loses power, crashes or hangs, the LB stops sending it traffic within seconds, with no human involved.
Kinds of check.
- TCP check: can the LB open a connection to the port? Cheap, and catches crashed processes and dead hosts, but a server whose process is up yet deadlocked will still pass.
- HTTP check: request a path such as
/healthzand expect a 2xx status within a timeout. This proves the web stack can answer. It is the normal choice for HTTP services. - Application-aware check: the endpoint verifies things the instance needs to do useful work, such as "my config is loaded and my local cache is warm".
- Passive checks (outlier detection): no extra probes. The LB watches real responses and ejects a server that returns, say, 5 consecutive 5xx errors or whose error rate is far above its peers. Envoy's outlier detection and NGINX's
max_failswork this way.
Liveness vs readiness. Kubernetes made a useful split popular. A liveness check answers "is this process wedged and in need of a restart?" A readiness check answers "should this instance receive traffic right now?" A server that is starting up, warming its cache or draining for shutdown is alive but not ready. Load balancers should follow readiness. Mixing the two causes restart loops: a slow dependency fails liveness, the orchestrator kills healthy processes, and the restarts make the overload worse.
Shallow vs deep. A deep check that queries the database, the cache and three downstream services sounds thorough, but it couples every server's health to shared dependencies. If the database slows down, every server fails its check at the same moment and the LB removes the whole fleet, turning a partial slowdown into a full outage. Prefer shallow checks that test the instance itself, and handle dependency failures with timeouts, circuit breakers and degraded responses.
Thresholds and timing. A typical active check runs every 5-10 seconds with a 2-5 second timeout, marks a server unhealthy after 2-3 consecutive failures, and healthy again after 2-5 successes. The asymmetry (quicker to remove, slower to restore) adds hysteresis, so a server that flaps between good and bad does not keep bouncing in and out.
Worked example of what detection time costs. A pool of 10 servers serves 5,000 requests per second, so each server gets 500. One server hangs. With a 10-second interval and 3 failures required, removal can take up to about 30 seconds plus the timeout. During that window around 500 x 30 = 15,000 requests go to the dead server. Users see errors or timeouts unless the LB retries them elsewhere. This is why serious setups combine active checks with passive outlier detection (which reacts after a handful of failed real requests) and with retries of idempotent requests on another server.
Health-check load. Checks are not free. A fleet of 100 LB nodes each checking 200 backends every 5 seconds produces 100 x 200 / 5 = 4,000 checks per second, which some small services notice. Large systems centralise checking in a few health-checker nodes and share the results, or have each LB check only a subset of backends.
Fail open, do not fail empty. If health checks say every backend is down, the likeliest cause is the check itself or a shared dependency, not that every server died at once. Sending traffic nowhere guarantees an outage. Many balancers fail open instead: AWS ALB routes to all targets when every target is unhealthy, and Envoy has a panic threshold (50% by default) below which it ignores health status and spreads load across all hosts.
Gray failure. The hardest case is a server that passes every check but is still bad: it answers /healthz in 2 ms while real requests take 3 seconds because one disk is dying, or it fails only requests for one tenant. Passive detection on real traffic, per-backend latency metrics, and comparing each server against its peers are the defences.
Connection draining and zero-downtime deploys#
Removing a server abruptly drops whatever it is in the middle of. Connection draining (AWS calls it the deregistration delay) means: stop sending new requests to the server, let in-flight requests finish, then close it. Ordinary HTTP APIs need 10-60 seconds; AWS defaults to 300 seconds, which is often far longer than needed and slows every deploy. Long-lived connections such as WebSockets never "finish", so the server should tell clients to reconnect elsewhere (for example a WebSocket close frame with a "going away" status) and clients should reconnect with random jitter so they do not all arrive at the same instant.
A rolling deploy behind an LB looks like this:
A classic bug in Kubernetes: the pod receives SIGTERM and exits immediately, but the load balancers and kube-proxy rules on other nodes take a few seconds to learn that the endpoint is gone, so they keep sending requests to a dead pod. The fix is a short preStop sleep (5-15 seconds) or a shutdown handler that first fails readiness, keeps serving for a few seconds, and only then stops accepting connections.
The same mechanics enable safer release patterns:
- Blue-green: run the new version as a full second pool, then switch the LB from blue to green in one step. Switching back is just as fast.
- Canary: send 1-5% of traffic to the new version using weights or a header rule, compare error rates and latency with the old version, then ramp up.
- Shadowing: an L7 proxy copies live requests to the new version and throws away its responses, testing it under real load with no user impact.
Sticky sessions and why to avoid them#
Sticky sessions (session affinity) send a user to the same server every time, using a cookie or IP hash. They are a workaround for servers that keep session state in memory.
Why to avoid them: load becomes uneven (a few heavy users pin one server), a server failure logs out its users, and autoscaling and deploys get harder because you cannot freely move users. The better fix is stateless servers with sessions in a shared store or tokens. Stickiness is still reasonable for long-lived connections (WebSockets) and for performance affinity such as local caches.
How stickiness is implemented.
- LB-issued cookie: on the first response the LB sets a cookie (for example AWS ALB's
AWSALB) that names the chosen server, and routes later requests that carry the cookie to that server. It is precise, but it only works at L7 and only for clients that keep cookies. - Application cookie: the LB hashes or looks up an existing session cookie set by the app.
- Source IP hash: works at L4 with no cookies, but many users can share one IP. Corporate proxies and carrier-grade NAT (where a mobile carrier puts thousands of phones behind a few public IPs) can send a huge group of users to one server. A phone that switches from Wi-Fi to mobile data also changes IP and loses its server.
- Consistent hash on a header or key (user ID, tenant ID): good affinity that survives changes in fleet size with little movement.
What it costs, in numbers. Suppose 20 servers each have 5% of users pinned to them. One large customer whose integration sends 30% of all traffic is stuck on one server, which runs hot while the rest idle. When a server dies, all its pinned users lose their in-memory sessions, so 5% of users are logged out at once. When autoscaling adds 5 servers, existing users stay where they are, so the new servers take hours to fill up and the hot servers stay hot. And a deploy has to wait for long sessions to end, or break them.
Where state should live instead. Store session data in Redis or Memcached (a single-digit-millisecond lookup), in a database, or in a signed token such as a JWT that the client sends with each request. Then any server can handle any request, and stickiness becomes optional.
When stickiness is the right tool.
- Persistent connections are sticky by nature: a WebSocket belongs to one server for as long as it is open. That is fine, as long as a reconnect can land on any server.
- Cache affinity: routing a user or tenant to the same server improves its local cache hit rate. Use consistent hashing on the key, and make sure a miss is only slower, never wrong.
- Migration step: a legacy app that keeps sessions in memory can run behind sticky sessions while the team moves state out.
- Multi-step uploads or in-progress work that cannot easily be shared, where the cost of a broken affinity is just a retry.
TLS termination#
The LB usually terminates TLS: it holds the certificate, decrypts traffic, applies L7 rules, and forwards to servers over plain HTTP inside a private network, or re-encrypts for end-to-end encryption. Centralising TLS simplifies certificate rotation and offloads CPU from app servers.
TLS at the load balancer in depth#
There are three ways to place TLS around a load balancer:
| Mode | Where TLS ends | LB can see HTTP? | Pros | Cons |
|---|---|---|---|---|
| Termination | At the LB; plain HTTP to backends | Yes | One place for certificates, L7 features, cheaper backends | Traffic inside the network is unencrypted |
| Re-encryption (TLS bridging) | At the LB, then new TLS to backends | Yes | L7 features plus encryption in transit everywhere | Two handshakes, certificates on backends too |
| Passthrough | At the backend; LB forwards encrypted bytes | No, only SNI | End-to-end encryption, backend holds keys | L4 routing only, no per-request features |
Termination is the common default for public traffic. The primer stresses two benefits: backends do not spend CPU on encryption, and you do not need to install and rotate an X.509 certificate on every server. Managed services go further, issuing and renewing certificates automatically (AWS Certificate Manager, Google-managed certificates, Let's Encrypt with Caddy or Traefik).
Re-encryption is now common inside regulated or zero-trust networks, where "the internal network is trusted" is no longer an acceptable assumption. Service meshes do this automatically with mutual TLS (mTLS), giving each workload its own short-lived certificate that proves its identity to the next hop.
Passthrough still allows some routing: the TLS ClientHello carries the target host name in plain text (SNI, Server Name Indication), so an L4 balancer can route a.example.com and b.example.com to different pools without decrypting anything.
The cost of TLS on the LB. Most TLS cost is in the handshake, not the bulk encryption, which modern CPUs speed up with AES instructions. As a rough guide, one CPU core can do about 1,000-2,000 RSA-2048 private-key signatures per second, but tens of thousands of ECDSA P-256 signatures per second. Using ECDSA certificates, TLS 1.3 and session resumption (so returning clients skip the expensive step) can cut handshake CPU several-fold. Long keep-alive connections help even more: a client that sends 50 requests on one connection pays for one handshake. When an LB is CPU-bound, the cause is usually a flood of new connections, not data volume.
Load balancer high availability#
The LB itself must not be a SPOF.
- Managed cloud LBs (AWS ALB/NLB, Google Cloud Load Balancing) run as redundant fleets across zones; you get a DNS name or anycast IP.
- Self-hosted active-passive pair: two LB nodes share a virtual IP using VRRP (for example, keepalived); if the active one fails, the passive takes over the IP in seconds.
- Active-active with anycast or ECMP: many LB nodes announce the same IP; routers spread traffic across them.
Load balancer high availability in depth#
The primer's warning is simple: a single load balancer is itself a single point of failure, and adding more load balancers adds complexity. Here is how that complexity is handled in practice.
Active-passive pair with a floating IP. Two LB nodes run the same config. The active one owns a virtual IP (VIP). The passive one watches it using VRRP (Virtual Router Redundancy Protocol), most often through keepalived. If the active node stops sending heartbeats (typically about once per second), the passive node claims the VIP and announces it with a gratuitous ARP so switches learn the new location. Failover takes about 1-3 seconds. In-flight connections usually break unless connection state is synced between the pair. Half the hardware sits idle, and this setup only works within one L2 network, so cloud providers offer different tools.
Active-active with ECMP and anycast. Several LB nodes all announce the same VIP to the upstream routers using BGP. The routers use ECMP (equal-cost multi-path routing) to hash each flow's 5-tuple and spread flows across the LB nodes. If a node dies, it stops announcing the route, BGP withdraws it, and routers spread its flows across the others. Every node does useful work, and capacity grows by adding nodes. The catch: when the set of nodes changes, the routers' hashing changes too, and some existing flows land on a different LB node that has never seen them. Large L4 balancers survive this by making every node compute the same backend for a given 5-tuple using consistent hashing, so it does not matter which LB node a packet reaches. Google's Maglev is built around exactly this idea.
DNS across load balancers. As described above, publishing several LB addresses in DNS spreads clients and survives the loss of one LB, at the cost of DNS-speed failover. Managed cloud LBs use this internally: an AWS ALB's DNS name resolves to several IPs across availability zones, and the set changes as AWS scales the LB.
Managed LBs scale too, but not instantly. Cloud L7 load balancers add capacity as traffic grows, but a sudden 10x spike (a product launch, a flash sale) can outrun their scaling. Network load balancers that work at L4 generally handle spikes better. For a planned event, ask the provider to pre-provision capacity, and load-test beforehand.
Cross-zone balancing. If zone A has 2 backends and zone B has 8, and the LB nodes in each zone send traffic only to their own zone, the two in zone A each take 25% of all traffic while the eight in zone B take 6.25% each. Cross-zone load balancing spreads traffic over all healthy backends regardless of zone, at the price of cross-zone data transfer fees and a little extra latency.
This layered shape (routers, then a stateless L4 tier, then an L7 proxy tier, then services) is how large companies build their edge. The L4 tier is cheap per packet and absorbs floods. The L7 tier does the expensive, smart work and can scale independently.
Global vs local load balancing#
- Local (regional) LB spreads requests across servers in one region or zone.
- Global LB (GSLB) picks the region: by latency, geography or health. It is done with DNS routing (Route 53, Cloudflare), with anycast IPs (Google Cloud global LB, Cloudflare), or both. See DNS.
Global load balancing in depth#
Global server load balancing (GSLB) answers a different question from local balancing: not "which server?" but "which region or data center?". It weighs four inputs: how close the region is to the user (latency), whether the region is healthy, whether it has spare capacity, and any legal rules about where data may go (data residency, for example keeping EU users in EU regions).
There are two main mechanisms, and large providers combine them:
- DNS-based GSLB. The authoritative DNS server returns a different address depending on the resolver's location (or the client subnet if the resolver sends it), on region health and on weights. Route 53, Cloudflare, NS1 and Azure Traffic Manager work this way. It is simple and works with any protocol, but failover is bounded by DNS caching: realistically a minute or more even with a 60-second TTL, because some resolvers and clients hold on to old answers. Details are in DNS.
- Anycast-based GSLB. The same IP address is announced over BGP from many locations, and the internet's routing delivers each user to the nearest one, usually measured in network hops rather than milliseconds. A front-end proxy at that edge location then forwards the request over the provider's private backbone to a healthy region with capacity. Google Cloud's global external load balancer and Cloudflare work this way. Failover is fast (seconds, as routes change or the edge proxy picks another region), and clients never need to re-resolve DNS.
Spillover and capacity. Sending every user to the nearest region is right until that region is full. A good GSLB knows each region's capacity and, once a region reaches its limit, sends the overflow to the next-nearest region rather than letting the nearest one fall over. This is how a region can absorb a local traffic spike, or how traffic shifts smoothly when one region loses half its capacity.
Failover capacity. Global failover only works if the surviving regions can take the extra load. With three regions each running at 60% of capacity, losing one adds 30 percentage points to each of the other two, putting them at 90%. That is tight but survivable. At 75% each, the survivors would need 112.5%, and the failover would cascade into a global outage. Plan regional headroom for "N-1 regions" just as you plan server headroom for "N-1 servers".
Pinning users to a home region. Some systems must always send a given user to the region that holds their data, for example because writes go to a single primary. Then the GSLB's choice is driven by a lookup (user to home region) rather than by proximity, often implemented as an L7 redirect or a routing header added at the edge.
Real use cases#
- Spreading API traffic across a stateless app tier, with autoscaling adding servers.
- Blue-green and canary deployments using weights or header rules.
- Routing
/api,/staticand/wsto different services from one domain. - Spreading cache or shard traffic by key with consistent hashing.
- Internal service-to-service balancing, often done client-side or by a service mesh sidecar (Envoy).
Case study: consistent hashing of chat servers#
A chat system shows why plain load balancing is not enough once servers hold state. Suppose an app has 1 billion users with 200 million connected at once. A single chat server can hold on the order of 1-2 million connections (WhatsApp was famous for reaching about this per host with Erlang), so you need a few hundred chat servers.
What breaks with a plain load balancer. Put a load balancer in front of the chat servers and let it place each WebSocket by least connections. User A is on server 1, user B on server 2. When A sends B a message, server 1 has no connection to B, so it cannot deliver it. Load balancing spread the connections, but now the system has a routing problem: given a user, which server holds their connection?
A tempting dead end: one queue topic per user. Some designs give every user their own Kafka topic, and have each chat server subscribe to the topics of its connected users. Kafka is not designed for billions of topics. Each topic and partition carries metadata, files and replication overhead, and at around tens of KB per topic, a billion of them means tens of TB of overhead before a single message is stored.
Consistent hashing of users to servers. Assign every user to a chat server by hashing their user ID onto a ring of chat servers. Keep the ring (which servers exist, their addresses and which arcs they own) in a coordination service such as ZooKeeper or etcd, and have every server watch it. When a client connects, the connection layer routes it to the server that owns its user ID. When server 1 needs to deliver to B, it hashes B's ID, finds server 2, and calls it directly.
This works, but it brings problems you must be ready to discuss:
- Server-to-server mesh. Every chat server may need to talk to every other one. With 300 servers that is about 45,000 server pairs to keep connected, which pushes you toward fewer, larger servers.
- Scaling events move users. Adding a server changes ownership of some arcs, so the users on those arcs must disconnect and reconnect to their new owner. Do it gradually, with jittered reconnects, or the reconnect wave becomes a thundering herd that overloads the new server.
- Messages in flight during a move. While ownership is changing, send events to both the old and the new owner, or buffer them, so none are dropped.
The usual alternative: a pub/sub layer. Instead of routing between chat servers, let users connect to any chat server (plain least-connections balancing). When a user connects, their server subscribes to a channel named after their user ID in a pub/sub system such as Redis Pub/Sub. To deliver a message, publish it to the recipient's channel; whichever server holds the connection receives it and pushes it down the socket. Redis channels are very light, just in-memory lists of subscribers with no message storage, so delivery is at most once and a durable store must still hold messages for offline users. The pub/sub layer itself is sharded across Redis nodes by user ID. This trades the ring and the mesh for one extra hop through Redis, and it makes chat servers stateless apart from their open sockets.
The lesson for load balancing: once a server holds something the next request depends on (a cache entry, a socket, a shard), the balancing decision becomes a routing decision, and you choose between affinity (consistent hashing to the owner) and indirection (any server, plus a lookup or pub/sub layer).
Load balancing in Kubernetes and service meshes#
Kubernetes has its own layers of load balancing, and they behave differently from a classic LB:
- A Service of type ClusterIP gets a virtual IP.
kube-proxyprograms iptables or IPVS rules on every node, so traffic to that IP is sent to a backend pod. With iptables the pick is random per connection; IPVS supports round robin, least connections and others. - A LoadBalancer Service asks the cloud provider for an external L4 load balancer.
- An Ingress or Gateway API controller (NGINX, Envoy-based ones such as Contour, cloud ALB controllers) provides L7 routing by host and path.
The trap is gRPC and other HTTP/2 traffic. A gRPC client opens one long-lived connection, kube-proxy balances it once at connect time, and from then on every request goes to the same pod. Scale from 3 pods to 10 and the 7 new pods sit idle. Fixes include client-side balancing with a headless Service (DNS returns every pod IP and the gRPC client balances across them), an L7 proxy or mesh sidecar that balances per request, or a maximum connection age on the server so clients reconnect regularly.
Sizing a load balancer: a worked example#
Say an API peaks at 50,000 requests per second. Requests average 2 KB and responses 20 KB. Clients reuse connections, so about 10% of requests open a new TLS connection. Each request takes 100 ms end to end.
- Bandwidth: 50,000 x 22 KB is about 1.1 GB/s, or roughly 9 Gbps. A single 10 Gbps interface would be close to full, so plan for several LB nodes or 25 Gbps links.
- TLS handshakes: 10% of 50,000 is 5,000 new handshakes per second. With ECDSA certificates that fits on a few cores. With RSA-2048 at around 1,500 per core it needs 3-4 cores just for signatures, plus headroom.
- Concurrency: by Little's law (in-flight = arrival rate x time in system), 50,000 x 0.1 s = 5,000 requests in flight. Idle keep-alive connections can number far more, often 100,000 or more for mobile clients that leave connections open.
- Redundancy: size so that losing one node (or one zone) leaves enough capacity. With three nodes, each must handle half the peak.
Managed LBs hide most of this, but the same numbers drive their cost: AWS, for example, bills load balancers partly on new connections, active connections, bytes and rule evaluations.
Overload protection at the load balancer#
The LB is the natural place to stop overload before it reaches the servers.
- Connection and request limits. Cap concurrent connections and pending requests per backend (Envoy calls these circuit breakers). When a backend is full, fail fast or try another backend instead of queueing forever.
- Queue limits and timeouts. A request that waited 10 seconds in a queue is probably useless; the client has given up. Short queue timeouts keep latency bounded.
- Load shedding. Under extreme load, reject a fraction of low-priority traffic with 503 or 429 so the rest succeeds. Serving 80% of users well beats serving 100% badly.
- Retry budgets. Allow retries only while they stay under a fixed share of total traffic, so retries cannot multiply load during an outage. See Rate Limiting.
- Fair queueing per tenant, so one noisy customer cannot fill every server.
When to Use It#
- Any service with more than one instance, or that needs zero-downtime deploys.
- L7 for HTTP/gRPC services that need path routing, retries or header-based canaries.
- L4 for non-HTTP protocols (databases, MQTT, game servers), extreme throughput, or TLS passthrough.
- Global LB when you run in more than one region.
When NOT to Use It#
- A single small internal service with one instance may not need one, though even then a managed LB simplifies TLS and deploys.
- Do not put an L7 LB in front of systems with their own client-side routing (Cassandra drivers, Kafka clients); they connect to nodes directly.
How to Implement It#
- Choose managed vs self-hosted: managed for most teams; self-hosted Nginx, HAProxy or Envoy for fine control or on-premise.
- Pick L4 or L7 per traffic type.
- Pick the algorithm: least connections or least response time by default for APIs; consistent hashing for caches.
- Configure health checks, timeouts and connection draining.
- Make the LB redundant across zones, and put a global LB in front of regions.
# Nginx L7 load balancing (simplified)
upstream api {
least_conn;
server 10.0.2.11:8080 max_fails=3 fail_timeout=10s;
server 10.0.2.12:8080 max_fails=3 fail_timeout=10s;
server 10.0.2.13:8080 weight=2; # bigger instance
keepalive 64; # reuse backend connections
}
server {
listen 443 ssl http2;
location /api/ { proxy_pass http://api; proxy_next_upstream error timeout; }
}| Technology | Fits when |
|---|---|
| AWS ALB / Google Cloud HTTP(S) LB | Managed L7 for HTTP and gRPC |
| AWS NLB / Google TCP/UDP LB | Managed L4, static IPs, very high throughput |
| Nginx | Reverse proxy and L7 LB, static file serving |
| HAProxy | High-performance L4/L7, rich health checks |
| Envoy | Service mesh sidecars, gRPC, advanced L7 features |
| Cloudflare, Route 53 | Global load balancing across regions |
Hardware, software and cloud load balancers#
Dedicated load balancers come in three forms:
- Hardware appliances such as F5 BIG-IP and Citrix ADC (formerly NetScaler). These are purpose-built boxes, often with custom chips for TLS and packet processing, and they sit in on-premise data centers. They are very fast and feature-rich, and very expensive. Scaling means buying a bigger box, and they are usually deployed as active-passive pairs.
- Software load balancers such as HAProxy, NGINX, Envoy, Traefik and Linux IPVS, running on ordinary servers or containers. They are cheap, scriptable and easy to automate, and you scale them out by adding nodes behind ECMP or DNS.
- Cloud load balancers such as AWS Elastic Load Balancing (ALB for L7, NLB for L4, Gateway Load Balancer for inline appliances), Google Cloud Load Balancing and Azure Load Balancer and Application Gateway. These are software load balancers run by the provider, billed by use.
The largest internet companies moved away from appliances toward software running on commodity servers, because software scales out horizontally and can be changed quickly. Google's Maglev, Meta's Katran, GitHub's GLB and Cloudflare's Unimog are all software L4 balancers. In a typical product-design interview, scaling the load balancer itself is not the focus; a managed LB is a fine answer. If the numbers get extreme (millions of connections per second, hundreds of Gbps), mention a layered design with a scaled-out L4 tier, or hardware appliances in an on-premise setting.
| Tool | Layer | Strengths | Watch out for |
|---|---|---|---|
| HAProxy | L4 and L7 | Very fast, rich health checks, detailed stats, random(2) and hash-balance-factor | Config reloads need care at scale |
| NGINX | L7 (L4 via stream module) | Reverse proxy, static files, caching, huge community | Active health checks only in the commercial NGINX Plus |
| Envoy | L4 and L7 | gRPC, HTTP/2 and HTTP/3, outlier detection, xDS dynamic config, mesh data plane | Complex config, usually driven by a control plane |
| Traefik, Caddy | L7 | Automatic TLS with Let's Encrypt, easy container discovery | Fewer advanced traffic features |
| Linux IPVS, kube-proxy | L4 | In-kernel, fast, built into Kubernetes | Connection-level only |
| Katran (XDP/eBPF) | L4 | Line-rate forwarding in the kernel, consistent hashing | Needs specialist networking skills |
| AWS ALB / NLB | L7 / L4 | Managed, multi-zone, integrates with autoscaling and certificates | Per-hour and per-capacity-unit cost, limited tuning |
| Google Cloud Load Balancing | L4 and L7, global | Single anycast IP across regions | Provider lock-in |
| F5 BIG-IP | L4 and L7 | Mature enterprise features, hardware TLS | Cost, scale-up model |
Trade-offs#
| Choice | Pros | Cons | Pick when |
|---|---|---|---|
| L4 | Fast, cheap, any protocol | No HTTP-aware routing | Non-HTTP, raw throughput |
| L7 | Smart routing, retries, observability | More CPU and latency (~ms) | HTTP and gRPC services |
| Managed LB | No ops, multi-zone by default | Less control, per-hour and per-GB cost | Most cloud workloads |
| Self-hosted LB | Full control, cheaper at very large scale | You run its HA, scaling and upgrades | On-premise, special needs |
| Sticky sessions | Works with stateful apps | Uneven load, lost sessions on failure | WebSockets, temporary migration step |
| Client-side balancing | No extra hop, no central bottleneck | Logic in every client, slower updates | Internal services, smart drivers |
| Dedicated LB | Instant updates, clients stay simple | Extra hop, must be scaled and made HA | Public traffic, clients you do not control |
| NAT-mode L4 | Simple, works across subnets | LB carries replies, client IP hidden | Moderate traffic, simple networks |
| DSR or tunnelling | LB carries only the small inbound side | No response visibility, special backend setup | Video, downloads, very high throughput |
| Active-passive pair | Simple, well understood | Idle standby, seconds of failover, one L2 network | On-premise, small scale |
| Active-active with ECMP | All nodes work, scales out | Needs BGP and consistent hashing across nodes | Large edges, self-built L4 tiers |
| Least connections | Evens out long-lived connections | Rushes new servers without slow start | WebSockets, SSE, uneven requests |
| Consistent hashing affinity | Cache hits, known owner per key | Hot keys, rebalancing on membership change | Caches, chat servers, shards |
| Pub/sub instead of affinity | Any server can hold any connection | Extra hop, at-most-once delivery | Large chat and notification systems |
| DNS-based GSLB | Simple, any protocol | Failover bounded by caching | Multi-region with relaxed failover |
| Anycast GSLB | Fast failover, one IP | Needs a global network or provider | Global low-latency services |
Common Pitfalls#
- Deep health checks that fail all servers when one dependency is slow.
- No connection draining, so every deploy drops requests.
- Round robin with long-lived connections, leaving new servers idle.
- LB retries on non-idempotent requests, causing duplicate orders.
- A single self-hosted LB node: the new SPOF.
- Liveness and readiness mixed up, so a slow dependency triggers restarts of healthy servers.
- Failing empty: removing every backend when all health checks fail, instead of failing open.
- Least connections without slow start, so each newly started server is flooded and crashes.
- Trusting
X-Forwarded-Forfrom any client, letting attackers spoof their IP for rate limits and audits. - gRPC or HTTP/2 behind an L4 balancer or kube-proxy, leaving new pods idle after scale-up.
- Modulo hashing for cache nodes, so adding one node empties almost the entire cache.
- IP-hash stickiness for mobile users behind carrier NAT, pinning huge user groups to one server.
- Regions sized with no failover headroom, so losing one region overloads the others.
- Pods that exit on SIGTERM before load balancers stop routing to them.
- Drain timeouts left at 300 seconds for short requests, making every deploy slow.
Real-World Examples#
GitHub has publicly described GLB, its own load balancer built for its data centers, as an example of a large company building a custom LB at scale.
Envoy, originally built at Lyft, is now widely used as an L7 proxy and as the data plane of service meshes such as Istio.
Google described Maglev in "Maglev: A Fast and Reliable Software Network Load Balancer" (Eisenbud and others, NSDI 2016). It is a distributed software L4 balancer on commodity Linux servers that had been serving Google's traffic since 2008. Routers spread packets across Maglev machines with ECMP. Each machine picks backends with its own consistent hashing method, so any machine makes the same choice for a flow, and it uses GRE encapsulation so backends reply directly to clients.
Meta open-sourced Katran in 2018. It is an L4 load balancer built on XDP and eBPF that processes packets in the Linux kernel's network driver path, before the normal networking stack, and runs alongside other workloads on the same hosts.
GitHub built GLB, its load balancer for its own data centers, and open-sourced the GLB Director in 2018. It uses a rendezvous-hashing-based forwarding table that stores a primary and a secondary server for each bucket, so a draining server can finish its existing connections while new ones go elsewhere ("second chance" forwarding).
Envoy was built at Lyft and open-sourced in 2016. It became the data plane for Istio and many other meshes, and it popularised outlier detection, retry budgets and dynamic configuration through xDS APIs.
Vimeo described adding consistent hashing with bounded loads (from Mirrokni, Thorup and Zadimoghaddam's paper "Consistent Hashing with Bounded Loads") to HAProxy, where it is exposed as hash-balance-factor, to keep cache affinity for video segments without letting popular content overload a single server.
In the Interview#
Putting load balancing on the whiteboard#
A strong interview answer covers load balancing in one or two sentences per layer, then goes deep only where the problem needs it:
- Edge: "Users resolve our domain through latency-based DNS or hit an anycast IP, which picks the nearest healthy region."
- Regional L7: "A managed L7 load balancer terminates TLS and routes by path:
/apito the API service,/uploadto the upload service." - Persistent connections: "WebSocket traffic goes through an L4 balancer using least connections, and chat servers find each other through pub/sub, so any server can hold any user."
- Internal calls: "Service-to-service calls use client-side balancing from service discovery, or a mesh sidecar."
- Stateful tiers: "The cache cluster is addressed by consistent hashing on the key, so adding a node moves only about 1/N of keys."
Then mention the operational basics once: health checks with readiness, connection draining on deploy, and LB redundancy across zones.
Common follow-ups and strong answers#
- "How does the load balancer know a server is down?" Active checks every few seconds plus passive outlier detection on real traffic; removal after a few failures, slow start on return, fail open if everything looks down.
- "Your WebSocket servers are unevenly loaded after a deploy. Why?" Long connections stay where they were placed. Use least connections with slow start, and on deploy have servers close connections gradually so clients reconnect with jitter.
- "How would you route a message to the server holding user B?" Either consistent hashing of users to servers with a membership registry, or a pub/sub channel per user. Explain the trade-off: affinity needs careful rebalancing; pub/sub adds a hop and at-most-once delivery.
- "What happens when you add a cache node?" With modulo hashing nearly all keys move and the database gets flooded; with consistent hashing and virtual nodes only about 1/N move, spread across all nodes.
- "Can the load balancer handle 1 million requests per second?" A managed cloud LB scales out on its own. Self-built: a layered design with ECMP across many L4 nodes, then a scaled-out L7 tier. On-premise, hardware appliances are an option.
- "How do you do a canary?" Weighted routing at the L7 LB, 1-5% to the new version, automatic rollback on error-rate or latency regressions.
Deep Dive: Client-side balancing, long connections and retry stormsShow
Client-side load balancing. Inside a data center, many systems skip a central LB. Each client gets the server list from service discovery and balances itself (gRPC clients, Finagle, Envoy sidecars). This removes a network hop and a central bottleneck, but every client needs the logic and up-to-date membership.
Long-lived connections defeat connection-level balancing. HTTP/2 and gRPC multiplex many requests on one connection, so an L4 LB balances connections, not requests: new servers get almost no traffic after a scale-up. Fixes are L7 balancing per request, or limiting maximum connection age so clients reconnect and spread out.
Least-connections can herd. Many independent LB instances each seeing a stale view can all pick the same "least loaded" server. Power of two random choices avoids this with almost no coordination.
Retries amplify load. An LB that retries failed requests on another server is helpful for isolated failures but dangerous during overload: each layer retrying 3 times turns 1 request into 3, 9, 27. Use retry budgets (for example, retries at most 10% of requests), only retry idempotent requests, and combine with circuit breakers.
Direct server return (DSR). Some L4 balancers let servers reply straight to clients, bypassing the LB on the way back. Since responses are usually much larger than requests, this greatly increases throughput for video or downloads.
Deep Dive: Inside software L4 load balancers (Maglev, Katran, GLB)Show
The problem they solve. A hyperscale edge receives tens of millions of packets per second per site. Appliances in active-passive pairs cannot scale out, and stateful connection tracking breaks when routers rehash flows. The answer every large operator arrived at is a fleet of stateless-ish software forwarders on ordinary servers, all making the same decision for the same flow.
Packet path. Edge routers announce the service VIPs and use ECMP to hash flows across forwarder machines. A forwarder receives a packet, looks up the 5-tuple in its local connection table, and on a miss computes a backend with a consistent hash. It records the choice, wraps the packet in an outer IP header (GRE, IP-in-IP or GUE) addressed to the backend, and sends it. The backend unwraps it, sees the original client IP and the VIP as destination, and replies straight to the client, bypassing the forwarder.
Maglev hashing. Maglev builds a lookup table of fixed prime size M (65,537 in the paper) that maps hash buckets to backends. Each backend gets its own permutation of the table positions, computed from two hashes of its name: an offset and a skip. The table is filled in turns. Each backend, in order, claims the next position in its permutation that is still empty, until the table is full. Every backend ends up owning almost exactly M/N positions, so load is very even, and lookups are a single array index. When a backend is removed, the table is rebuilt; most positions keep their old owner, though not quite as many as in a ring. The design trades a little extra disruption for near-perfect balance and O(1) lookups, and the connection table covers most of the remaining disruption.
Why both a connection table and consistent hashing. The table keeps existing flows stable when the backend set changes. Consistent hashing keeps flows stable when the forwarder set changes: if a router moves a flow to a different forwarder that has no table entry, that forwarder still computes the same backend. A flow is disrupted only when both change at once.
Running in the kernel or bypassing it. Maglev uses kernel bypass, moving packets between the network card and user space directly to avoid the normal networking stack's overhead. Katran uses XDP, which runs an eBPF program in the network driver before the kernel allocates its usual packet structures, so it can share hosts with other workloads while still forwarding at very high rates.
GLB's second chance. GitHub's GLB Director keeps no per-flow state on the forwarders at all. Its forwarding table stores two servers per bucket, a primary and a secondary, chosen by rendezvous hashing. The packet goes to the primary. If the primary does not recognise the flow (it was a new server, or it is draining), it forwards the packet to the secondary listed in the packet's encapsulation header. This lets a server drain gracefully: it becomes secondary for its buckets, new connections go to the new primary, and existing ones still find their way back.
Production lessons. These systems all invest heavily in health checking at scale, in staged config rollouts (a bad table pushed to every forwarder at once is a global outage), and in tools for safely draining forwarders and backends. Their papers and posts report that the hard parts were operations and failure handling, not the hashing.
Deep Dive: The math of balancing, subsetting and tail latencyShow
Join the shortest queue. In queueing theory, sending each job to the server with the shortest queue is close to optimal for many workloads. Random assignment behaves like N separate M/M/1 queues (single-server queues with random arrivals), and at high utilisation their waiting times blow up: an M/M/1 queue at 90% utilisation holds 9 jobs on average. Joining the shortest queue makes the fleet behave much more like one shared queue with N servers, where waits stay short until utilisation is very high. Two random choices captures most of that benefit with almost no state.
Tail latency compounds. If a page fans out to 100 backends and each has a 1% chance of a slow response, then 1 - 0.99^100, about 63%, of page loads include at least one slow response. Balancing that steers away from slow servers (peak EWMA, outlier ejection) and hedged requests (send a second copy to another server if the first has not answered by the 95th-percentile time) cut the tail. Dean and Barroso's "The Tail at Scale" (Communications of the ACM, 2013) explains these techniques.
Subsetting. With 1,000 clients and 1,000 backends, if every client connects to every backend you need a million connections, each with memory, keep-alive traffic and health-check cost. Subsetting gives each client a small subset, say 20-50 backends, and balances within it. Random subsets give uneven load: some backends end up in many more subsets than others. Google's Site Reliability Engineering book (2016, chapter "Load Balancing in the Datacenter") describes deterministic subsetting, which shuffles backends in rounds and hands out non-overlapping slices so each backend serves almost exactly the same number of clients.
Server-reported load. Client-side counts only see the client's own traffic. The same SRE chapter describes weighted round robin where backends report their utilisation and success rate in response metadata, and clients adjust weights accordingly. It also describes a lame duck state: a backend that is shutting down tells clients to stop sending new requests while it finishes current ones, which is draining done at the protocol level.
Bounded-load consistent hashing. Plain consistent hashing ignores load. Mirrokni, Thorup and Zadimoghaddam's "Consistent Hashing with Bounded Loads" (2018) sets a cap of, say, 1.25 times the average load per server. A key goes to its normal ring owner unless that owner is at the cap, in which case it moves clockwise to the next server with room. You keep most of the affinity, and no server ever runs more than 25% above average, which is exactly what a cache tier facing hot content needs.
Ring variance in numbers. With one point per server, the largest arc is about ln N times the average, so with 100 servers the unluckiest one owns several times its fair share. With V virtual nodes per server, the standard deviation of each server's share shrinks roughly as 1 over the square root of V: 100 virtual nodes gives about 10% spread, 400 gives about 5%. This is why rings use hundreds of virtual nodes, and why table-based schemes like Maglev, which hit near-perfect balance by construction, are attractive.
Key Takeaways#
- Load balancers spread traffic, remove unhealthy servers and enable zero-downtime deploys.
- L4 routes connections by IP and port; L7 understands HTTP and routes requests by path, headers and cookies.
- Choose the algorithm by workload: round robin for uniform, least connections or response time for uneven, consistent hashing for keyed data.
- Use cheap health checks, connection draining, and avoid sticky sessions by keeping servers stateless.
- Make the LB redundant, and use DNS or anycast global load balancing to choose a region.
- Scale up first if one machine is enough; once you scale out, keep servers stateless and watch downstream connection counts.
- Balancing can live in the client (registry, Redis Cluster, DNS), in a dedicated LB, or in a sidecar; use dedicated LBs for clients you do not control.
- L4 places connections and suits WebSockets and non-HTTP traffic; L7 places requests and is needed for HTTP/2 and gRPC per-request balancing.
- Two random choices gives near-optimal balance with stale information; pure least-loaded selection herds when many balancers share a view.
- Modulo hashing moves almost every key when the pool changes; consistent hashing with virtual nodes moves about 1/N, but hot keys still need replication or splitting.
- Use readiness checks, passive outlier detection, slow start, connection draining, and fail open when every check fails.
- Make the LB itself redundant: active-passive with VRRP, active-active with ECMP and consistent hashing, or a managed multi-zone service.
- Global load balancing picks a region by latency, health, capacity and data rules, and regions need headroom to absorb a failed neighbour.
- When servers hold state such as sockets, balancing becomes routing: choose affinity by consistent hashing, or indirection through pub/sub.