Sub topic 7
Choosing a load-balancing method
This chapter covers how Nginx picks a backend from an upstream group, and how to choose among the available methods. It assumes you can already define an upstream block and point proxy_pass at it, as covered in the previous chapter. It also assumes you know what an HTTP session cookie is and what a TCP connection is.
What a balancing method decides
When a request arrives, Nginx must choose one server from the group. The balancing method is the rule for that choice. It runs once per request (or once per connection for non-HTTP uses). If the chosen server fails, Nginx can try another one, but that retry is a separate mechanism covered in the next chapter.
The methods are declared with a single directive inside the upstream block. If you declare none, Nginx uses weighted round robin.
| Method | Directive | Picks a server by | Typical use |
|---|---|---|---|
| Round robin | (default) | Taking servers in turn, respecting weights | Stateless apps with similar requests |
| Least connections | `least_conn;` | Fewest active connections, adjusted by weight | Requests with very uneven duration |
| IP hash | `ip_hash;` | Hash of the client IP address | Simple client-to-server stickiness |
| Generic hash | `hash key [consistent];` | Hash of a key you choose | Cache affinity, per-tenant routing |
| Random | `random [two [method]];` | Random choice, optionally best of two | Several balancers sharing one backend pool |
Round robin and weights
Round robin is the default. With no method directive, Nginx sends requests to each server in turn. With equal weights, three servers each receive one third of the requests.
The weight parameter changes the proportions. A server with weight=3 receives three requests for every one sent to a server with the default weight of 1. Use weights when backends have different capacity, for example a larger instance next to a smaller one.
upstream app_backend {
server 10.0.0.11:8080 weight=3;
server 10.0.0.12:8080;
server 10.0.0.13:8080;
}Here the first server receives 3 of every 5 requests. Nginx uses a smooth weighted algorithm, so the three requests to the heavy server are interleaved with the others instead of arriving in one burst.
Round robin counts requests, not work. If some requests take 50 ms and others take 30 seconds, a server can end up holding several slow requests while its neighbors sit idle. That is the case least connections addresses.
Least connections
least_conn sends each new request to the server with the fewest active connections. When weights are set, Nginx divides the connection count by the weight, so a server with weight=3 is allowed roughly three times as many open connections as a server with weight 1. If several servers tie, Nginx falls back to weighted round robin among them.
upstream app_backend {
least_conn;
server 10.0.0.11:8080 weight=3;
server 10.0.0.12:8080;
}Least connections is a good choice when request duration varies widely, such as an API where some endpoints generate reports. It also copes with a newly restarted server: that server starts with zero connections and receives traffic until it catches up.
Two limits apply. First, Nginx counts only connections it opened itself in this worker configuration, and it counts connections, not CPU or memory load. A server doing heavy work on few connections still looks idle. Second, without a shared memory zone, each Nginx worker process keeps its own counters. Adding a zone directive to the upstream block makes the counters and server state shared between workers, which gives more accurate balancing.
upstream app_backend {
zone app_backend 64k;
least_conn;
server 10.0.0.11:8080;
server 10.0.0.12:8080;
}Session affinity with ip_hash
Some applications keep session data in the memory of one server. If the next request lands on a different server, the user appears logged out. The cleanest fix is to move the session to a shared store such as Redis or a database. When that is not possible, you can make routing sticky.
ip_hash computes a hash from the client address and maps it to a server. For IPv4 it uses the first three octets, so clients in the same /24 network go to the same server. IPv6 uses the whole address. As long as the group does not change, a given client keeps reaching the same server.
upstream app_backend {
ip_hash;
server 10.0.0.11:8080;
server 10.0.0.12:8080;
server 10.0.0.13:8080 down;
}The down parameter marks a server as permanently unavailable while preserving the hash mapping for the others. Use it instead of deleting a line, otherwise the hash positions shift and many clients move to different servers.
ip_hash has failure modes you should know before you rely on it:
- Shared addresses. Many users behind one corporate NAT or mobile carrier gateway share an address, or at least a /24. They all hit one server, which produces uneven load.
- Proxy chains. If Nginx itself sits behind another proxy or CDN, the client address it sees is the proxy's address, and most traffic hashes to the same server. Nginx can take the real address from a header through the
realipmodule, but only configure that for sources you trust. - Weights do not apply the way you expect.
ip_hashcannot be combined withweightto get precise ratios, andbackupservers are not supported with it. - Resizing the group. Adding or removing a server remaps a large share of clients, and those users lose their sessions.
Generic hash and consistent hashing
The hash directive lets you choose the key. The key can be text, a variable, or a mix. This is useful when you want requests for the same resource to reach the same server, for example so each backend's local cache holds a distinct slice of the content.
upstream cache_backend {
hash $request_uri consistent;
server 10.0.0.21:8080;
server 10.0.0.22:8080;
server 10.0.0.23:8080;
}The consistent parameter selects ketama consistent hashing. With plain hash, adding or removing a server changes the modulo arithmetic and remaps most keys. With consistent, only the keys that belonged to the changed server move, roughly 1 divided by the number of servers. For cache affinity this difference decides whether a scale-up event empties every backend cache or only a fraction of it.
You can also hash on a cookie or header, such as hash $cookie_sessionid consistent;. This gives true per-session stickiness without the NAT problem of ip_hash. If the key is empty (the cookie is not set yet), all such requests hash to the same value, so the first request of every new visitor goes to one server. Choose a key that is always present, or accept that skew.
Random
random picks a server at random, taking weights into account. The useful form is random two least_conn;. Nginx picks two servers at random and then chooses the one with fewer active connections. This approach, often called "power of two choices", works well when several Nginx instances balance across the same pool. Each instance has only its own connection counts, and pure least connections can make all of them rush toward the same idle server. Random choice spreads those decisions.
upstream app_backend {
zone app_backend 64k;
random two least_conn;
server 10.0.0.11:8080;
server 10.0.0.12:8080;
server 10.0.0.13:8080;
}Server parameters that affect selection
These parameters can be set on any server line, and they combine with the methods above.
| Parameter | Effect |
|---|---|
| `weight=N` | Relative share of traffic. Default is 1. |
| `max_conns=N` | Maximum simultaneous connections to this server. Default 0 means no limit. Requests beyond the limit go to other servers, or fail if none are free. |
| `backup` | Receives traffic only when all non-backup servers are unavailable. |
| `down` | Excludes the server, keeping hash positions stable. |
| `max_fails`, `fail_timeout` | Passive failure detection, covered in the next chapter. |
Use max_conns to protect a backend that has a hard concurrency limit, such as a single-threaded process. Set it together with a zone so the limit is enforced across all workers.
A decision guide
Work through the questions in order:
- Does the application need the same client on the same server? If you can, remove that requirement with a shared session store. If not, use
hashon a cookie withconsistent, orip_hashfor simple cases. - Do you want each backend to cache a distinct slice of content? Use
hash $request_uri consistent. - Do request durations vary a lot? Use
least_conn, orrandom two least_connwhen multiple balancers share a pool. - Otherwise, use round robin, and add weights if the servers differ in capacity.
Verifying the distribution
Do not assume a method works as intended. The upstream_log format from the logging chapter records $upstream_addr. Even without it, you can add a quick format and count requests per backend.
sudo nginx -t && sudo systemctl reload nginx
awk '{for(i=1;i<=NF;i++) if($i ~ /^upstream=/) c[$i]++} END{for(k in c) print c[k], k}' /var/log/nginx/proxy_access.log | sort -rnIf you use ip_hash or hash and the counts are heavily skewed, test with traffic from varied addresses or keys before drawing conclusions. A load test run from a single machine always hashes to the same server under ip_hash.
Exercise
Your backends are three identical servers. Most requests finish in 20 ms, but a few report endpoints run for 20 seconds. Users complain that some pages are slow while one server seems idle. Which method fits, and why would round robin fall short?
Show answer
Use least_conn (optionally with a zone so all workers share counters). Round robin counts requests, so it can keep sending new requests to a server already tied up with several 20-second reports while another server is idle. Least connections sends new requests to the server with the fewest active connections, which avoids the loaded one.
Exercise
You use hash $request_uri; without consistent across four cache servers, then add a fifth. Roughly what happens to cache hit rates, and what change reduces the damage?
Show answer
Most keys are remapped to different servers, so many requests miss the caches and hit the origin until the caches warm up. Adding consistent (ketama hashing) means only about one fifth of the keys move to the new server, so the other four caches stay mostly valid.