Sub topic 9
Detecting failed backends
This chapter assumes you know how a reverse proxy distributes requests across backends (the previous chapter on load balancing), basic HTTP status codes, and what a TCP connection and a timeout are. It covers how a proxy learns that a backend has failed, what it does next, and where this detection goes wrong.
Why failure detection is needed
A load balancer that keeps sending requests to a dead backend turns one failed server into failed requests for many users. With two backends and round-robin, half of all requests would hit the dead one. The proxy therefore needs a way to decide that a backend is unhealthy and stop sending it traffic. It also needs a way to decide when the backend has recovered.
Detection methods fall into two groups:
- Passive checks watch real client traffic. If a request to a backend fails, the proxy records it.
- Active checks send synthetic probe requests to each backend on a timer, whether or not clients are asking for anything.
Open-source nginx supports passive checks. Active checks are available in NGINX Plus, HAProxy, Envoy, Traefik and most cloud load balancers. Many production setups use both.
Passive checks in nginx
The first nginx example from the plan marks backends like this:
upstream app_servers {
server 10.0.0.11:8080 max_fails=3 fail_timeout=30s;
server 10.0.0.12:8080 max_fails=3 fail_timeout=30s;
}The two parameters work together:
max_fails=3means that three failed attempts within onefail_timeoutwindow mark the server as unavailable.fail_timeout=30shas two jobs. It is the window in which failures are counted, and it is also how long the server is considered unavailable once marked.
After 30 seconds, nginx tries the server again with a real request. If that request succeeds, the failure count resets and the server rejoins the rotation. If it fails, the server is marked unavailable for another 30 seconds.
What counts as a failure
By default, nginx counts a failure when it cannot connect to the backend, cannot send the request, cannot read the response header, or hits a timeout while doing so. An HTTP 500 response is not counted by default, because the backend did answer. The directive proxy_next_upstream controls which conditions count and also which conditions make nginx retry the same request on another backend.
location / {
proxy_pass http://app_servers;
proxy_connect_timeout 2s;
proxy_read_timeout 10s;
proxy_next_upstream error timeout http_502 http_503;
proxy_next_upstream_tries 2;
}This configuration does the following:
- Gives up on a connection attempt after 2 seconds.
- Gives up waiting for a response after 10 seconds.
- Treats connection errors, timeouts,
502and503responses as failures that justify trying another backend. - Allows at most two attempts in total for one client request.
Without proxy_connect_timeout, a backend that silently drops packets can make each attempt wait 60 seconds, which is the nginx default. A short connect timeout is the cheapest way to make failures cheap.
The cost of passive checks
Passive detection has no extra load and no extra configuration on the backend. Its weakness is that a real user request has to fail before the proxy learns anything. With max_fails=3, at least three requests are affected, or retried, before the server is removed. If the proxy retries on another backend, the user may never notice. If it does not, the user sees an error.
Retries have their own risk. Retrying a request that is not idempotent can run it twice. An idempotent request is one where repeating it has the same effect as sending it once, such as GET or PUT. A POST that creates an order is not idempotent. nginx does not retry non-idempotent requests (POST, LOCK, PATCH) once they have been sent to a backend, unless you add non_idempotent to proxy_next_upstream. Leave that option off unless the application deduplicates requests.
Active health checks
An active check is a probe that the proxy sends on its own schedule. A typical probe is an HTTP GET /healthz every 5 seconds. A backend is considered healthy when the response is 200 and unhealthy otherwise.
HAProxy shows the idea clearly:
backend app_servers
balance roundrobin
option httpchk
http-check send meth GET uri /healthz ver HTTP/1.1 hdr Host example.com
http-check expect status 200
server app1 10.0.0.11:8080 check inter 5s fall 3 rise 2
server app2 10.0.0.12:8080 check inter 5s fall 3 rise 2The check parameters mean:
| Parameter | Meaning |
|---|---|
| `inter 5s` | Probe every 5 seconds |
| `fall 3` | Mark the server down after 3 consecutive failed probes |
| `rise 2` | Mark the server up again after 2 consecutive successful probes |
The worst-case time to detect a failure is roughly inter × fall, here 15 seconds, plus the probe timeout. Lower values detect failures faster but make the proxy more sensitive to brief hiccups. Separate fall and rise values add hysteresis: it takes more evidence to bring a server back than a single good probe, which prevents a flapping server from bouncing in and out of rotation.
Designing a good health endpoint
What the probe asks matters more than how often it asks. There are three common levels:
- Port check. The proxy opens a TCP connection and closes it. This confirms that a process is listening, and nothing else. A server that accepts connections but returns errors for every request still passes.
- Shallow HTTP check.
GET /healthzreturns200if the application process is running and can serve a request. It does not touch other systems. - Deep check. The endpoint also queries the database, cache or other dependencies.
Deep checks look attractive and are often a mistake. If every backend checks the same database and the database slows down, all backends fail their probes at once. The proxy then has no healthy backends, and a partial degradation becomes a full outage. A common compromise is to keep the load balancer's probe shallow, and to expose dependency status on a separate endpoint for monitoring and alerting.
The probe should also exercise the same path as real traffic where it matters. For example, send the correct Host header, as in the HAProxy example, because a virtual host that rejects unknown hosts would otherwise fail every probe.
Slow starts and draining
Detection is only half of the lifecycle. Two related behaviors matter when servers come and go.
- Slow start. A freshly recovered server with cold caches can be overwhelmed if it immediately receives its full share. Some proxies ramp traffic up gradually. In nginx this is the
slow_startparameter, available in NGINX Plus. HAProxy hasslowstart. - Connection draining. When you remove a backend on purpose, for a deploy, you want in-flight requests to finish. Marking the server as
downin nginx stops new requests while existing connections continue. HAProxy offers adrainstate for this.
Failure modes to watch for
| Problem | What happens | Mitigation |
|---|---|---|
| Retry storm | A struggling backend fails requests, and retries multiply the load on the remaining backends, which then fail too | Limit tries with `proxy_next_upstream_tries`, and set `proxy_next_upstream_timeout` |
| All backends marked down | Every server fails its probe, so the proxy has nowhere to send traffic | Keep probes shallow. Some proxies keep sending traffic anyway when all servers are down (HAProxy and Envoy have panic modes that ignore health status) |
| Flapping | A server oscillates between healthy and unhealthy | Use `rise` greater than 1, and fix the underlying cause |
| Slow, not dead | The server answers but takes 20 seconds, which passes a port check and ties up connections | Set read timeouts. Use a health endpoint with a response-time limit |
| Wrong probe path | The probe passes while real requests fail, or the reverse | Probe a path that exercises the application, with the right `Host` header |
| Checker is single | One proxy's view of a backend may differ from another's because of network partitions | Treat health as a local opinion, and monitor from several vantage points |
When nginx marks every server in an upstream as unavailable, it does not stop trying. It resets the state and tries the servers again, so a total outage does not become permanent after the backends recover.
Verifying your setup
Test failure detection before production does it for you. With the first nginx example running, stop one backend and watch the proxy's logs:
# Send 20 requests and print the status code of each
for i in $(seq 1 20); do
curl -s -o /dev/null -w "%{http_code}\n" http://example.com/
done | sort | uniq -cRun this once with both backends up, then stop one backend and run it again. With passive checks only, expect a few errors or slow responses at first, followed by clean 200 responses once the failed server is marked unavailable. If errors continue, check that proxy_next_upstream includes the failure type you caused.
Exercise
A proxy runs HAProxy-style active checks with inter 4s fall 3 rise 2 and a probe timeout of 2 seconds. A backend crashes immediately after a successful probe. Roughly how long can clients be sent to the dead backend in the worst case, and what is one way to reduce that window without making the proxy more sensitive to a single dropped probe?
Show answer
The next probes run at 4, 8 and 12 seconds after the last good one. Each fails (the last is declared failed after its timeout), so the server is marked down around 12 to 14 seconds after the crash, about inter × fall plus the probe timeout. During that time clients can be sent to it. To shorten the window without reacting to one dropped probe, keep fall 3 but lower inter (for example 2s), and add passive detection or retries (a proxy_next_upstream-style setting) so that a real failed request is retried on another backend immediately.
Exercise
Why is a health endpoint that checks the database a risk when all backends share one database?
Show answer
If the database slows down or fails, every backend fails its probe at the same time. The proxy then marks all of them unhealthy and has no valid target, so a partial problem becomes a complete outage. A shallow probe keeps backends in rotation, so the application can still serve requests that do not need the database, and can return its own error handling for the rest.