Load Balancing: L4, L7, Algorithms and Health Checks
Overview
Once you have many servers, something must decide which one serves each request. That component is the load balancer. It spreads traffic, hides failed servers and gives the world a single address for your service. This lesson explains what a load balancer does, the difference between layer 4 and layer 7 balancing, the common algorithms, how health checks remove broken servers, and how to avoid making the load balancer itself a single point of failure.
Detailed Notes
What Is It?
A load balancer (LB) is a component that receives incoming requests and forwards each one to one of several backend servers. Clients talk to one address (the load balancer's); they never need to know how many servers exist.
A reverse proxy is a server that sits in front of other servers and forwards client requests to them. A load balancer is a reverse proxy whose main job is choosing among several backends.
Load balancers work at different levels of the network, called layers:
Layer 4 (L4) balancing works with TCP or UDP connections. It sees IP addresses and ports but not the content. It forwards the raw connection to a backend. Very fast and simple.
Layer 7 (L7) balancing works with the HTTP request itself. It can read the path, headers and cookies and make decisions from them, for example "send /images to the image servers" or "send logged-in users to pool B". It can also terminate TLS, compress responses and add headers. It is more capable but does more work per request.
Why Do We Need It?
Capacity: spreads load so that many servers act as one large one (horizontal scaling).
Availability: when a server fails, the LB stops sending it traffic, so users do not notice.
Safe deployments: take a server out of rotation, upgrade it, put it back; or send 5% of traffic to a new version first.
One front door: a single address, one place for TLS certificates, rate limits and logging.
Flexibility: servers can be added or removed without clients changing anything.
How Does It Work?
Load Balancer in Front of an App TierArchitecture
Key point. The load balancer gives capacity and failure tolerance, but it must itself be redundant.
Clients see one address. The balancer picks a healthy server and stops sending to failed ones.
The flow: the client resolves the service name via DNS to the load balancer's address; the LB picks a healthy backend using its algorithm; it forwards the request; the backend answers, and the LB returns the answer (or, in some L4 modes, the backend replies directly).
Balancing algorithms
Round robin: servers take turns: A, B, C, A, B, C. Simple and fair if requests cost about the same and servers are equal.
Weighted round robin: stronger servers get a larger share. Useful when machines differ in size or during a gradual rollout.
Least connections: send to the server with the fewest active connections. Better when request duration varies widely (some take 10 ms, some 10 seconds) because it adapts to real load.
Least response time: prefer the server answering fastest. Reacts to slow servers but can oscillate.
IP hash: hash the client's IP to choose a server, so the same client usually lands on the same one. A cheap form of stickiness.
Consistent hashing: pick the server from a hash of a key (for example a user id) arranged so that adding or removing a server moves only a small fraction of keys. It is essential for caches and partitioned data, covered in the partitioning lesson. An LB uses it when the same key should hit the same backend, for example to benefit from a per-server cache.
Random (with two choices): pick two servers at random and send to the less loaded. Surprisingly effective and cheap at scale.
Health checks
A health check is a periodic probe from the LB to each backend. Active checks send a request (for example GET /health every 5 seconds) and expect a 200. Passive checks watch real traffic and mark a server bad after several errors or timeouts. The rule: remove a server after N consecutive failures (say 3), and add it back after M consecutive successes. This avoids reacting to a single blip.
Design the health endpoint carefully. A shallow check ("the process is up") misses a server whose database connection is broken. A deep check that tests every dependency can take the whole fleet out if one shared dependency is slow, because every server then reports unhealthy at once. A balanced approach: check what the server needs to serve at all, and treat a shared dependency's outage separately.
Related ideas: connection draining lets in-flight requests finish before a server is removed, and slow start gradually ramps traffic to a new server so a cold cache does not get overwhelmed.
Stickiness
If you cannot make servers stateless, sticky sessions pin a user to one server using a cookie or IP hash. This was discussed in the scaling lesson; prefer a shared session store.
Avoiding a single point of failure
A single point of failure (SPOF) is one component whose failure takes the whole system down. A lone load balancer is exactly that. Solutions: run two or more LBs, either active-passive (a standby takes over, using a shared floating IP address) or active-active (all serve traffic, with DNS or an anycast network spreading clients across them). Managed cloud load balancers do this for you across multiple zones. Also use DNS-level balancing across regions when needed.
Where load balancers sit
Load balancers appear at several points: between users and web servers (public), between web servers and internal services, and in front of caches or databases. Large systems often have an L4 layer at the edge feeding a fleet of L7 balancers.
Layer 4 vs Layer 7 Load BalancingComparison
Layer 4
connections (TCP/UDP)
1
Accept TCP connection
2
Pick backend
from IP and port only
3
Forward bytes unchanged
Very fast and cheap
Any protocol, even WebSocket or database
No routing by path or header
No HTTP-level metrics
Edge entry point or non-HTTP traffic.
Layer 7
HTTP requests
1
Terminate TLS, read HTTP
2
Pick backend
by path, header, cookie
3
Forward, retry, add headers
Content-based routing
Retries, compression, auth hooks
More CPU and latency
Sees plaintext after termination
Default for web APIs and microservices.
Key point. Use L7 for HTTP APIs that need routing rules; use L4 for raw speed or non-HTTP protocols.
Both spread traffic; they differ in what they can see and decide on.
Interview tip. Common mistakes: drawing one LB box and forgetting it is a single point of failure, saying "round robin" without checking if request cost varies, and ignoring health checks. Also do not claim the LB fixes a slow database; it only spreads the app tier.
Interview discussion. "I'll put an L7 load balancer in front of the stateless API servers with least-connections balancing and health checks on /health. The LB runs in two zones so it is not a single point of failure. Static assets go through the CDN instead."
Real-World Example
A streaming service has an API with a mix of tiny requests (get profile, 5 ms) and heavy ones (build personalized home screen, 800 ms). With round robin, a server unlucky enough to receive several heavy requests queues up while others sit idle. Switching to least connections spreads real work much more evenly, and p99 latency drops. Health checks catch a server that is stuck on garbage collection and drain it until it recovers.
System Design Example
For a chat system, users hold long-lived WebSocket connections (a persistent two-way connection). An L4 balancer fits: it forwards TCP connections cheaply and holds millions of them. It uses least connections so new users go to the emptiest chat server. When a chat server dies, its clients reconnect, the LB sends them elsewhere, and the clients fetch missed messages. For the separate REST API (login, history) an L7 balancer routes by path: /auth to the auth service, /history to the history service.
Trade-off thinking. L7 is flexible (content-based routing, TLS termination, per-request metrics) but costs more CPU and latency and sees plaintext. L4 is faster and handles any protocol but cannot route by content. Hardware or managed balancers are easy but cost money; software ones (NGINX, HAProxy, Envoy) are flexible but you run them. Pick from the requirement.
Key Interview Takeaway
A load balancer spreads requests across healthy servers, hides failures and gives clients one address. Know L4 (fast, connection-level) versus L7 (content-aware), pick the algorithm from the workload (round robin for uniform requests, least connections for uneven ones), use health checks, and never leave the load balancer as a single point of failure.