Balancing algorithms: which one to pick
Inside an upstream block, nginx distributes requests using one of four algorithms:
| Directive | Selection rule | When to use |
|---|---|---|
| (omitted) | Round-robin, honoring weight |
Uniform fast requests (static assets, lightweight APIs) |
least_conn; |
Node with the fewest active connections | Mix of fast and slow requests so one slow node doesn’t pile up a queue |
ip_hash; |
First three octets of client IPv4 (or full IPv6) | App stores sessions in local memory; incompatible with backup |
hash $key consistent; |
Consistent hashing (e.g., on $arg_user or $request_uri) |
Distributed cache or sharding: losing a node remaps the fewest keys |
Every algorithm (except unweighted hash) accepts weight=N: weight=2 on node 1 and weight=1 on node 2 sends twice as many requests to node 1 (four out of every six).
Ready config: upstream, keepalive, and safe retries
A pool with two weighted primary nodes, one backup node, and a persistent keepalive connection pool.
upstream app_pool {
least_conn;
server 10.0.0.11:8080 weight=2 max_fails=2 fail_timeout=10s;
server 10.0.0.12:8080 weight=1 max_fails=2 fail_timeout=10s;
server 10.0.0.13:8080 backup;Declare upstream in the http context (outside server). least_conn routes each new request to the least busy node. max_fails=2 fail_timeout=10s runs passive health checks: two failures within 10 seconds pull the node out for 10 seconds before nginx probes it with one request. backup receives traffic only when every primary node is unavailable.
default:weight 1max_fails 1fail_timeout 10s
keepalive 16;
keepalive_requests 1000;
keepalive_timeout 60s;
}Idle TCP connection cache **per nginx worker** (4 workers × keepalive 16 = up to 64 open connections total). Each connection stays alive for up to 1000 requests or 60s idle, avoiding repeat TCP handshakes and TIME_WAIT buildup.
default:keepalive_requests 1000keepalive_timeout 60s
server {
listen 80;
server_name pool.example.org;
location / {
include snippets/proxy-headers.conf;
proxy_set_header Connection "";
proxy_pass http://app_pool;Include the shared header snippet from Reverse proxy (proxy_http_version 1.1 plus Host/X-Forwarded-*) and clear Connection to an empty string — without both directives, upstream keepalive won’t activate. proxy_pass points to the app_pool group name.
proxy_next_upstream error timeout http_502 http_503 http_504;
proxy_next_upstream_tries 3;
proxy_next_upstream_timeout 10s;
}
}Failover triggers: network error, timeout, or 502/503/504. proxy_next_upstream_tries 3 covers both primary nodes plus backup, while proxy_next_upstream_timeout 10s caps total retry duration at 10 seconds.
default:proxy_next_upstream error timeoutproxy_next_upstream_tries 0 (all)proxy_next_upstream_timeout 0
Open-source nginx health checks are passive: a node is marked down only after live requests fail (max_fails). To drain a node cleanly for maintenance with zero failed requests, mark it down temporarily and reload:
server 10.0.0.11:8080 weight=2 down;
Active background health checks (periodic /health probes by the proxy) aren’t in open-source nginx — they ship in commercial NGINX Plus, HAProxy, and Traefik.
503 maintenance page without reloading nginx
Editing configs and reverting them during a database migration or release adds extra steps. A cleaner pattern is a flag file on disk: creating an empty maintenance.on file switches the site to 503 with Retry-After right away; deleting the file restores traffic immediately.
To let administrators verify the site during maintenance, list their IPs in a geo block (http context).
geo $is_admin {
default 0;
203.0.113.50/32 1;
}IP allowlist that keeps seeing the live site during maintenance (geo lives in the http context, outside server). Everyone else gets $is_admin = 0.
server {
listen 80;
server_name pool.example.org;
error_page 503 @maintenance;
location / {
set $maint 0;
if (-f /var/www/maintenance.on) { set $maint 1; }
if ($is_admin = 1) { set $maint 0; }
if ($maint = 1) { return 503; }
include snippets/proxy-headers.conf;
proxy_set_header Connection "";
proxy_pass http://app_pool;
}When /var/www/maintenance.on exists and the client isn’t allowlisted, return 503 so error_page 503 @maintenance; handles it. Keep any assets used by the page (logo, CSS) in a dedicated location or inline them inside maintenance.html.
location @maintenance {
root /var/www/errors;
add_header Retry-After 300 always;
rewrite ^ /maintenance.html break;
}
}Named maintenance location: Retry-After: 300 tells clients and crawlers to retry in 5 minutes (always is required because 503 is an error status), and rewrite ^ /maintenance.html break; serves the page for any requested path while preserving status 503.
Toggling maintenance mode takes a fraction of a second and needs no reload:
sudo touch /var/www/maintenance.on # return 503 to everyone except $is_admin
sudo rm /var/www/maintenance.on # restore normal traffic
How to check
- Validate syntax and reload:
sudo nginx -t && sudo systemctl reload nginx - Verify weighted distribution (six requests against
weight=2andweight=1):for i in 1 2 3 4 5 6; do curl -s -H "Host: pool.example.org" http://127.0.0.1/; done | sort | uniq -c # 4 app1 # 2 app2 - Confirm
keepaliveholds openESTABconnections to backends:sudo ss -tnp '( dport = :8080 )' | grep ESTAB # ESTAB 0 0 10.0.0.10:46122 10.0.0.11:8080 users:(("nginx",pid=49180,fd=7)) - Stop the first backend and verify failover (with
add_header X-Upstream $upstream_addr always;enabled temporarily in staging):curl -sD - -H "Host: pool.example.org" http://127.0.0.1/ | grep -iE '^(HTTP/|x-upstream)' # HTTP/1.1 200 OK # X-Upstream: 10.0.0.11:8080, 10.0.0.12:8080 - Test maintenance mode:
sudo touch /var/www/maintenance.on curl -sI -H "Host: pool.example.org" http://127.0.0.1/any/path | grep -iE '^(HTTP/|retry-after)' # HTTP/1.1 503 Service Temporarily Unavailable # Retry-After: 300 sudo rm /var/www/maintenance.on
If it doesn’t work
You added keepalive 32; to upstream, yet TIME_WAIT sockets climb under load and backends see a new connection per request
- Cause
- The
locationblock still proxies over HTTP/1.0 withConnection: close(nginx’s default), so thekeepalivepool goes unused. - Fix
- Include both lines in
location:proxy_http_version 1.1;(already insnippets/proxy-headers.conf) andproxy_set_header Connection "";.
Both primary nodes went down, yet backup never answered — clients got 502 with X-Upstream: 10.0.0.11:8101, 10.0.0.12:8102
- Cause
proxy_next_upstream_tries 2;spent both attempts on the two dead primary nodes, so nginx never tried the third (backup) node.- Fix
- Set
proxy_next_upstream_triesto at least the total node count includingbackup(or0for unlimited attempts, capping total time viaproxy_next_upstream_timeout).
During occasional backend timeouts, orders or payments started getting created twice
- Cause
non_idempotentwas added toproxy_next_upstream, making nginx replay aPOSTon a second node while the first was still committing to the database.- Fix
- Remove
non_idempotentfromproxy_next_upstream: without it, nginx retries only safe methods (GET,HEAD,OPTIONS) and never duplicatesPOSTorPATCH.
You served a maintenance page with 200 OK, and search engines replaced page titles with the maintenance notice
- Cause
- Crawlers treated
200as updated site content and re-indexed the placeholder. - Fix
- Always return
503 Service Unavailablewith aRetry-Afterheader (in seconds) so crawlers treat the downtime as temporary and keep existing rankings.
During a planned backend update, some clients hit 502 before the node reaches max_fails
- Cause
- The backend stopped while nginx was still routing traffic to it; non-idempotent
POSTrequests that landed on it first won’t retry on another node. - Fix
- Mark the server
down;inupstream, runsudo nginx -t && sudo systemctl reload nginx, update the backend, removedown;, and reload again.