Load balancing
How traffic is spread across servers, the difference between layer 4 and layer 7, the main algorithms, and why the balancer itself must not become the single point of failure.
ConceptFoundation11 min readUpdated
- 1 architecture diagram
- 1 sequence flow
- 2 code samples
- 5 interviewer follow-ups
- 3 self-checks
On this page11 sectionsLLDSenior depth
Read first: A framework for system design interviews
- Explain what a load balancer does and why stateless services make it easy.
- Choose between layer 4 and layer 7 balancing, and between common algorithms.
- Describe health checks and what happens when a server dies.
- Explain why sticky routing is a trade-off and how to avoid needing it.
Race four load balancers on the same traffic
Compare round robin, random, least connections and two random choices, then kill a server and see what health checks buy you.
Open the interactive2 code samples (50 lines), collapsed so the explanation stays in focus.
One server has a ceiling: CPU, memory, network, connections. When traffic exceeds it you can buy a bigger machine (vertical scaling) or run several (horizontal scaling). Horizontal scaling is cheaper at scale and survives a machine failing, but it creates a new question: which server should handle each request? A load balancer answers it.
A load balancer sits in front of a pool of servers and presents a single address to clients. For each connection or request it picks a server, forwards the traffic, and returns the response. It also removes servers that stop responding.
The design only works smoothly when the servers are stateless: any server can handle any request because nothing important lives in its memory. Session data, uploads and counters go in shared stores such as a database or a cache. The moment a server holds state that others do not, the balancer cannot treat servers as interchangeable.
| Layer 4 (transport) | Layer 7 (application) | |
|---|---|---|
| Sees | IP addresses, ports, TCP/UDP | HTTP method, path, headers, cookies |
| Decides by | Connection | Request content |
| Cost | Very fast, little processing | More work per request |
| Can do | Spread connections (some can also terminate TLS) | Route /api and /images differently, rewrite requests, authenticate, split traffic for canary releases |
Layer 4 is the simple, fast choice when you only need to distribute connections. Because it never reads the request, the server loses the client's address unless the balancer passes it on, for example with the PROXY protocol. A layer 7 balancer typically adds an X-Forwarded-For header instead. Layer 7 is what you want when different paths go to different services, or when you need smarter behaviour such as canary releases. Many real systems use both: a layer 4 balancer at the edge in front of a fleet of layer 7 proxies.
- Round robin. Servers take turns. Simple and fair when requests cost about the same and servers are identical.
- Weighted round robin. Bigger servers take proportionally more turns.
- Least connections. Send to the server with the fewest open connections. Better when request durations vary widely, because slow requests pile up on one server under plain round robin.
- Hashing (by client IP, user ID or URL). The same key always goes to the same server. Useful for cache locality and sticky behaviour, but it does not adapt to load, and adding or removing a server reshuffles keys unless you use consistent hashing (see the replication and sharding lesson).
- Random with two choices. Pick two servers at random and send to the less loaded one. Surprisingly effective, and it needs only the load of the two sampled servers, not a view of the whole pool.
Here is one server failing, from the balancer's point of view:
A balancer is only useful if it stops sending traffic to servers that cannot serve it.
- Active checks: the balancer probes each server on an interval, for example an HTTP request to a health endpoint, and removes it after a few consecutive failures.
- Passive checks: the balancer watches real traffic and ejects a server that returns errors or times out.
Keep the health endpoint honest. A check that only returns "the process is up" will keep sending traffic to a server whose database connection is broken. Equally, a check that depends on a shared dependency can mark every server unhealthy at once and take the whole service down. Check what that server needs to serve its own requests, and think about what happens if the check fails everywhere.
When a server is removed or deployed, connection draining lets in-flight requests finish before it stops, so users do not see errors during routine changes.
Sticky routing sends a user to the same server every time, typically by cookie or IP hash. It is tempting when a server keeps session state in memory. The costs are real:
- Load becomes uneven if some users are much heavier than others.
- If that server dies, those users lose their session.
- It undermines autoscaling because new servers receive little traffic.
The usual fix is to move session state out of the server into a shared store, so any server can answer. Sticky routing also has a distributed rate limiting angle: if requests from one client always hit the same instance, a per-instance counter happens to be accurate, and the problem is hidden until routing changes. The rate limiting lesson, and its interactive 3D companion, show this directly.
If everything goes through one load balancer, that balancer is a single point of failure and a possible bottleneck. Standard answers:
- Run a pair (active-passive or active-active) sharing a virtual IP, so one takes over if the other fails.
- Use DNS to return several balancer addresses, or anycast, where the same IP is announced from multiple locations and internet routing (BGP) sends each client to a topologically close one. "Close" in routing terms is not always lowest latency.
- Use a managed balancer from a cloud provider, which handles redundancy for you. Say you would, but be ready to explain what it does.
For users spread across the world, global load balancing directs them to the nearest healthy region, using geographic DNS or anycast, with failover to another region when one is down. How fast that failover really is, and what a region failover needs besides routing, are in DNS, CDNs and the edge and multi-region design.
Terminating TLS at the balancer means certificates live in one place and backend servers skip the cryptographic work. The trade-off is that traffic between the balancer and the servers is unencrypted unless you re-encrypt it, which many security-conscious systems do.
Two algorithms from the list above, written out. Least connections needs a counter per backend. Power of two choices needs only a random number generator and the load of two backends.
C# · Backend, Pickers
using System;
using System.Collections.Generic;
using System.Linq;
public sealed class Backend
{
public Backend(string name) { Name = name; }
public string Name { get; }
public int Active { get; set; } // requests in flight right now
public bool Healthy { get; set; } = true; // set by health checks, never by the picker
}
public static class Pickers
{
/// <summary>The healthy backend with the fewest requests in flight, or null if none is healthy.</summary>
public static Backend LeastConnections(IReadOnlyList<Backend> pool)
{
Backend best = null;
foreach (var b in pool)
if (b.Healthy && (best == null || b.Active < best.Active)) best = b;
return best;
}
/// <summary>Sample two healthy backends at random and take the less loaded one.</summary>
public static Backend PowerOfTwo(IReadOnlyList<Backend> pool, Random random)
{
var healthy = pool.Where(b => b.Healthy).ToList();
if (healthy.Count == 0) return null;
var first = healthy[random.Next(healthy.Count)];
var second = healthy[random.Next(healthy.Count)];
return first.Active <= second.Active ? first : second;
}
}A test shows the claim rather than asserting it. Place 5,000 long-lived requests over 50 backends (an average of 100 each), once blindly and once with two choices:
C#
using System.Diagnostics;
var three = new List<Backend> { new Backend("a") { Active = 5 }, new Backend("b") { Active = 2 }, new Backend("c") { Active = 9 } };
Debug.Assert(Pickers.LeastConnections(three).Name == "b");
three[1].Healthy = false; // b fails its health check
Debug.Assert(Pickers.LeastConnections(three).Name == "a");
foreach (var b in three) b.Healthy = false;
Debug.Assert(Pickers.LeastConnections(three) == null); // the caller must decide: shed load, or return an error
var pool = Enumerable.Range(0, 50).Select(i => new Backend($"s{i}")).ToList();
var rng = new Random(7);
for (int i = 0; i < 5000; i++) pool[rng.Next(pool.Count)].Active++;
int blindMax = pool.Max(b => b.Active);
foreach (var b in pool) b.Active = 0;
for (int i = 0; i < 5000; i++) Pickers.PowerOfTwo(pool, rng).Active++;
int twoMax = pool.Max(b => b.Active);
Debug.Assert(blindMax >= 110 && twoMax <= 105); // with this seed: 121 against 101Blind placement leaves the busiest server about a fifth above the average. Two choices keeps it within a percent or two. The extra sample costs one comparison, and no balancer needs a global view or a lock, because each instance decides from two numbers. (The classic "balls into bins" analysis explains it: the surplus on the busiest server grows with traffic for random placement but stays tiny for two choices.) In production the healthy list is an array refreshed by the health checker, not filtered on every request.
Interviewer follow-upL6The load balancer is itself a single point of failure. How do you remove it?How to answer
Run more than one. For layer 4, share a virtual IP between an active and a standby balancer so the standby takes over on failure, or have several balancers advertise the same address (anycast) and let the network spread flows across them. Managed cloud balancers do this for you. At the DNS level, return several balancer addresses and health-check them. Mention connection state: if the set of balancers changes, consistent hashing of connections minimises the flows that get re-routed.
Interviewer follow-upL6Round robin sends every server the same number of requests, yet one server is overloaded. Why, and what do you change?How to answer
Requests are not equal: some are expensive, and long-lived connections such as WebSockets pile up on whichever server got them. Switch to least connections or least outstanding requests. Power of two choices (pick two servers at random, send to the less loaded) gets close to the best balance without any global state. Use weights for unequal hardware, and consider latency-aware selection.
Interviewer follow-upL7A server gets slow but still passes its health check. What happens, and how do you defend against it?How to answer
This is a gray failure. The balancer keeps sending traffic, tail latency climbs, and clients retry, which adds load to the already struggling server (a retry storm). Defend in layers: outlier detection that ejects a server on error rate or latency, health checks that exercise real work without cascading into dependencies, per-request timeouts, bounded retries with jitter and a retry budget, circuit breakers, and load shedding so overload turns into fast, cheap errors instead of slow ones.
Interviewer follow-upL5Why not just use DNS round robin instead of a load balancer?How to answer
DNS hands out several addresses, but it knows nothing about health or load. Resolvers and clients cache the answer, so a dead server keeps receiving traffic until the TTL expires, and a client often sticks to one address for a long time, so the spread is uneven. DNS works well as the first hop that points at a few load balancers, which then decide per request.
Interviewer follow-upL6How do you deploy a new version with no dropped requests?How to answer
Drain, do not kill. Fail the server's readiness check so the balancer stops sending it new connections, let in-flight requests finish (up to a timeout), then stop the process and start the new version. Send it traffic only once its readiness check passes, and roll out one slice at a time while watching error rate and latency. Liveness (is the process alive) and readiness (should it receive traffic) are different checks, and mixing them up causes restart loops during slow starts.
Load balancers make horizontal scaling transparent. Keep servers stateless, choose an algorithm that matches how request cost varies, check health honestly, avoid sticky sessions unless you must, and remember the balancer needs redundancy of its own.
Try answering out loud before you reveal each answer.
QuestionWhat is the difference between a layer 4 and a layer 7 load balancer?Reveal answer
Layer 4 spreads connections using IP addresses and ports without reading the content. Layer 7 reads the HTTP request (path, headers, cookies), so it can route by content, rewrite requests and split traffic for canary releases.
QuestionWhy do health checks need care?Reveal answer
A shallow check keeps sending traffic to a server whose dependencies are broken, while a check on a shared dependency can mark every server unhealthy at once. Check what each server needs to serve its own requests, and think about what happens if the check fails everywhere.
QuestionWhy is sticky routing usually avoided, and what replaces it?Reveal answer
It makes load uneven, loses sessions when a server dies, and weakens autoscaling. Moving session state into a shared store lets any server answer.