Load Balancers and How They Share Traffic
Understand layer 4 and layer 7 balancing, common algorithms, health checks and sessions, so a failed server doesn't take your site down.
Key takeaways
- Layer 4 balancers route connections by address and port, while layer 7 balancers read requests and can route by hostname, path or header.
- Round robin suits similar requests on similar servers, and least connections copes better when request times vary widely.
- Health checks remove failing servers from rotation, so what they test matters a great deal.
- Keeping session data outside individual servers is sturdier than pinning each user to one machine.
- The balancer itself needs redundancy, or it becomes the single point of failure.
A load balancer accepts incoming connections or requests and hands each one to one of several servers that can do the job. It lets you add capacity by adding machines, and it keeps a service running when one of them fails or is taken down for maintenance.
The two decisions that shape its behavior are what it can see, just connections or full requests, and how it picks a server. Health checks then decide which servers are even in the running.
Why spread the load
One server has a ceiling on processing, memory and connections. You can buy a bigger one, called scaling up, or add more of them, called scaling out. Scaling out needs something in front to divide the work.
The other benefit is availability. With three servers behind a balancer, one can crash, be patched or receive a new release while the other two carry on. For that to work, the remaining servers need enough spare capacity to absorb its share.
Layer 4 and layer 7
The names refer to the transport and application layers of the network model.
A layer 4 balancer works with TCP or UDP. It sees source and destination addresses and ports, picks a backend for each connection or flow, and moves bytes without interpreting them. It's fast, protocol-agnostic and can pass encrypted traffic through untouched.
A layer 7 balancer understands HTTP. It terminates the client's connection, reads each request and can send /images/ to one group and /checkout/ to another. It can add headers, retry failed requests, compress and cache. In effect it's a reverse proxy with balancing features.
One consequence matters with long-lived connections. HTTP/2 can carry many requests over one connection. A layer 4 balancer assigns the whole connection to one server, so a single busy client can leave the others idle. A layer 7 balancer can spread the requests individually.
TLS and where encryption ends
A layer 7 balancer needs to read requests, so it usually terminates TLS and holds the certificate. That centralizes renewal and spares the backends the handshake work. Traffic onward to the servers can be re-encrypted, which is the safer default on any network you share with others.
Passthrough is the alternative. A layer 4 balancer forwards the encrypted bytes, and each backend holds the certificate and performs the handshake. The balancer can still choose a backend by the server name sent at the start of the handshake in some products, but it can't see paths or cookies. Passthrough suits cases where only the application may see the plain content, or where the protocol isn't HTTP. For what happens during that setup, see the TLS handshake.
Newer transports add a wrinkle. HTTP/3 runs over QUIC, which uses UDP, and its connections can survive a change of client address. A balancer that routes purely by source address and port may send the later packets to the wrong server, so confirm that your balancer supports QUIC properly before enabling it.
Algorithms for choosing a server
| Method | How it chooses | Good when |
|---|---|---|
| Round robin | Each server in turn | Servers and requests are alike |
| Weighted round robin | In turn, in proportion to weights | Servers differ in size |
| Least connections | The one with the fewest active | Request durations vary |
| Least response time | Favors quicker servers | Latency differs and is measured well |
| Hash of a key | Same key goes to the same server | Caches or affinity matter |
| Random two choices | Picks two at random, takes the less busy | Many balancers act independently |
Plain hashing, such as a key's hash divided by the number of servers, reshuffles most keys whenever the server count changes. Consistent hashing is designed so that adding or removing a server moves only a portion of them, which keeps caches warm.
Hashing by client IP address has a weakness. Many users can share one address behind carrier-grade NAT or an office gateway, and mobile users change addresses.
Start with round robin or least connections. Change only when measurements show an uneven load that matters.
Health checks
A balancer needs to know which backends work. Active checks send a probe at intervals, such as a TCP connection or an HTTP request to a health path. Passive checks watch real traffic and set aside a server that keeps failing.
Designing the health endpoint takes thought. One that returns success whenever the process is alive will miss a server that can't reach its database. One that tests every dependency can mark all servers unhealthy at once when a shared service hiccups, turning a partial problem into a total outage.
A practical rule: check the things whose failure is specific to that server and that another server could cover. Require several failures before removal and several successes before return, so a server doesn't flap in and out.
What to do when everything is unhealthy
Decide in advance how the balancer behaves if every backend fails its check. Some products then send traffic to all of them anyway, on the theory that the check itself may be wrong. Others return 503 Service Unavailable. Know which yours does, and provide a clear maintenance or error page for the second case, as described in 503 and maintenance done right.
Test health checks deliberately. Stop the application on one server during a quiet period and watch how long the balancer takes to notice, whether any requests fail meanwhile, and how it behaves when the server returns. A check interval of many seconds with several required failures means a window in which visitors are still being sent to a dead machine. Shortening it detects trouble sooner but increases probe traffic and the chance of reacting to a brief blip.
Sessions and stickiness
If a server keeps a user's shopping basket in its own memory, the next request has to return to it. Sticky sessions arrange this, usually with a cookie set by the balancer.
Stickiness is easy but has costs. Load becomes uneven, and when that server dies the sessions die with it. The sturdier design keeps session data in a shared database or in-memory store, or in a signed cookie, so any server can handle any request. Uploaded files need the same treatment: store them somewhere all servers can reach.
Caches should agree too. If each server generates its own entity tags or has slightly different builds, clients see inconsistencies, as noted in ETags and conditional requests.
Draining and deploying
To update a server, mark it as draining: it gets no new work but finishes what it has. After a time limit, it can be stopped, updated, health-checked and returned.
That enables several release styles:
- Rolling. Update a few servers at a time.
- Blue-green. Run a second full set with the new version and switch traffic over.
- Canary. Send a small share of requests to the new version and watch errors before continuing.
During any of these, two versions run side by side, so database changes and APIs need to tolerate both.
Beyond one location
DNS-based balancing returns different addresses to different queries. It can steer users between regions, but resolvers and devices cache answers, so changes take effect gradually. See DNS caching and TTL.
Anycast announces one address from many places and lets internet routing deliver users to a nearby one. Large networks combine it with local balancers at each site.
Cloud providers offer managed balancers that handle their own redundancy within the limits they document. If you run your own, use at least two, commonly with a shared virtual address that moves to the standby when the active one fails, for example using VRRP.
A worked sizing example
Say your busiest hour needs the equivalent of two fully loaded servers. Running exactly two leaves no room for growth, failure or maintenance. Three servers each run at about two thirds of capacity, and losing one puts the other two at their limit. Four run at half, and a failure leaves three at about two thirds, which is comfortable.
Capacity also depends on shared parts. Adding web servers doesn't help if they all wait on one database, and each new server opens more database connections. Watch the shared components as you scale out, and load test the whole system on infrastructure you control, not just one machine in isolation.
Autoscaling adds and removes servers according to load. It helps with predictable daily patterns and gradual surges. A sudden spike can arrive faster than new machines boot, so keep a baseline that survives the first few minutes.
What to watch
Monitor request rate, error rate and response time, both at the balancer and per backend. One server that's slower than its peers often reveals a failing disk, a bad deployment or a noisy neighbor. Also track how many backends are healthy and raise an alert when that number drops, even though visitors may notice nothing yet. Lost redundancy that goes unreported turns the next small fault into an outage.
What can go wrong
- Retry storms. Retrying failed requests multiplies load on a struggling system. Limit retries, add backoff, and retry only operations that are safe to repeat, as discussed in retries and idempotency.
- Lost client addresses. Backends see the balancer. Use forwarded headers at layer 7, or the PROXY protocol or address-preserving modes at layer 4.
- Mismatched timeouts. If a backend closes idle connections sooner than the balancer expects, occasional gateway errors appear. Make the backend's idle timeout the longer one.
- Cold servers. A newly added machine with empty caches can be overwhelmed. A slow-start setting ramps traffic up.
- No spare capacity. Two servers at 70 percent each can't survive the loss of one.
Common questions
Does a small site need a load balancer?
Often not. One well-monitored server with good backups and caching serves many sites comfortably. Add balancing when downtime during maintenance or failure costs more than running a second server and the added complexity.
How is it different from a CDN?
A CDN places content near users and balances traffic across its own network. A load balancer typically divides requests among your servers in one location or region. Larger sites use both.