Sub topic 6
Spreading requests with a load balancer
This chapter assumes you know how a client talks to a web server over HTTP, what a TCP connection is, and what a health check or timeout means at a basic level. It also assumes you have read the earlier chapters on horizontal scaling. Once you run several copies of an application server, something has to decide which copy handles each request. That component is the load balancer.
What a load balancer does
A load balancer is a component that accepts client traffic at one address and forwards each request or connection to one of several backend servers. Clients see a single endpoint. The set of backends behind it is called the pool.
A load balancer gives you four things:
- Distribution. Work spreads across the pool, so no single server saturates while others sit idle.
- Health checking. The balancer probes each backend and stops sending traffic to those that fail.
- A stable entry point. Servers can be added, removed, or replaced without clients changing the address they use.
- Optional extras. Many balancers also terminate TLS, compress responses, enforce rate limits, or route by URL path.
Layer 4 and layer 7 balancing
Balancers work at one of two levels of the network stack, and the choice affects what they can decide.
| Property | Layer 4 (transport) | Layer 7 (application) |
|---|---|---|
| Sees | IP addresses, ports, TCP/UDP | HTTP method, path, headers, cookies |
| Routing decisions | Per connection | Per request |
| Can route `/api` and `/images` differently | No | Yes |
| Can terminate TLS and inspect content | Usually passes it through | Yes |
| Overhead | Lower | Higher |
| Typical use | Databases, raw TCP services, very high throughput | Web applications, APIs, microservices |
A layer 4 balancer picks a backend when a connection opens and then shuttles bytes. A layer 7 balancer parses each HTTP request, so it can send one connection's requests to different backends. That per-request routing matters with HTTP keep-alive, where one client connection carries many requests.
Balancing algorithms
The algorithm decides which backend gets the next request. No algorithm is best for every workload.
Round robin
Round robin sends requests to servers in order and wraps around at the end of the list. It is simple and needs no knowledge of server load.
from itertools import cycle
servers = ["app-1", "app-2", "app-3"]
pool = cycle(servers)
for request_id in range(5):
print(request_id, "->", next(pool))The output assigns requests 0 to 4 to app-1, app-2, app-3, app-1, app-2. Round robin works well when requests cost about the same and servers have equal capacity. It works badly when a few requests are very expensive, because it still hands the next request to a server that is already busy with a heavy one.
Weighted round robin
Each server has a weight that sets its share of traffic. A server with weight 3 receives three requests for every one sent to a server with weight 1. Use it when the pool mixes machine sizes, for example during a migration from older to newer instance types.
Least connections
The balancer tracks how many active connections each backend holds and sends the next request to the one with the fewest. This adapts to uneven request cost. If one server is stuck on slow requests, its connection count stays high and it receives less new work. It is a good default for workloads where request duration varies widely, such as a mix of quick reads and long report generation.
Hash-based selection
The balancer computes a hash of some request property, such as the client IP address or a header, and maps the result to a backend. The same key always lands on the same server while the pool is unchanged. This gives affinity without cookies, and it is useful for caches, where sending the same key to the same server keeps its cache warm.
The weakness is pool changes. With simple modulo hashing (hash % number_of_servers), adding or removing one server remaps most keys. Consistent hashing reduces this: when the pool changes, only a small fraction of keys move. Many balancers offer it for cache-oriented routing.
Choosing among them
| Algorithm | Best when | Weak point |
|---|---|---|
| Round robin | Uniform requests, equal servers | Ignores current load |
| Weighted round robin | Servers differ in capacity | Weights are set by hand and can go stale |
| Least connections | Request cost varies | Connection count is only a proxy for load |
| Hash-based | You need key-to-server affinity or cache locality | Uneven spread if keys are skewed; remapping on pool changes |
Health checks
A balancer that keeps sending traffic to a dead server turns a partial failure into user-visible errors. Health checks prevent this.
There are two kinds:
- Active checks. The balancer periodically sends a probe, such as
GET /healthz, and expects a success response within a timeout. - Passive checks. The balancer watches real traffic. If a backend returns repeated errors or resets connections, it is marked unhealthy.
Most settings come down to three numbers: the probe interval, the timeout, and how many consecutive failures or successes change a server's state. A short interval and low failure threshold detect failures fast but can eject a healthy server that has one slow response. A long interval is stable but leaves a failed server in rotation for longer. Requiring several consecutive successes before a recovered server re-enters the pool avoids flapping, where a struggling server bounces in and out.
What a health endpoint should check
A shallow check returns success if the process is running. A deep check also tests dependencies, such as a database connection. Deep checks catch more failures but have a hazard: if the shared database goes down, every backend fails its check at once, and the balancer removes the whole pool. The result is a total outage instead of degraded service. A common compromise is a shallow check for the balancer's rotation decision and a separate deeper endpoint for monitoring and alerts.
Connection draining
When you remove a server for a deploy or a scale-in event, in-flight requests should finish first. Connection draining (also called deregistration delay) stops new requests from going to the server while letting existing ones complete, up to a time limit. Without it, users see dropped connections during every deployment.
Session affinity
Session affinity, or sticky sessions, sends all requests from one client to the same backend, usually through a cookie the balancer sets or a hash of the client IP. Applications that keep session data in server memory sometimes need it.
Affinity has costs:
- Load can become uneven, because a few heavy clients pin to one server.
- When that server fails or is removed, the sessions it held are lost.
- Clients behind a shared NAT address look like one client to an IP-hash scheme and all land on the same server.
The better fix is to remove the need for affinity by keeping servers stateless, which the next chapter covers. Treat sticky sessions as a stopgap for applications you cannot change yet.
The balancer as a single point of failure
Adding a load balancer moves the single point of failure instead of removing it. If one balancer fails, every backend becomes unreachable even though all of them are healthy.
Common mitigations:
- Redundant pairs. Run two balancers in active-passive or active-active mode. In active-passive, a standby takes over a shared virtual IP address when the primary fails.
- Managed balancers. Cloud providers run the balancer as a service spread across several availability zones, so you do not manage the failover yourself.
- DNS-level distribution. DNS returns several balancer addresses, and clients spread across them. DNS caching makes failover slow, so this is usually combined with other methods.
Capacity matters too. The balancer itself has limits on connections, bandwidth, and TLS handshakes per second. At very high traffic it can become the bottleneck, which is why large systems put a layer 4 tier in front of a layer 7 tier.
Common errors
- Treating all requests as equal. Round robin with highly variable request cost leaves some servers overloaded. Switch to least connections.
- Health checks that are too deep. A check that fails when a shared dependency fails can remove every backend at once.
- No draining. Deploys drop in-flight requests.
- Relying on sticky sessions. Failures and scale-in events destroy session data, and load skews.
- Backend timeouts longer than the balancer's. The balancer gives up and returns an error while the backend keeps working on a request nobody is waiting for. Align the timeouts, and keep the balancer's slightly longer than the backend's.
- Losing the client IP. Backends see the balancer's address. Read the original client address from a header such as
X-Forwarded-For, and trust it only when it was set by your own balancer. - Ignoring retries. If the balancer retries failed requests on another backend, non-idempotent operations such as payments can run twice. Limit retries to safe methods or use idempotency keys.
Load balancing and autoscaling
The balancer is the part that makes scaling out invisible to clients. When an autoscaler adds a server, it registers it with the balancer. The balancer starts health checking it and sends traffic once it passes. When the autoscaler removes one, draining lets its requests finish. The autoscaling chapter builds on this, so a newly started server should only report healthy when it is actually ready to serve.
Exercise
A pool of four identical servers uses round robin. Most requests take 20 ms, but about 2% trigger a report that takes 10 seconds. Users report that some servers are slow at times while others are nearly idle. What change would you try first, and why?
Show answer
Switch to least connections. Round robin ignores how busy each server is, so it keeps assigning new requests to a server that is tied up with 10-second reports. Least connections sees the high active-connection count on that server and routes new work to the others. A further option is to move report generation to a separate pool or background queue so slow requests do not share servers with fast ones.
Exercise
Your health check endpoint queries the primary database. During a database failover that lasts 30 seconds, users get errors from the whole site for longer than 30 seconds. Explain what likely happened and how to fix it.
Show answer
Every backend failed its deep health check at the same moment, so the balancer removed all of them from rotation. After the database returned, the backends had to pass several consecutive checks before re-entering the pool, which extended the outage beyond 30 seconds. Fix it by making the rotation check shallow (process is up and can accept requests) and moving the database check to a separate monitoring endpoint, or by configuring the balancer to keep serving from the pool when all backends are unhealthy.