Sub topic 13
Load balancing with upstream groups
This chapter assumes you can already write a server block, use proxy_pass to forward requests to an application, and test and reload configuration with nginx -t. Here you will spread traffic across several backend servers with an upstream group, choose a balancing method, and handle backends that fail.
What an upstream group does
An upstream group is a named list of backend servers. You define it in the http context and then use its name in proxy_pass. Nginx picks one member of the group for each request.
Load balancing gives you two things:
- Capacity. Several application processes share the work.
- Availability. If one backend stops answering, Nginx sends traffic to the others.
A basic upstream group
The upstream block sits in the http context, next to your server blocks. On Debian and Ubuntu, a file in /etc/nginx/conf.d/ or /etc/nginx/sites-available/ is already included inside http, so you can place it there.
upstream app_backend {
server 10.0.0.11:3000;
server 10.0.0.12:3000;
}
server {
listen 80;
server_name app.example.com;
location / {
proxy_pass http://app_backend;
}
}Three details matter:
- The name in
proxy_pass http://app_backend;must match theupstreamname. There is no port, because eachserverline in the group carries its own. - The
upstreamblock cannot go inside aserverblock. Putting it there makesnginx -tfail. - Without a method directive, Nginx uses round robin. It sends the first request to the first server, the second to the next, and so on, then starts over.
If you keep the headers from the reverse proxy chapter, add them to the location so each backend still sees the original host and client address.
Balancing methods
Round robin treats every request the same. That is a poor fit when requests vary in cost or when clients need to reach the same backend. Nginx offers other methods, and you choose one by adding a directive at the top of the upstream block.
| Method | Directive | Picks the backend by | Typical use |
|---|---|---|---|
| Round robin | none (default) | Rotating through the list | Similar backends and short, similar requests |
| Least connections | `least_conn;` | Fewest active connections | Requests with very different durations |
| IP hash | `ip_hash;` | Hash of the client IP address | Keeping a client on one backend without cookies |
| Generic hash | `hash $key consistent;` | Hash of a value you choose | Cache-friendly routing, for example by URI |
Least connections
upstream app_backend {
least_conn;
server 10.0.0.11:3000;
server 10.0.0.12:3000;
}Nginx sends each new request to the server with the fewest active connections. This helps when some requests take seconds, such as report generation, and others take milliseconds.
IP hash
upstream app_backend {
ip_hash;
server 10.0.0.11:3000;
server 10.0.0.12:3000;
}The same client address usually reaches the same backend. This is called session persistence, or sticky sessions. It has limits:
- Clients behind one NAT or corporate proxy share an address, so one backend can receive a disproportionate share of traffic.
- If Nginx itself sits behind another proxy or load balancer,
ip_hashsees that proxy's address unless you restore the real client address first (therealipmodule does this). - When you add or remove a server, some clients move to a different backend.
Storing sessions in a shared place, such as a database or Redis, is usually more reliable than depending on stickiness.
Generic hash
upstream app_backend {
hash $request_uri consistent;
server 10.0.0.11:3000;
server 10.0.0.12:3000;
}The hash directive uses any variable or text as the key. The consistent parameter uses consistent hashing, so adding or removing a server remaps only a fraction of the keys instead of nearly all of them.
Weights and server parameters
Each server line accepts parameters. Backends are not always equal, and you sometimes need to take one out of rotation.
upstream app_backend {
server 10.0.0.11:3000 weight=3;
server 10.0.0.12:3000;
server 10.0.0.13:3000 backup;
server 10.0.0.14:3000 down;
}| Parameter | Effect |
|---|---|
| `weight=N` | Share of traffic. The default is 1. With `weight=3` against a default of 1, the first server receives about three of every four requests. |
| `backup` | Used only when all non-backup servers are unavailable. |
| `down` | Marks the server as permanently unavailable. Useful for maintenance, because the line stays in the file. |
| `max_fails=N` | Number of failed attempts within `fail_timeout` before the server is considered unavailable. The default is 1. |
| `fail_timeout=T` | The window in which failures are counted, and also how long the server is then skipped. The default is 10 seconds. |
| `max_conns=N` | Limit on simultaneous connections to this server. |
Passive health checks
The open source version of Nginx does not probe backends on a schedule. It uses passive health checks. It watches real requests, and when a connection to a backend fails or times out, it counts that as a failure. After max_fails failures within fail_timeout, Nginx stops using that server for fail_timeout, then tries it again.
upstream app_backend {
server 10.0.0.11:3000 max_fails=3 fail_timeout=30s;
server 10.0.0.12:3000 max_fails=3 fail_timeout=30s;
}Consequences to keep in mind:
- A real client request is the one that discovers a dead backend. That client may see a delay or an error, unless Nginx retries on another server.
- A backend that answers with an HTTP 500 is not counted as failed by default. Nginx counts connection errors and timeouts. You control which responses count with
proxy_next_upstream. - Active health checks (the
health_checkdirective) are part of the commercial Nginx Plus product.
Retrying on another backend
When an attempt fails, proxy_next_upstream decides whether Nginx tries the next server in the group.
location / {
proxy_pass http://app_backend;
proxy_next_upstream error timeout http_502 http_503;
proxy_next_upstream_tries 2;
proxy_connect_timeout 3s;
proxy_read_timeout 30s;
}errorandtimeoutare the default conditions.http_502andhttp_503add those status codes.proxy_next_upstream_tries 2limits the total number of attempts, including the first.- A short
proxy_connect_timeoutmakes Nginx give up on a dead host quickly. The default is 60 seconds, which is long enough that users give up first.
Be careful with retries on non-idempotent requests. By default, Nginx does not retry a POST, LOCK, or PATCH request after it has been sent to a backend. Adding non_idempotent to proxy_next_upstream changes that, and it can cause a payment or order to be submitted twice. Leave it off unless your application handles duplicate requests.
Keeping connections open to backends
By default, Nginx opens a new TCP connection to a backend for each request. A keepalive directive in the upstream group lets Nginx reuse connections. This lowers latency and CPU use on both sides. It requires HTTP/1.1 and clearing the Connection header.
upstream app_backend {
server 10.0.0.11:3000;
server 10.0.0.12:3000;
keepalive 16;
}
server {
listen 80;
server_name app.example.com;
location / {
proxy_pass http://app_backend;
proxy_http_version 1.1;
proxy_set_header Connection "";
}
}The number after keepalive is the count of idle connections each worker process keeps open. It is not a limit on total connections.
Applying and testing the change
Check the syntax, reload, and then watch which backend answers. The test below assumes each backend adds a header that identifies it, such as X-Backend. If yours does not, compare the backends' own access logs.
sudo nginx -t && sudo systemctl reload nginx
for i in 1 2 3 4 5 6; do curl -s -o /dev/null -D - http://app.example.com/ | grep -i x-backend; doneTo see the chosen backend in Nginx's own logs, add $upstream_addr to a log format:
log_format upstream_log '$remote_addr "$request" $status '
'upstream=$upstream_addr time=$upstream_response_time';
access_log /var/log/nginx/app_access.log upstream_log;When Nginx retried, $upstream_addr lists several addresses separated by commas, which shows you the failover happened.
Common errors
| Symptom | Likely cause |
|---|---|
| `nginx -t` reports `"upstream" directive is not allowed here` | The `upstream` block is inside a `server` block instead of `http`. |
| `host not found in upstream` | A hostname in a `server` line does not resolve when Nginx starts. Fix DNS or use an IP address. |
| `502 Bad Gateway` for every request | No backend is reachable. Check that the application is listening and that the address and port are right. |
| `502` only now and then | One backend is down, and retries are disabled or exhausted. Review `proxy_next_upstream` and the error log. |
| `504 Gateway Timeout` | A backend accepted the connection but did not answer within `proxy_read_timeout`. |
| All traffic goes to one server | `ip_hash` with clients behind one NAT, or large weight differences. |
| Users lose their login between requests | Sessions are stored in each backend's memory, and requests alternate between backends. |
Nginx resolves hostnames in server lines once, when it loads the configuration. If a backend's DNS record changes, you must reload Nginx to pick up the new address.
Exercises
Exercise
You have three backends. The first has twice the CPU of the others. Write the upstream group so the first server receives about half of the requests, and explain why that is the result.
Show answer
upstream app_backend { server 10.0.0.11:3000 weight=2; server 10.0.0.12:3000; server 10.0.0.13:3000; } The weights add up to 4 (2 + 1 + 1), so the first server gets 2 of every 4 requests, which is half. The other two get one quarter each.
Exercise
A client sends a POST request to a backend, and the backend closes the connection before it replies. Nginx has proxy_next_upstream error timeout; configured. Does Nginx send the same POST to the second backend? What would change that, and why might you avoid it?
Show answer
No. By default, Nginx does not retry non-idempotent methods such as POST after the request has been sent to a backend. Adding non_idempotent to proxy_next_upstream allows the retry. You might avoid it because the first backend may have processed the request before it failed, so the retry could run the same action twice.
Exercise
Your site uses ip_hash. Users report that one backend is overloaded while the others are nearly idle. Name one likely cause and one alternative approach.
Show answer
A likely cause is that many clients share one public IP address, for example behind a corporate NAT, or that Nginx sees a front proxy's address instead of the real client address. Alternatives include least_conn combined with a shared session store, or hash on a cookie or header value with consistent.