System Design · Concept Library · Free article
Load Balancing — One Front Door for a Pool
Why the answer to “one server can’t take the traffic” isn’t a bigger server — it’s many servers behind one address, and the thing that makes that possible. From what a load balancer is up through L4 vs L7, the balancing algorithms, health checks, failover, and the day the balancer itself goes down — for interns through principal engineers.
A load balancer is a single front door that spreads incoming requests across a pool of identical servers, so no one box is overwhelmed and any box can fail without taking the site down. Once one server can’t keep up, you don’t buy a bigger one — you run many and put a load balancer in front: clients talk to one stable address, and the balancer fans each request out to a healthy backend. The interesting parts are all in how it chooses: a Layer 4 balancer routes by raw connection (fast, but it can pin a chatty client to one box); a Layer 7 balancer reads each request and spreads them individually (smarter, the usual default). On top of that sits the algorithm (round-robin, least-connections, hashing…), health checks that pull dead backends out of rotation, and the uncomfortable truth that the balancer is now itself a single point of failure — so it, too, must be made highly available. This page takes you from the stake all the way to failover, measuring imbalance, and when a load balancer is the wrong tool.
The 2am page: one box, pegged at 100%
By the Hug of Death chapter, Hatch had a cache, and reads were a cool ~10ms from memory. It felt unbreakable. Then Maya — your creator with two million followers — posts one of your links, and two million people tap it inside a minute. Your phone lights up: app-server CPU flatlined at 100%, requests timing out.
Here’s the trap, and it catches almost everyone: the cache made each read cheap, but it didn’t make the reads fewer. Every one of those ~12,000 requests a second still lands on an app server to do its small job — check the cache, return the URL — and a single box runs out of CPU and open connections long before it runs out of things to do. A faster cache can’t save you here, because the bottleneck isn’t the cache. It’s that one machine can only do so much work per second, full stop.
So you reach for the obvious fix: run more than one app server. If one box caps out near ~500 requests a second, then ~25 boxes could share 12,000. Easy — except the moment you have a second server, a brand-new question appears that you never had to answer before: when a request arrives, which server does it go to? The browser only knows one address. It can’t know there are now twenty-five boxes behind it, and it certainly can’t be trusted to spread itself evenly across them.
You need something to sit in front of the pool — one address the whole world talks to — that takes each incoming request and hands it to one of the servers behind it, keeping the load even and steering around any box that’s struggling. That thing is a load balancer, and it’s the single piece that turns a pile of servers into a pool.
What a load balancer actually is
Strip away the jargon and a load balancer is a traffic director. It’s a single, stable address — one IP, one hostname like hatch.ly — that every client connects to. Behind it sits a pool of identical servers that the outside world never sees directly. When a request arrives, the balancer picks one healthy server from the pool and forwards the request to it; the reply comes back through the balancer to the client. The client thinks it’s talking to one machine. It’s really talking to one doorway in front of many.
That indirection — clients hit a front door, not the servers themselves — is the whole trick, and it buys you four things at once. Each one is worth saying in plain terms before it gets a name.
- Spread the load. No single box drowns, because every request is handed to whichever server has room. Twelve thousand requests a second become ~500 each across twenty-five boxes.
- Survive a dead box. If a server crashes, the balancer stops sending it traffic and the rest of the pool absorbs the load. Users never notice (this is availability).
- Grow and shrink on demand. Spin up more servers when the spike hits, register them with the balancer, and traffic flows to them immediately; remove them when it passes. The front door stays the same address the whole time (this is elastic horizontal scaling).
- Hide the messy inside. Clients only ever know one address. You can deploy, replace, move, or renumber the servers behind it without anyone outside changing a thing.
Layer 4 vs Layer 7: how much does the balancer *read*?
Every load balancer has to make one decision per arriving request — which backend? — and the first big question is how much of the request it looks at to decide. This is the L4-vs-L7 split, and the names come from where each one operates in the network stack (the network layers page has the full ladder). You don’t need the OSI model memorised; you need the one practical difference.
A Layer 4 load balancer works at the transport level. It sees a connection’s source and destination IP and port — the envelope — and nothing inside. It picks a backend based on that envelope and then forwards the raw bytes back and forth, never opening them. It’s like a mailroom that routes sealed boxes by zip code: blindingly fast, because it isn’t reading anything, but it has no idea what’s in the request.
A Layer 7 load balancer works at the application level. It actually terminates the connection, reads the HTTP request — the URL path, the headers, the cookies — and routes based on what it sees. It can send /api/ to one pool and /images/ to another, pin a user to a server by a cookie, retry a failed request on a different backend, or strip away TLS so the servers behind it don’t have to. All of that costs CPU (it’s parsing every request), but it’s smart: it sees individual requests, so it can spread them individually.
That last difference is the one that bit Hatch, so let’s make it concrete.
Watch it happen. Below, a few clients each open a long-lived connection and send a stream of requests. Flip between an L4 balancer (routes the connection once, then pins it) and an L7 balancer (routes every request), and watch how evenly — or unevenly — the pool fills:
The interactive version of this example is available when JavaScript loads.
| Layer 4 (transport) | Layer 7 (application) | |
|---|---|---|
| Routes by | IP + port (the connection envelope) | URL, headers, cookies (the request content) |
| Reads the payload? | No — forwards raw bytes | Yes — terminates and parses each request |
| Speed / cost | Very fast, low CPU, low latency | More CPU per request (it parses everything) |
| Spreads a chatty connection? | No — pins the whole connection to one box | Yes — distributes each request individually |
| Can do | Plain connection forwarding; great for non-HTTP (databases, game servers, SMTP) | Path/host routing, TLS termination, retries, rate limiting, header rewriting, sticky cookies |
| Reach for it when | You need maximum throughput or aren’t speaking HTTP | You’re balancing HTTP/gRPC and want content-aware, even routing — the usual default |
The balancing algorithms: which backend gets the next request?
Once you’ve decided how much the balancer reads (L4 vs L7), there’s a second choice underneath it: given a set of healthy backends, which one gets this request? That rule is the balancing algorithm, and the differences are all about how much the balancer knows and how much it bothers to track. They sort into two families — ones that ignore how busy each server actually is, and ones that pay attention.
The “don’t track anything” family — simple, stateless
- Round-robin — hand requests out in a rotation: server 1, 2, 3, 1, 2, 3… It’s the default for a reason: dead simple, and perfectly even when every request costs about the same and every server is identical. Its weakness is exactly those assumptions — one slow request can leave a server still chewing while the rotation keeps dumping more on it.
- Weighted round-robin — the same rotation, but a beefier server (more CPU) gets a bigger share. Use it when your pool is a mix of machine sizes.
- Random — just pick a backend at random. Surprisingly decent at scale (the law of averages evens it out) and needs zero bookkeeping. Its smarter cousin is “power of two choices”: pick two backends at random and send the request to the less-busy of the two — almost as cheap as random, but it dodges the worst pile-ups.
The “watch the servers” family — adaptive, a little more work
- Least-connections — send the next request to whichever backend currently has the fewest open connections. This adapts to reality: if one server is bogged down with slow requests, its connection count stays high and the balancer naturally steers traffic away from it. The go-to when request durations vary a lot.
- Least-response-time — like least-connections, but it also weighs how fast each backend has been answering lately, favouring the genuinely quickest. The most “aware” of the common algorithms.
- Hashing / consistent hashing — route by a key (the client’s IP, a user ID, a cache key) so the same key always lands on the same backend. You give up perfect evenness to get stickiness — and it’s the backbone of sharded caches and databases. It’s subtle enough to deserve its own beat, just below.
Feel the difference. Below, a stream of requests of uneven cost arrives at a pool. Switch the algorithm and watch how level the servers stay — notice round-robin getting unlucky when a slow request lands, and least-connections quietly routing around the busy box:
The interactive version of this example is available when JavaScript loads.
Consistent hashing: stickiness that survives a resize
Hashing to choose a backend sounds trivial — server = hash(key) % N — until you change N. Add or remove a single server and that % N changes for almost every key at once: nearly the whole keyspace gets reshuffled to a different backend. For a stateless app pool that’s merely wasteful; for a cache or a shard, it’s a disaster — every key suddenly maps to the wrong node, so the entire cache misses at once and stampedes the database (the very stampede you met in the Caching chapter, triggered by a deploy).
Consistent hashing is the fix, and the mental picture is a ring. Imagine a clock face. You hash each server to a position on the ring, and you hash each key to a position too; a key belongs to the first server you meet walking clockwise from its spot. Now add a server: it drops onto one point of the ring and steals only the slice of keys between it and the previous server — every other key stays put. Remove a server and only its slice moves to the next one along. Instead of reshuffling everything, a resize disturbs roughly 1/N of the keys.
Add and remove a server on the ring below and watch how few keys actually change colour — only the slice next to the change is re-painted. Then flip on “virtual nodes,” the trick that keeps the ring from clumping:
The interactive version of this example is available when JavaScript loads.
Health checks & draining: keeping the pool honest
A balancer spreading load evenly across servers is only safe if it knows which servers can actually take it. Send requests to a box that just crashed, or one still booting, and the user gets an error even though the rest of the pool is fine. So a load balancer is constantly asking each backend a quiet question — “are you OK?” — and routing only to the ones that say yes. That’s a health check, and there are two flavours of asking.
- Active health checks — the balancer probes each backend on a schedule: every few seconds it hits a
/healthendpoint and expects a200 OK. Miss a few in a row (the unhealthy threshold) and the backend is pulled out of rotation; pass a few in a row again (the healthy threshold) and it’s let back in. The thresholds exist so a single blip doesn’t yank a server, and a server doesn’t rejoin the instant it twitches back. - Passive health checks — instead of probing, the balancer watches real traffic: if a backend starts returning errors or timing out on actual requests, it’s marked unhealthy. Cheaper (no extra probe traffic) and faster to notice a real problem, but it learns by failing real user requests first. Most setups use both — active to catch a dead box before users do, passive to catch a sick one mid-flight.
Health checks also matter going the other way — when you deliberately take a server out, to deploy or scale down. Yank it instantly and you kill every request it was mid-way through serving. Instead you drain it: the balancer stops sending it new requests but lets the in-flight ones finish (a connection draining or deregistration delay window), then removes it cleanly. The mirror image is slow-start: when a fresh server joins, ramp its traffic up gradually instead of slamming it with a full share before its caches and connection pools are warm.
Watch a pool heal itself. Kill a backend and see the balancer notice, pull it out, and reroute its traffic to the survivors — then bring it back and watch it drain and rejoin:
The interactive version of this example is available when JavaScript loads.
Sticky sessions — and why statelessness beats them
Here’s a problem you hit the moment you have a pool. A user logs in, and their session — who they are, what’s in their cart — gets stored in the memory of whichever server handled the login. Their next request gets balanced to a different server, which has never heard of them, and suddenly they’re logged out. The load balancer did its job — it spread the requests — and that’s exactly what broke things.
The quick fix is sticky sessions (a.k.a. session affinity): tell the balancer to keep sending the same user back to the same server, usually by setting a cookie or hashing their IP. Now the server that holds their session always gets their requests. Problem solved… and three new ones created.
Why sticky sessions quietly hurt
- They re-create imbalance. Pinning users to servers undoes the even spreading you added the balancer for — a few heavy users stuck on one box re-introduce the hot-server problem.
- They lose data on a crash. If the server holding a user’s session dies, that session is gone — the user is logged out, their cart emptied. The whole point of a pool was that any box can die harmlessly; sticky state breaks that promise.
- They fight scaling. Add a new server and it gets no existing users (they’re all stuck to old boxes); drain an old one and its users scatter. Elasticity gets clumsy.
The load balancer is now a single point of failure
Step back and look at what you’ve built. Every request to Hatch now flows through one load balancer. You added it so that no single server could take the site down — and in doing so you funnelled the entire world through a single box whose death takes down everything. You moved the single point of failure; you didn’t remove it. If that one balancer crashes, it doesn’t matter that twenty-five healthy app servers are sitting right behind it — nobody can reach them. This is the question that separates a toy design from a real one: who balances the balancer?
The answer is to never run just one. You run the load balancer itself as a redundant pair (or more), so the failure of any single balancer is invisible. There are a few standard ways to do it.
| Approach | How it works | The trade |
|---|---|---|
| Active–passive + floating IP | Two balancers; one is live, one is a hot standby. A floating (virtual) IP points at the active one. A heartbeat between them watches for death; if the active dies, the IP “floats” over to the standby, which takes over in seconds (VRRP / keepalived). | Simple and proven. But half your capacity sits idle as standby, and there’s a brief failover blip while the IP moves. |
| Active–active | Two or more balancers all live at once, all taking traffic (clients are spread across them by DNS or anycast, below). If one dies, the others simply carry its share. | No idle capacity and no single failover moment — but every balancer must be sized to absorb a peer’s load, and shared state (if any) is harder. |
| DNS load balancing | Publish several balancer IPs under one hostname (multiple A records). Clients resolving hatch.ly get handed different IPs, spreading them across balancers — a crude balancer in front of your balancers. | Free and built-in, but DNS is cached by clients and resolvers, so a dead IP keeps getting handed out until the TTL expires. Coarse and slow to react. |
| Anycast (BGP) | Announce the same IP from many data centres at once. The internet’s own routing (BGP) sends each user to the nearest one. If a whole site drops, routes converge to the next-closest automatically. | The planet-scale answer (it’s how CDNs and big DNS work) — but it needs control of network routing and is well beyond a single-rack setup. |
The everyday default is the first one: a pair of balancers and a floating IP. Watch it work — kill the active balancer and see the virtual IP jump to the standby, traffic barely flinching:
The interactive version of this example is available when JavaScript loads.
Measuring & debugging a load balancer
Most write-ups stop at the algorithms. But a balancer you can’t see is one you can’t trust — and the most common production surprise isn’t the balancer dying, it’s the balancer quietly sending uneven load while every dashboard looks “green.” A few numbers tell you almost everything, and the skill is reading them per backend, not just in aggregate.
| Metric | What it tells you | When to worry |
|---|---|---|
| Per-backend request rate | How evenly traffic is actually spread across the pool. | One server far above the others → imbalance (L4 connection pinning, a bad hash, or sticky sessions). |
| Healthy host count | How many backends are currently in rotation. | Dropping → backends are failing health checks; if it hits zero the site is down even though the LB is up. |
| Per-backend latency / errors (p99, 5xx) | Whether one backend is sick while the rest are fine. | One box’s p99 or 5xx climbing → drain it; a pool-wide climb → you’re out of capacity, add servers. |
| Surge queue / rejected connections | Requests the balancer is holding or dropping because no backend can take them. | Anything above zero for long → the pool is saturated; scale out. |
| Active connections per backend | The real-time depth feeding least-connections. | A lopsided distribution with round-robin → long-lived connections are pinning load; consider least-connections or L7. |
The cost, and when you don’t need one
A load balancer is close to mandatory the moment you run more than one server — but it isn’t free, and pretending otherwise is how you over-engineer a small app. It costs an extra hop (every request now passes through one more box, adding a little latency), it’s one more thing to run and make highly available (an L7 balancer terminating TLS for millions of requests is itself a serious system), and a managed cloud balancer is a real line on the bill (priced per hour and per gigabyte of traffic). You take all that on to buy capacity and resilience — so make sure you actually need them.
When a load balancer is overkill
- You genuinely run one server and one is plenty. A side project or an internal tool with modest traffic doesn’t need a pool — a single right-sized box (and good backups) is simpler and cheaper. Add the balancer when you add the second server.
- The bottleneck isn’t compute. If your app servers are bored and the database is the thing falling over, a load balancer in front of the app tier does nothing — you need caching, read replicas, or sharding behind it, not more front doors.
- A CDN already absorbs it. For static assets, a CDN at the edge serves the traffic before it ever reaches your origin — no app-tier balancing required for that slice.
The landscape: hardware, software, and cloud
You don’t need to memorise products — you need to know the three shapes a load balancer comes in and which one you’d actually reach for. (Each of these tools is deep enough for its own page; here it’s enough to place them.)
| Shape | What it is | Reach for it when |
|---|---|---|
| Software | A program you run on ordinary servers — nginx, HAProxy, Envoy. Flexible, cheap, runs anywhere, the engine inside most modern setups (Envoy is the data plane of many service meshes). | You want control and portability, you’re already on your own machines or Kubernetes, or you need L7 features without a cloud bill per request. |
| Cloud / managed | A balancer your cloud runs for you — AWS ALB (L7) / NLB (L4), GCP and Azure equivalents. You click it into existence; health checks, autoscaling, and HA are handled. | The default for most teams. You want it to just work and to scale itself, and you’re fine paying per hour + per GB to not operate it. |
| Hardware | A dedicated physical appliance (F5 BIG-IP, Citrix) engineered for enormous throughput, often with specialised chips for TLS. | Very high, steady traffic in your own data centre where a purpose-built box earns its (large) keep. Rarer now that software + cloud have caught up. |
A load balancer, in actual config
The ideas on this page are usually configuration, not code — a few lines that declare a pool, an algorithm, and a health check. Here’s the same balancer expressed three ways: an nginx upstream, an HAProxy backend, and the cloud-console equivalent in plain terms — so the page maps straight onto what you’d actually write.
The interactive version of this example is available when JavaScript loads.
Pitfalls: the silent load-balancer traps
- Running a single load balancer. It’s now the single point of failure for everything behind it. Always run a redundant pair (active-passive + floating IP, or active-active) — an un-balanced balancer is a time bomb.
- L4 balancing for long-lived HTTP/2 or gRPC. Connection pinning glues a chatty client’s entire request stream to one backend. Use L7 (per-request) or least-connections so the load actually spreads.
- Sticky sessions instead of stateless servers. Affinity re-creates imbalance and loses sessions when a box dies. Externalise session state (Redis / a token) and let any server serve any request.
- Shallow health checks. A
/healththat returns 200 while the database is unreachable keeps a broken box in rotation. Check the real dependencies — but not so deeply that one flaky downstream marks the whole pool unhealthy. - Plain
hash % Nfor a cache or shard. Adding or removing one node reshuffles nearly every key at once and stampedes the backend. Use consistent hashing (with virtual nodes). - No connection draining on deploy. Yanking a server instantly kills its in-flight requests. Drain it — stop new traffic, let existing requests finish — then remove it.
- Round-robin with wildly uneven request costs. It keeps dumping work on a server already stuck on a slow request. Switch to least-connections so traffic routes around the busy box.
- Forgetting the balancer adds a hop. Every request now crosses one more box; for latency-critical internal calls that hop (and TLS termination) isn’t free — measure it.
Best practices
- Default to a Layer 7 balancer for HTTP — per-request routing, content awareness, TLS termination — and drop to L4 only for raw throughput or non-HTTP protocols.
- Always run the balancer redundantly (active-passive + floating IP at minimum). The front door must not be a single point of failure.
- Make the app servers stateless — push session state to a shared store or a token — so any backend serves any request and the balancer can spread freely.
- Pick the algorithm to fit the traffic: round-robin for uniform requests, least-connections for variable durations, consistent hashing (with virtual nodes) when keys must stick.
- Health-check at the right depth — enough to prove the box can serve, not so deep that one flaky dependency downs the whole pool — and tune the healthy/unhealthy thresholds.
- Drain on the way out, slow-start on the way in — let in-flight requests finish before removing a server, and ramp a fresh one up gradually.
- Watch the spread, not the average — per-backend request rate, latency, and healthy-host count catch imbalance and creeping failure before users do.
- Add the balancer when you add the second server — not before (overkill) and not after the first outage (too late).
Rapid-fire cheat-sheet (intern → principal)
- "What is a load balancer and why use one?"
- A single front door that spreads requests across a pool of identical servers. It lets you scale out (no one box drowns), survive a server dying (it’s pulled from rotation), grow and shrink elastically, and hide the servers behind one stable address.
- "Layer 4 vs Layer 7 — what’s the difference?"
- L4 routes by IP and port without reading the request — fast, but it pins a whole connection to one backend (bad for long-lived HTTP/2 or gRPC). L7 reads each request and routes on path, headers, or cookies — spreads requests evenly and can terminate TLS, retry, and rate-limit, at more CPU cost. Default to L7 for web traffic.
- "Which balancing algorithm, and when?"
- Round-robin (or weighted, for mixed hardware) for uniform, cheap requests. Least-connections when request durations vary, so traffic routes around a busy box. Consistent hashing when a key must keep hitting the same backend — a sharded cache or shard.
- "Why consistent hashing instead of hash % N?"
- Plain
hash % Nremaps almost every key when you add or remove one node — a deploy then misses the entire cache at once and stampedes the DB. Consistent hashing (a ring) only moves ~1/N of the keys on a resize; virtual nodes keep the spread even. - "How does the balancer know a server is healthy?"
- Health checks. Active = the LB probes a /health endpoint on a schedule and pulls a backend after N failures (restores after N successes). Passive = it watches real traffic for errors. Keep the check deep enough to prove it can serve, but not so deep one flaky dependency downs the pool.
- "What are sticky sessions, and why avoid them?"
- Session affinity pins a user to the server holding their session. It re-creates imbalance, loses the session if that box dies, and fights scaling. The fix is stateless servers — push session state to Redis or a token — so any server serves any request.
- "Isn’t the load balancer itself a single point of failure?"
- Yes — that’s the key follow-up. You run it redundantly: active-passive with a floating IP that fails over to a standby in seconds, or active-active behind DNS/anycast. Every component you add to remove a SPOF becomes the new SPOF until you make it redundant too.
- "You scaled out but one server is pegged while others idle — why?"
- Almost always routing, not capacity. L4 pinning long-lived connections, sticky sessions gluing heavy users to one box, or round-robin with very uneven request costs. Fixes: go L7 / least-connections, externalise session state, or use weights — not a bigger balancer.
- "What happens when you deploy or remove a server?"
- Drain it: stop sending new requests but let in-flight ones finish (connection draining / deregistration delay), then remove it. For a server joining, slow-start — ramp traffic up so it isn’t slammed before its caches and pools are warm.
- "How would you make a service handle 100× more traffic?" (the meta-question)
- Confirm compute is the bottleneck → make the app servers stateless → put them in a pool behind an L7 load balancer → pick an algorithm for the traffic shape → add health checks + draining → make the balancer itself HA (pair + floating IP) → for multi-region, GSLB picks the region and a regional LB picks the server → watch the per-backend spread to prove it’s even.
The takeaway
By GOAT Engineer. Back to Concept Library. Privacy Policy · Contact.