Load balancing: L4 vs L7
What a load balancer sees at layer 4 and layer 7, how the main algorithms choose a server, and how health checks, draining and redundancy keep traffic flowing.
The problem
A team runs its API on one server, which copes with about 2,000 requests per second. Traffic passes that, so they add a second server. Now, how do clients reach both?
The first attempt is DNS: publish two A records and let clients spread themselves. It half works. When a server dies, DNS keeps handing out its address until caches expire, so for minutes half the users get errors. DNS has no idea that one server is busy with slow requests while the other is idle. And every deploy means killing a server that clients are still talking to.
The second attempt is to give clients a list of servers and have them choose. That works for internal services you control, but not for browsers and mobile apps you cannot update every time a server changes.
What the team needs is a component with one stable address that knows, second by second, which servers are alive and how busy they are. That is a load balancer.
What a load balancer solves
- Scale out. Capacity becomes “add another server”, with no client aware of it.
- Failure. Dead servers are detected and skipped within seconds.
- Planned change. Servers can be drained and replaced without dropping requests.
- One front door. TLS termination, access logs and basic protection live in one place.
L4 vs L7
The names come from the layers of the network model: layer 4 is transport (TCP and UDP), layer 7 is the application protocol (HTTP).
| L4 | L7 | |
|---|---|---|
| Sees | IP addresses, ports, protocol | Method, path, headers, cookies, body |
| Balances | Connections | Individual requests |
| Good at | Any TCP or UDP protocol, very high throughput, TLS passthrough | Routing by path or host, retries, TLS termination, cookie stickiness |
| Examples | AWS NLB, Linux IPVS, HAProxy in TCP mode | NGINX, HAProxy, Envoy, AWS ALB |
An L4 balancer picks a backend when a connection opens, then forwards packets without reading them. It is cheap per packet and protocol-agnostic. Its blindness is the limit: it cannot route by URL, cannot retry a failed request, and cannot spread the requests inside one long-lived connection. That last point bites with HTTP/2 and gRPC, where one connection may carry thousands of requests, all to the same backend.
An L7 balancer terminates the client’s connection, parses each request, and sends it over a separate connection to a backend it chooses per request. That costs more CPU, and in exchange it can do everything in the table.
Choose L7 by default for HTTP services. Choose L4 for non-HTTP protocols (databases, MQTT, game traffic over UDP), when the backend must terminate TLS itself, or as a fast first tier in front of a fleet of L7 proxies.
Algorithms
| Algorithm | How it picks | Use when | Watch out for |
|---|---|---|---|
| Round robin | Next server in turn | Identical servers, similar requests | Ignores how busy each server is |
| Weighted round robin | In turn, in proportion to a weight | Mixed machine sizes, canary at 5% | Weights are static |
| Least connections | Fewest requests in flight | Uneven request cost, long-lived connections | A server that fails fast looks idle |
| Consistent hashing | Hash of client IP, user ID or URL | You want the same key on the same server | Hot keys overload one server |
| Power of two choices | Two at random, take the less loaded | Several balancers, imperfect load data | Slightly worse than a perfect global view |
Round robin’s weakness is that it counts requests handed out, not work in progress. If one request in ten takes five seconds, some servers will pile up slow requests by chance. Least connections corrects for that.
Try the simulator with uneven request sizes: run round robin and watch one server’s backlog grow, then switch to least connections and compare.
Consistent hashing is for affinity. It keeps a user on the server that holds their cache entries or their WebSocket, and moves only a small share of keys when a server joins or leaves.
Power of two choices exists because “send it to the least loaded server” goes wrong when many balancers act on slightly stale information. They all see the same idle server and all send to it. Picking two servers at random and using the less loaded one spreads the choices, and the analysis behind it shows that this one extra comparison removes most of the imbalance of purely random selection. NGINX and Envoy both offer it.
Health checks
Step 1 of 8
The load balancer spreads requests over three servers in turn. Clients see one address and never learn how many servers sit behind it.
Read the steps as text
- The load balancer spreads requests over three servers in turn. Clients see one address and never learn how many servers sit behind it.
- Every few seconds it also sends each server a small health probe, such as a GET to a health endpoint. A server that answers quickly with a 200 stays in rotation.
- Server B's process hangs. Its next probe times out, but one failure is not enough to act on. The balancer keeps sending B a third of the traffic, and those requests fail.
- After three failed probes in a row, B is marked unhealthy and removed from rotation. With a five second interval that took about fifteen seconds, which is the price of not reacting to a single blip.
- Passive checks close that gap. The balancer watches real responses, and a server that returns a run of errors or timeouts is ejected straight away, without waiting for the next probe.
- B is restarted and begins passing probes. After two successes it rejoins, ideally with a slow start that ramps up its share, so that a cold server is not handed a full load in its first second.
- Now a deploy needs to replace Server C. The balancer drains it. No new requests are sent to C, while requests already in flight are given time to finish.
- Once C is idle, or the drain timeout runs out, it is removed and no client saw an error. Health checks handle the failures you did not plan. Draining handles the ones you did.
Active checks probe each server on a timer, for example an HTTP GET every 5 seconds, marking it down after 3 failures and up after 2 successes. Passive checks watch real traffic and eject a server that returns a run of errors or timeouts. Use both: active checks find a dead server that is receiving no traffic, and passive checks react faster.
Keep the health endpoint shallow. It should say “this process can serve requests”, not “the database and every downstream service are fine”. If the check queries a shared database, one slow database marks every server unhealthy at the same moment, and the balancer has nowhere to send anything.
For the same reason, good balancers fail open. If all or most backends look unhealthy, they assume the check is wrong and send traffic anyway. Envoy calls this panic mode, and AWS load balancers route to all targets when none is healthy.
Connection draining
Removing a server abruptly cuts off its in-flight requests. With draining, the balancer stops sending new requests to the server and gives existing ones time to finish before it is removed. AWS calls this the deregistration delay and defaults it to 300 seconds. Set it a little above your longest normal request. Long-lived connections such as WebSockets will not finish by themselves, so the server should tell clients to reconnect elsewhere.
Sticky sessions
Stickiness sends a client to the same server each time, through a cookie at L7 or by hashing the source IP at L4. It is needed when the server holds something the client depends on: an in-memory session, or an open WebSocket.
It has costs. Load becomes uneven, because long-lived or heavy users stay put. When a server dies, its users lose their state. Scaling in and deploying get harder. If the only reason for stickiness is session data, move the session to a shared store and make the servers stateless. Keep stickiness for cases where it is inherent, such as long-lived connections, or where it is only an optimisation, such as warm local caches.
Making the load balancer highly available
A single load balancer is a single point of failure in front of everything.
- Active-passive pair. Two balancers share a virtual IP. The standby takes it over within a few seconds when heartbeats stop (VRRP, with keepalived on Linux). It is simple, but half the capacity sits idle.
- Active-active. Several balancers all serve. Routers spread flows across them with equal-cost multipath (ECMP) or anycast. The L4 tier uses consistent hashing so that whichever balancer receives a packet picks the same backend for that connection. Google’s Maglev is the well-known design.
- Managed. Cloud load balancers run several nodes across availability zones behind one name or address. That covers a zone failure. For region failure you still need DNS or anycast above them.
In the interview
Almost every design has a load balancer in it. Do not just draw the box. Say which kind and why: “an L7 balancer here, because I want path routing and per-request balancing”, or “L4, because this is raw TCP from devices”.
Then cover, in a sentence each, the points interviewers probe: the algorithm (least connections if request costs vary), health checks (shallow, active plus passive), draining on deploy, where session state lives so that stickiness is not required, and how the balancer itself is redundant. Say when you would not add one too: a single server needs none, and between internal services, client-side balancing may replace it.
Key takeaways
- A load balancer gives clients one stable address, spreads work over many servers, and hides server failures and deploys.
- An L4 balancer sees addresses and ports and balances connections. An L7 balancer reads HTTP and balances individual requests.
- Round robin suits identical servers and similar requests. Least connections suits uneven or long-lived work. Hashing gives affinity.
- Power of two choices gets most of the benefit of least-loaded selection without many balancers stampeding one server.
- Health checks should be shallow and should fail open. A check that depends on a shared database can mark every server dead at once.
- Drain servers before removing them, keep servers stateless so stickiness is optional, and never run a single load balancer.
Try it
Check yourself
0 of 5 answered
Flashcards
These 6 cards are in your review deck. Tap a card to see the answer.
What can an L4 load balancer see, and what can an L7 one see?
L4 sees IP addresses, ports and the transport protocol, and forwards connections. L7 parses the application protocol, so it sees HTTP method, path, headers and cookies for each request.
When is least connections better than round robin?
When requests differ a lot in cost or connections are long-lived, such as WebSockets. Round robin counts requests handed out, not work still in progress.
What is power of two choices?
Pick two backends at random and send the request to the less loaded of the two. It avoids the herd effect of everyone choosing the single least-loaded server on stale data.
Active versus passive health checks?
Active checks probe each server on a timer. Passive checks watch real traffic and eject a server after a run of errors or timeouts. Use both.
What is connection draining?
Before removing a server, the balancer stops sending it new requests and lets in-flight ones finish, up to a timeout. It is what makes deploys and scale-in invisible to users.
How do you stop the load balancer being a single point of failure?
Run at least two. Either an active-passive pair sharing a virtual IP, or several active instances behind ECMP or anycast routing. Managed cloud balancers do this across zones for you.
Interview questions on this
- When would you put an L4 load balancer in front of a service instead of an L7 one?
- Round robin gives every server the same number of requests, yet some servers are overloaded while others are idle. Why, and what would you change?
- The load balancer marked every backend unhealthy at once and the site went down, though the servers were running. Why, and how should health checks be designed?