Sub topic 5
Health checks: keeping traffic off failed backends
This chapter assumes you know what a load balancer does and how it picks a backend. It also assumes you can read NGINX or HAProxy configuration. A balancing algorithm only chooses among servers the balancer believes are usable. Health checks are how it forms that belief. If they are wrong, the balancer sends users to dead servers or removes good servers from rotation.
What a health check decides
A health check is a test the load balancer uses to decide whether a backend may receive traffic. Each backend is in one of two states from the balancer's point of view: in rotation or out of rotation. The check only moves it between the two.
There are two ways to gather evidence:
- Active checks. The balancer sends its own probe to each backend at a fixed interval, whether or not real users are connected.
- Passive checks. The balancer watches real traffic. If proxied requests fail or time out, it marks the backend as failed. Passive checking is also called outlier detection.
| Aspect | Active check | Passive check |
|---|---|---|
| Source of evidence | Synthetic probe | Real user requests |
| Detects failure | Even with no traffic | Only when traffic arrives |
| Cost to users | None, the probe absorbs the failure | The failing request is a real user's request |
| Extra load | Small constant probe traffic | None |
| Typical setting | `check` in HAProxy | `max_fails` in open-source NGINX |
Using both is common. The active check finds problems early. The passive check reacts within one request when something breaks between probes.
Types of probe
The probe decides how much "healthy" means. Deeper probes give better answers but cost more and fail in more ways.
- TCP connect. The balancer opens a connection and closes it. This proves the process is listening. It does not prove the application works. A server that accepts connections but returns errors on every request passes.
- HTTP request. The balancer sends a request such as
GET /healthzand checks the status code, and sometimes the body. This proves the application can answer. - Application-level or script check. The balancer runs an external command or calls a dedicated agent. This is the most flexible and the most work to maintain.
A Layer 4 balancer can usually only do TCP probes, though many also support HTTP probes. A Layer 7 balancer can inspect responses. This follows from the layer you chose in the previous chapters.
The state machine: thresholds and flapping
One failed probe should not remove a server. Networks drop packets, and garbage collection pauses stall responses. Balancers therefore use counters before changing state.
In HAProxy these are fall (consecutive failures before marking down) and rise (consecutive successes before marking up). The defaults are 3 and 2.
The thresholds trade speed against stability:
- Low
fall. A failed server leaves rotation quickly, but a brief hiccup also removes healthy servers. - High
fall. The balancer tolerates noise, but it keeps sending users to a dead server for longer. - Low
rise. A server returns quickly, but it may return before it is fully warm. - High
rise. A server returns only when it is stable, but capacity stays reduced longer.
A server that alternates between up and down is flapping. Flapping causes constant reshuffling of traffic and can overload the remaining servers. Raising rise is the usual fix, because servers should be harder to re-admit than to remove.
Worst-case detection time is roughly inter × fall plus the probe timeout. With inter 2s fall 3, a server that dies right after a successful probe is detected after about 6 seconds. During that time, about a third of requests to a two-server pool can fail. Clients or the balancer must retry those requests, or you accept the loss.
Passive checks in NGINX
Open-source NGINX has no built-in active HTTP probe. Active checks (health_check) are part of the commercial NGINX Plus. Open-source NGINX uses passive checks, configured per server:
upstream app {
least_conn;
server 10.0.0.11:8080 weight=3 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;
}
server {
listen 80;
location / {
proxy_pass http://app;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}max_fails=3 fail_timeout=30s has two meanings, and people often miss the second:
- If 3 attempts fail within a 30-second window, NGINX considers the server unavailable.
- It then skips that server for the next 30 seconds. After that it tries the server again with a real request, and success restores normal service.
What counts as a failure is controlled by proxy_next_upstream. Its default is error timeout, so a backend that quickly returns HTTP 500 is not counted as failed. If you want 502 or 503 to count and the request to be retried on another server, add them explicitly:
location / {
proxy_pass http://app;
proxy_next_upstream error timeout http_502 http_503;
proxy_next_upstream_tries 2;
}Retrying has a risk. A non-idempotent request, such as a payment POST, may run twice if the first backend processed it but failed to respond. NGINX does not retry non-idempotent requests by default after they have been sent. Be careful when you change that.
The backup server receives traffic only when all primary servers are unavailable. It is a simple way to serve a maintenance page or a smaller fallback pool.
Active checks in HAProxy
HAProxy supports active checks directly. The check keyword on a server line turns them on:
frontend web
mode http
bind *:443 ssl crt /etc/haproxy/certs/site.pem
default_backend app
backend app
mode http
balance roundrobin
option httpchk GET /healthz
http-check expect status 200
cookie SRV insert indirect nocache
server app1 10.0.0.11:8080 check cookie app1
server app2 10.0.0.12:8080 check cookie app2Without option httpchk, check performs only a TCP connect. With it, HAProxy sends GET /healthz and http-check expect status 200 requires exactly that status. Without the expect line, any 2xx or 3xx response counts as healthy.
You can tune timing on each server line:
server app1 10.0.0.11:8080 check inter 2s fastinter 500ms downinter 5s fall 3 rise 2interis the interval between checks when the state is stable.fastinteris the interval while the server is changing state, which speeds up confirmation.downinteris the interval while the server is confirmed down.
HAProxy can also combine this with passive observation using observe layer7 and on-error mark-down, which counts real response errors toward the failure threshold.
Designing the health endpoint
The endpoint your probe calls matters as much as the balancer settings. Here is a minimal one in Python, using only the standard library:
from http.server import BaseHTTPRequestHandler, HTTPServer
ready = True # set to False to simulate a server that should leave rotation
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path == "/healthz":
body = b"ok\n" if ready else b"not ready\n"
self.send_response(200 if ready else 503)
else:
body = b"not found\n"
self.send_response(404)
self.send_header("Content-Type", "text/plain")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
if __name__ == "__main__":
HTTPServer(("0.0.0.0", 8080), Handler).serve_forever()Run it and curl -i http://localhost:8080/healthz returns 200. Change ready to False and it returns 503, which http-check expect status 200 treats as a failure.
Guidelines for what the endpoint should check:
- Keep it cheap. The balancer calls it every few seconds, and a single pool may be probed by several balancers. A heavy query on each probe is a self-inflicted load problem.
- Test what this server controls. Check that the process is running, its worker pool is not exhausted, and local resources such as disk are available.
- Be careful with shared dependencies. If every server's health endpoint queries the same database, a database outage fails every probe. The balancer then removes every backend at once, and a partial outage becomes a total one. Often the better design is to keep serving and return application-level errors.
- Separate liveness from readiness. Liveness asks "is the process broken and in need of a restart?" Readiness asks "can it take traffic right now?" A server that is starting up or shutting down is alive but not ready. Load balancers should normally use readiness.
- Use the same path as users when possible. A probe that skips the application stack, for example one that hits a static file, can pass while real routes fail.
Failure modes to plan for
- All backends fail the check. With no healthy server, most balancers return 503. HAProxy and some cloud balancers can instead send traffic to all servers anyway (fail-open, sometimes called panic mode). Decide which behavior you want. Fail-open can work when the checks are the problem, and it is harmful when the servers are truly down.
- Thundering herd on recovery. When a server returns, it may immediately receive a large share of traffic with cold caches. Slow-start options such as HAProxy's
slowstart 30sramp weight up gradually. - Probe and traffic diverge. The probe uses a different port, host header, or TLS setting than users, so it reports a state that does not match real behavior. Test the probe through the same path where you can.
- Overly strict timeouts. If the probe timeout is shorter than normal response time under load, busy servers fail checks and are removed, which pushes more load onto the rest. This can cascade.
- Check traffic in logs. Probes appear in access logs and metrics. Filter them out so they do not distort request counts and latency.
Exercise
A HAProxy backend uses inter 3s fall 4 rise 2 and a probe timeout of 2s. A server crashes just after passing a probe. Roughly how long can the balancer keep sending it traffic in the worst case, and how long after it is fixed until it can receive traffic again, assuming the server answers every probe once fixed?
Show answer
Removal takes about 4 failed probes spaced 3s apart, so about 12s, plus up to 2s of timeout on the last probe, for roughly 12 to 14s of exposure. Re-admission needs 2 consecutive successes, so about 6s after the first successful probe (the first success comes within 3s of the fix). In total, the server returns to rotation roughly 3 to 6s after it is fixed.