Sub topic 8
Handling Failed Backends with Passive Checks and Retries
This chapter assumes you can already write an upstream block, point proxy_pass at it, and reload Nginx safely. It covers what Nginx does when a backend misbehaves, and how to tune that behavior.
Passive checks: what Nginx can see
Open source Nginx has no built-in active health check. It never probes a backend on a timer. It learns that a server is unhealthy only by watching real client traffic. This is called a passive health check.
When Nginx tries to reach a backend and the attempt fails, it counts that failure against the server. After enough failures within a time window, Nginx stops sending traffic to that server for a while. When the window ends, it tries the server again.
The consequence is that a real client request pays for each discovery. The first requests that hit a dead backend may be slow or retried. Passive checks reduce the damage, and they do not prevent it.
The two directives on the server line
Two parameters on each server line in an upstream block control this behavior.
max_fails=Nis the number of failed attempts withinfail_timeoutthat mark the server as unavailable. The default is 1. Setting it to 0 turns the accounting off, so the server is never marked unavailable.fail_timeout=Thas two jobs. It is the window in which the failures are counted. It is also how long the server is considered unavailable once the limit is reached. The default is 10 seconds.
Here is an example.
upstream app_backend {
server 10.0.0.11:8080 max_fails=3 fail_timeout=30s;
server 10.0.0.12:8080 max_fails=3 fail_timeout=30s;
}If three attempts to 10.0.0.11 fail within 30 seconds, Nginx skips that server for the next 30 seconds. After that, it lets a request through to test it. If that request succeeds, the server returns to normal rotation. If it fails, the server is skipped again.
The time window is easy to misread. The failure counter is not a lifetime total. Three failures spread over ten minutes never mark a server down with fail_timeout=30s.
What counts as a failure
Nginx does not treat every bad response as a failed attempt. The directive proxy_next_upstream decides which outcomes count. Its default is:
proxy_next_upstream error timeout;The condition names are listed below.
| Condition | Meaning |
|---|---|
| `error` | Connecting, sending a request or reading a response failed at the network level |
| `timeout` | A connect, send or read timeout expired |
| `invalid_header` | The backend returned an empty or invalid response header |
| `http_500`, `http_502`, `http_503`, `http_504` | The backend returned that status code |
| `http_403`, `http_404`, `http_429` | The backend returned that status code |
| `non_idempotent` | Allow retrying non-idempotent requests such as POST |
| `off` | Never pass a request to the next server |
With the defaults, a backend that answers 503 is not counted as failed. Nginx received a valid HTTP response, so the connection worked. If you want 502 and 503 to count, you must list them:
proxy_next_upstream error timeout http_502 http_503;There is one exception that surprises people. The status codes http_403, http_404 and http_429 are never counted toward max_fails, even if you list them in proxy_next_upstream. They allow a retry on another server, and they do not mark the server unhealthy. A 404 usually reflects the request and not the server's health.
Retries: what Nginx does with a failed request
When an attempt fails in a way that proxy_next_upstream allows, Nginx passes the request to the next server in the group. The client sees only the final result. Two safeguards limit this behavior.
proxy_next_upstream_tries Nlimits the total number of attempts, including the first. The default of 0 means no limit beyond the number of servers.proxy_next_upstream_timeout Tlimits the total time spent on retries. The default of 0 means no limit.
location / {
proxy_pass http://app_backend;
proxy_next_upstream error timeout http_502 http_503;
proxy_next_upstream_tries 2;
proxy_next_upstream_timeout 5s;
}This configuration tries at most two servers and gives up after five seconds of retrying. Without these limits, a slow failure on every server could make a client wait through each backend's full timeout in sequence.
A retry is possible only if Nginx has not yet started sending the response to the client. Once the first bytes of the response have gone out, Nginx cannot switch servers.
Retries and non-idempotent requests
An idempotent request is one that can be repeated without changing the result more than once. GET, HEAD, PUT and DELETE are idempotent. POST and PATCH are not.
By default, Nginx does not retry a non-idempotent request once it has been sent to a backend. If the backend received the request and then crashed, you cannot know whether it processed a payment or created a record. Retrying could do it twice. Adding non_idempotent to proxy_next_upstream removes this protection.
# Risky: a retried POST may be processed twice
proxy_next_upstream error timeout non_idempotent;A related detail is that a timeout can mean the backend is still working. If the read timeout fires while the backend is processing a slow request, Nginx may send the same request to another server while the first one is still running. For safe methods this only wastes work. For unsafe methods the default protection applies.
Backup servers
A server marked backup receives no traffic while any primary server is available. It is used only when all primaries are unavailable.
upstream app_backend {
server 10.0.0.11:8080 max_fails=3 fail_timeout=30s;
server 10.0.0.12:8080 max_fails=3 fail_timeout=30s;
server 10.0.0.13:8080 backup;
}Backup servers suit a standby instance, or a small server that returns a "temporarily degraded" page. Two limits apply. The backup parameter cannot be used with the hash, ip_hash and random balancing methods. A backup server also sits idle, so its health is never tested until you need it. Check it separately.
You can also mark a server down to take it out of rotation by hand. This is useful during maintenance. With ip_hash, it preserves the current hashing of clients.
server 10.0.0.12:8080 down;What happens when every server is down
If all primaries and backups are marked unavailable, Nginx does not return an error immediately. In that case it resets the failure counters and tries the servers again. This means a short outage of the whole group usually ends without a lasting lockout. During the outage, clients get a 502 Bad Gateway, or a 504 Gateway Timeout if the attempts timed out.
This is also why max_fails and fail_timeout are not a circuit breaker in the strict sense. They help with a single failing server and have little effect on a group-wide failure.
Timeouts decide how fast you notice
How long a failure takes to detect depends on the proxy timeouts. These directives are covered more fully in a later chapter. Three matter here:
proxy_connect_timeoutis how long to wait to establish a connection. The default is 60 seconds.proxy_send_timeoutis how long to wait between two write operations. The default is 60 seconds.proxy_read_timeoutis how long to wait between two reads of the response. The default is 60 seconds.
A dead host that silently drops packets makes Nginx wait for the full connect timeout. With the default of 60 seconds, a client could wait a minute before the retry begins. Lowering the connect timeout makes failover much faster.
location / {
proxy_pass http://app_backend;
proxy_connect_timeout 3s;
proxy_next_upstream error timeout http_502 http_503;
proxy_next_upstream_tries 2;
}A refused connection, where the host is up but nothing listens on the port, fails immediately. A crashed host that no longer answers at all is the slow case.
A worked failure sequence
The following diagram shows a request when the first backend is down and the second is healthy.
The client never sees the failure. Nginx records one failure for 10.0.0.11. If two more occur within fail_timeout, the server is skipped until the window ends.
Seeing failures in the logs
The error log records each failed attempt, even when the retry succeeds. A typical line looks like this:
2026/11/28 04:01:47 [error] 1234#1234: *7 connect() failed (111: Connection refused) while connecting to upstream, client: 203.0.113.9, server: example.com, request: "GET /orders HTTP/1.1", upstream: "http://10.0.0.11:8080/orders", host: "example.com"When Nginx marks a server unavailable, it does not log that decision at the default level. You see only the individual failures. To see which servers served a request, including retries, log the upstream variables. With retries, $upstream_addr and $upstream_status contain comma-separated lists, one entry per attempt.
log_format upstream_log '$remote_addr [$time_local] "$request" $status '
'upstream=$upstream_addr '
'upstream_status=$upstream_status '
'urt=$upstream_response_time rt=$request_time';
access_log /var/log/nginx/proxy_access.log upstream_log;A line such as upstream=10.0.0.11:8080, 10.0.0.12:8080 upstream_status=-, 200 shows that the first attempt failed with no status and the second succeeded.
Testing your configuration
Check the syntax and reload, then stop one backend and watch the result.
sudo nginx -t && sudo systemctl reload nginx
for i in $(seq 1 10); do curl -s -o /dev/null -w "%{http_code}\n" http://example.com/; done
sudo tail -n 5 /var/log/nginx/error.logStop one backend service and run the loop again. Every request should still return 200, and the error log should show connection failures for the stopped server. If you see 502 responses, check that the proxy_next_upstream conditions match the failure you caused.
Common mistakes
- Expecting a
503from the backend to trigger a retry. It does not unless you listhttp_503. - Setting
max_fails=0and wondering why a dead server keeps receiving traffic. - Leaving the connect timeout at 60 seconds and finding that failover takes a minute.
- Enabling
non_idempotentwithout protection against duplicates. - Relying on a single
backupserver that has never received traffic. - Using
proxy_next_upstream_trieswithout also setting a timeout, which lets total retry time grow.
Exercise
An upstream has two servers with max_fails=2 fail_timeout=20s, and the location uses the default proxy_next_upstream. Server A starts returning HTTP 503 for every request. Does Nginx mark A as unavailable, and what change would make it retry those requests on server B?
Show answer
No. The default conditions are error and timeout, and a 503 is a valid HTTP response, so it is neither retried nor counted toward max_fails. Add http_503 to the list, for example proxy_next_upstream error timeout http_503;. After two such failures within 20 seconds, A is skipped for 20 seconds, and each failed request is retried on B.
Exercise
A backend host loses power and stops answering. Clients wait about a minute before they get a response from the second backend. Which directive causes this delay by default, and what two directives would you set to bound the delay?
Show answer
proxy_connect_timeout defaults to 60 seconds, and Nginx waits that long for the dead host to accept the connection. Lower it, for example to 3s, and set proxy_next_upstream_timeout (and optionally proxy_next_upstream_tries) to cap the total time spent retrying.
Exercise
Why does Nginx refuse by default to retry a POST that reached a backend before the connection failed, and when is it acceptable to override that?
Show answer
The backend might have processed the request before failing, so a retry could repeat a side effect such as a payment. Override it with non_idempotent only when the application deduplicates requests, for example with idempotency keys.