Load balancers explained: layer 4 vs layer 7, algorithms and health checks
How one address can serve millions of requests. Layer 4 versus layer 7, how a balancer picks a server, why consistent hashing exists, what health checks catch, and why sticky sessions are usually a smell, with numbers from tested code.
10:09 video9 min read
- 2 architecture diagrams
- 1 sequence flow
- 2 interviewer follow-ups
- 3 self-checks
80% vs 20%
keys that move going from 4 to 5 servers: hash mod N versus consistent hashing
121 vs 101
load on the busiest of 50 servers: random placement versus two choices
L4 + L7
the usual pairing: raw speed at the edge, content-aware routing inside
On this page11 sectionsHLDSenior depth
- Why a load balancer exists, and what it must never become: a single point of failure.
- The difference between layer 4 and layer 7, and why real systems often use both.
- How round robin, least connections and power of two choices differ, and when each wins.
- Why consistent hashing and virtual nodes exist, what health checks catch, and why to avoid sticky sessions.
Ten million people open the same app at the same second, and they all send requests to one address. No single server can answer ten million requests at once, so something must sit in front of that address and decide, for every request, where it goes. Most engineers can name that something. This post explains how it works.
Every server has a ceiling. However well you optimise, there is a point where requests arrive faster than one machine can answer them, latency climbs, queues back up and requests time out. You can buy a bigger machine, which runs out fast and gets expensive, or more machines, which scales. But as soon as there is more than one server, someone must decide which one gets each request.
That is the load balancer. From outside, there is one address. Behind it is a pool of servers, three or three hundred, and the balancer is the only thing the outside world touches. You can add servers during a spike, remove them when it is quiet, and take one out for an upgrade in the afternoon: it leaves the pool, updates and rejoins while the front door never blinks. The pool changes all day. The address does not.
Balancers work at one of two levels, and interviewers like the difference.
| Layer 4 (transport) | Layer 7 (application) | |
|---|---|---|
| Sees | Addresses, ports, TCP or UDP | HTTP method, path, headers, cookies |
| Decides by | The connection | The request |
| Cost | Very fast, little work per connection | More work per request |
| Can do | Spread connections of any protocol | Route /api and /video differently, rewrite, authenticate, split traffic for canaries |
A layer 4 balancer never opens the request, so it is fast and works for any kind of traffic, but it cannot route by content. A layer 7 balancer reads the request, so it can send paths to different services and do smarter things, at the cost of more work. Real systems often use both: a layer 4 balancer at the very front for raw speed (a cloud network load balancer is this), and layer 7 proxies such as NGINX, HAProxy or Envoy closer to the services, routing by content.
Once there is a pool, the balancer needs a rule.
| Rule | Use it when | Watch out for |
|---|---|---|
| Round robin | Servers are identical and requests cost about the same | A slow request can land on a server already buried in slow requests, and the balancer does not know |
| Weighted round robin | Servers differ in size | Weights are static, so they must be tuned by hand |
| Least connections | Request durations vary a lot | Needs the live connection count for every server |
| Power of two choices | You want most of the benefit of least connections without a global view | Needs a load signal from the two servers it samples |
These are what real balancers ship. NGINX uses round robin by default and offers least_conn. Envoy's least-request balancer, with equal weights, picks two hosts at random and sends to the less loaded one, which is power of two choices.
The tested C# in the load balancing lesson shows why that is worth having. Put 5,000 long-lived requests on 50 servers, an average of 100 each. Random placement leaves the busiest server at 121. Sampling two and taking the less loaded leaves it at 101. The extra sample costs one comparison, and no balancer needs a global view or a lock.
Sometimes you do not want an even spread. You want the same key to land on the same server every time, for a cache, say, so that server stays warm. The obvious way is the user id modulo the number of servers. It works until a server dies or you add one: going from four servers to five changes the answer for most keys, every cache goes cold, and the database takes the hit.
Consistent hashing places both servers and keys around a ring. A key walks clockwise until it meets the first server. Now when a server is added or removed, only the keys next to it move. In the lesson's tested sample, going from four to five servers moves about 20% of keys with a ring, all of them to the new server, against about 80% with hash mod N.
One catch: with a handful of servers on the ring, one may own a huge slice and another a sliver. The fix is virtual nodes: each real server appears at many points on the ring (100 to 200 is common), which evens out the shares. This is the detail interviewers like and many candidates forget. You can watch both effects in the consistent hashing lab, and compare balancing algorithms in the load balancing arena.
Consistent hashing is also real infrastructure: NGINX has hash ... consistent, and Envoy offers ring hash and Maglev, a consistent-hashing variant with a fixed lookup table.
A balancer is only as good as its knowledge of which servers are alive. If it keeps sending traffic to a crashed server, every one of those requests fails. So it checks.
- Active checks: the balancer asks each server, on a schedule, "are you okay?" A server that misses a few checks in a row, say three a couple of seconds apart, is pulled from rotation.
- Passive checks: the balancer watches the real traffic, and a server that starts returning errors or timing out is marked unhealthy.
The best setups use both. The hardest case is a server that is slow but still answers its check: it keeps receiving traffic while latency climbs. Defend with outlier detection that ejects servers on error rate or latency, sensible timeouts, and bounded retries.
The server failed and nobody outside knew. When you deploy, use the same mechanism on purpose: fail the readiness check, let in-flight requests finish, then stop the process.
Sometimes a user must return to the same server: it keeps their login session in its own memory, and any other server has never heard of them. Sticky sessions pin a user to one server, usually with a cookie. It works, but it fights what a balancer is for. A pinned user cannot be moved, so load stops spreading evenly, and when that server dies everyone pinned to it loses their session at once.
The cleaner answer is to not need stickiness: move the session into a shared store every server can read, so any server can serve anyone. The balancer goes back to its real job.
Cover four things in order: why a balancer is needed (horizontal scaling, which needs stateless servers), how it chooses (and what in the workload decides the algorithm), how it notices failure (health checks), and how the balancer itself avoids being a single point of failure (more than one, with a shared address or anycast). Then offer consistent hashing only where you need affinity, such as a cache.
Interviewer follow-upL6Why not use consistent hashing for all load balancing?How to answer
Because it optimises for affinity, not for even load. Hashing sends all requests for a popular key to one server however busy it is, so a hot key becomes a hot server, and it does not react to load. For stateless services you want the even spread of least connections or two choices. Use hashing where moving a key has a real cost, such as a cache or a stateful shard, and add bounded-load variants if a few keys dominate.
Interviewer follow-upL6How do you balance long-lived connections such as WebSockets?How to answer
Round robin at connect time piles up connections on older servers, because connections last hours. Use least connections, and plan for rebalancing: when you deploy or scale, drain gradually and make clients reconnect with jittered delays, so thousands of clients do not reconnect in the same second and overload the servers that remain. Track connection count and memory per server, not just request rate.
QuestionWhat is the difference between a layer 4 and a layer 7 load balancer, and why use both?Reveal answer
Layer 4 forwards connections using addresses and ports without reading the request, so it is fast and protocol-agnostic. Layer 7 reads the request, so it can route by path or header and do smarter things, at more cost. A layer 4 balancer at the edge in front of layer 7 proxies gives speed on the outside and content-aware routing inside.
QuestionWhy does hash mod N cause trouble when a server is added, and how does consistent hashing help?Reveal answer
Changing N changes the result for most keys, so most keys move, caches go cold and the database is hit. With consistent hashing on a ring, only the keys next to the added or removed server move, about 20% going from four to five servers in our sample, against about 80% with modulo.
QuestionWhy are sticky sessions usually a smell?Reveal answer
They pin users to one server, so load cannot spread evenly and a server failure drops every session pinned to it. Keeping session data in a shared store lets any server serve anyone.
The load balancing lesson has the tested C# for least connections and power of two choices, and the replication and sharding lesson has the tested hash ring with virtual nodes. Try both ideas in the load balancing arena and the consistent hashing lab.
- NGINX, Using nginx as HTTP load balancer (opens in a new tab): round robin,
least_conn,ip_hash. - Envoy, Supported load balancers (opens in a new tab): weighted least request (power of two choices), ring hash, Maglev.
- Mitzenmacher, "The power of two choices in randomized load balancing", IEEE Transactions on Parallel and Distributed Systems (2001).
- Karger et al., "Consistent hashing and random trees", ACM STOC (1997).
Spot a mistake, or have a question?
Accuracy matters here. Tell me what looks wrong or unclear and I will fix it and credit you.