Sub topic 8
Load balancing behind a reverse proxy
This chapter assumes you know how a reverse proxy relays HTTP requests, how upstream (backend) servers are addressed, and what the Host and X-Forwarded-* headers do. It uses nginx for examples. The ideas apply equally to HAProxy, Envoy and cloud load balancers.
What the proxy does as a balancer
A reverse proxy already sits in front of your servers, so it is a natural place to spread traffic. For each incoming request, the proxy picks one backend from a pool, forwards the request, and returns the response. Clients see one address. You can add or remove backends without changing anything on the client side.
Load balancing gives you three things:
- Capacity. Several modest servers can handle more traffic than one.
- Availability. If one backend fails, the others keep serving.
- Operational freedom. You can deploy to one backend at a time, drain it first, and put it back.
The proxy makes two separate decisions for every request. The first is which backend to try. The second is what to do if that backend fails. The sections below follow that order.
Choosing a balancing algorithm
An algorithm is the rule for picking a backend. Pick one based on how your requests differ in cost and whether the same client or key should reach the same backend.
| Algorithm | How it picks | Good fit | Weakness |
|---|---|---|---|
| Round robin | Next backend in order | Similar requests, similar servers | Ignores current load |
| Weighted round robin | Round robin, with more turns for higher weights | Mixed server sizes | Weights are static and set by hand |
| Least connections | Backend with fewest active connections | Requests of varying duration | Counts connections, not CPU or memory cost |
| IP hash | Hash of the client address | Simple stickiness | Uneven when many clients share one address |
| Key hash (consistent) | Hash of a chosen key such as the URI | Cache pools, sharded data | Load follows key popularity |
| Random, two choices | Pick two at random, take the one with fewer connections | Many proxies without shared state | Less intuitive to reason about |
Round robin is nginx's default. It works well when requests cost about the same. It works badly when some requests take 20 ms and others take 20 seconds, because a backend can pile up slow requests while it still gets its turn. Least connections handles that case better, since a backend busy with long requests is skipped.
A weighted, least-connections pool
upstream app_servers {
least_conn;
server 10.0.0.11:8080 weight=3 max_fails=3 fail_timeout=30s;
server 10.0.0.12:8080 weight=1 max_fails=3 fail_timeout=30s;
server 10.0.0.13:8080 backup;
keepalive 32;
}
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://app_servers;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_connect_timeout 2s;
proxy_next_upstream error timeout http_502 http_503;
proxy_next_upstream_tries 2;
proxy_next_upstream_timeout 5s;
}
}Each part does one job:
weight=3sends the first server three times its share relative to the second. Use it when one machine is larger.backupmarks a server that receives traffic only when all the others are unavailable.keepalive 32keeps up to 32 idle connections to backends open per worker process, so the proxy skips a new TCP handshake for most requests. It only works withproxy_http_version 1.1and an emptyConnectionheader, which the config sets.proxy_connect_timeout 2smakes a dead host fail fast instead of holding the client for the default 60 seconds.
You can use the down parameter to take a server out of rotation by hand, for example before maintenance. Existing connections are not the concern of this directive. Remove the server from the pool and reload nginx for a graceful drain, because reload lets old worker processes finish their in-flight requests.
Failure handling and retries
Open-source nginx detects failures passively. It watches real traffic. When a request to a backend fails, that counts as a failed attempt. After max_fails failures within fail_timeout, the proxy stops sending traffic to that backend for fail_timeout, then tries it again. This is the behavior in the example above. Active probes that check a backend without user traffic are covered in the next chapter.
proxy_next_upstream decides which failures cause a retry on another backend. By default it retries on connection errors and timeouts. The example adds 502 and 503 responses. Two limits matter:
proxy_next_upstream_triesandproxy_next_upstream_timeoutcap the retry effort. Without them a bad request can visit every backend.- nginx does not retry non-idempotent requests such as
POSTonce they have been sent to a backend, unless you addnon_idempotent. This is deliberate. If the backend processed the request but crashed before replying, a retry would run the action twice.
Stickiness and session state
Many applications keep session data in the memory of one backend. If the next request lands on a different backend, the user appears logged out. There are three ways to handle this:
- Make backends stateless. Store sessions in a shared store such as Redis or in a signed cookie. This is the best option because every backend can serve every request, and failover is trivial.
- Hash the client address.
ip_hash;sends a client to the same backend while the pool is unchanged. For IPv4 it uses the first three octets, so a whole /24 network maps to one backend. Clients behind a corporate NAT or another proxy all look like one client, which skews load. - Hash a key you control. For example, a session cookie or a request header.
The third option is also the basis for cache pools, where the same URL should always reach the same cache:
upstream cache_pool {
hash $request_uri consistent;
server 10.0.1.21:8080;
server 10.0.1.22:8080;
server 10.0.1.23:8080;
}The consistent parameter uses consistent hashing. When you add or remove a server, only a fraction of keys move to a different server. Without it, a plain modulo hash remaps almost every key, and every cache starts cold at once.
Gotchas and failure modes
The proxy sees the wrong client. If another proxy or a cloud load balancer sits in front of nginx, $remote_addr is that device, not the user. ip_hash then sends everyone to one backend. Configure the realip module to take the client address from a trusted X-Forwarded-For header, and trust only known source addresses.
Retries amplify overload. When backends are slow because they are overloaded, timeouts trigger retries, and retries add more load. Keep the number of tries small, and set an overall retry timeout.
A recovered backend gets a burst. Least connections sees a fresh server with zero connections and sends it everything. A cold server with empty caches can fall over again. NGINX Plus has a slow_start parameter for this. In open-source setups, use weights and gradual rollout instead.
Weights go stale. A static weight reflects the server size on the day you set it. If instances change type, update the weights too.
The proxy is now the bottleneck. All traffic passes through one process. Watch its CPU, connection count and file descriptor limit, and plan for more than one proxy. That design question comes later in this tutorial.
Uneven hashing. With a key hash, one very popular key sends all its traffic to a single backend. Balancing by key distributes keys, not requests.
Choosing in practice
Start with round robin or least connections and stateless backends. Add weights only when servers differ. Use key hashing for caches and sharded data, not as a default. Set connect timeouts, retry limits and keepalive before you tune anything else, because those settings decide how the pool behaves when something goes wrong.
Exercise
A pool of three backends serves a report endpoint. Most requests finish in 30 ms, but some take 15 seconds. Under round robin, one backend often has a long queue while another is idle. Which algorithm would you try first, and why? Also, what should you check before you add ip_hash to fix a separate session problem when nginx sits behind a cloud load balancer?
Show answer
Try least_conn. It routes new requests to the backend with the fewest active connections, so a backend busy with 15-second requests is skipped, while round robin keeps giving it a turn. Before using ip_hash, check what $remote_addr contains. Behind a cloud load balancer, it is the balancer's address, so every request would hash to the same backend. Configure the realip module to read the real client address from X-Forwarded-For (trusting only the balancer's addresses), or move sessions into a shared store so stickiness is not needed.
Exercise
Why does nginx not retry a failed POST on another backend by default, and what does proxy_next_upstream_tries 2 limit?
Show answer
A POST usually changes state. If the first backend processed it and then failed before responding, a retry would repeat the action, for example charging a card twice. So nginx does not retry non-idempotent requests that have already been sent, unless you add non_idempotent. proxy_next_upstream_tries 2 caps the total number of backends tried per request, counting the first attempt, so a failing request cannot cycle through the whole pool.