Health Checks & Balancing
Open-source Nginx only learns that a backend is broken when real requests fail (passive checks). HAProxy probes every server on its own schedule, takes failing ones out before users notice, and puts them back when they recover. Combined with its balancing algorithms, queueing and slow start, this is the main reason teams put HAProxy in front of application fleets.
Active health checks
| Setting | Meaning |
|---|---|
check (on a server line) |
enable health checks for that server; without it the server is always considered up |
option httpchk GET /health |
check with an HTTP request instead of a TCP connect |
http-check expect status 200 |
what counts as healthy (also rstatus 2[0-9][0-9], string ok) |
inter 2s |
time between checks (fastinter/downinter for transitions and down servers) |
fall 3 / rise 2 |
consecutive failures to mark DOWN / successes to mark UP again |
default-server inter 2s fall 3 rise 2 |
set these for every server in the backend |
observe layer7 error-limit 10 on-error mark-down |
also count errors in real traffic (passive), like Nginx's max_fails |
fall and rise add hysteresis: a single failed probe doesn't flap a server out, and a server that recovers must prove itself twice before taking traffic. With inter 2s fall 3, a dead server is detected within about 6 seconds; until then, requests that hit it fail unless option redispatch and retries send them elsewhere.
What /health checks matters as much: a liveness-style endpoint ("the process runs") keeps a server in rotation whose database connection is broken; a deep check ("the database answers") can take the whole fleet out when the shared database blips. A common middle ground: check the server's own dependencies with short timeouts and treat shared ones carefully, as Kubernetes probes do with readiness.
Watching a server go down and come back
Each backend reports unhealthy while a file named down-<name> exists, so the session can break and repair servers on demand. A tiny helper talks to HAProxy's stats socket (the Runtime API):
cat > app.py <<'EOF'
import os, sys
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
NAME = sys.argv[2]
class H(BaseHTTPRequestHandler):
def do_GET(self):
sick = os.path.exists(f"down-{NAME}")
code = 503 if (self.path == "/health" and sick) else 200
self.send_response(code); self.end_headers(); self.wfile.write(f"{NAME}\n".encode())
def log_message(self, *a): pass
ThreadingHTTPServer(("127.0.0.1", int(sys.argv[1])), H).serve_forever()
EOF
python3 app.py 9001 web1 & python3 app.py 9002 web2 & python3 app.py 9003 web3 &
for p in 9001 9002 9003; do for i in $(seq 50); do curl -s 127.0.0.1:$p/ > /dev/null && break; sleep 0.1; done; done
cat > haproxy.cfg <<'EOF'
global
pidfile haproxy.pid
stats socket "${HOME}/admin.sock" mode 600 level admin
defaults
mode http
timeout connect 1s
timeout client 10s
timeout server 10s
frontend fe
bind 127.0.0.1:8080
default_backend be_app
backend be_app
balance roundrobin
option httpchk GET /health
http-check expect status 200
default-server check inter 500ms fall 2 rise 3
server web1 127.0.0.1:9001
server web2 127.0.0.1:9002
server web3 127.0.0.1:9003
EOF
haproxy -c -f haproxy.cfg && haproxy -D -f haproxy.cfg
hap() { python3 -c 'import socket,sys; s=socket.socket(socket.AF_UNIX); s.connect("admin.sock"); s.sendall((sys.argv[1]+"\n").encode()); print(s.makefile().read(), end="")' "$1"; }
state() { hap "show stat" | awk -F, '$1=="be_app" && $2 ~ /^web/ {printf "%s=%s ", $2, $18} END {print ""}'; }
wait_for() { for i in $(seq 50); do state | grep -q "$1" && break; sleep 0.1; done; }
wait_for "web1=UP web2=UP web3=UP quot;; echo "start: $(state)"
echo "traffic: $(for i in 1 2 3 4 5 6; do curl -s 127.0.0.1:8080/; done | tr '\n' ' ')"
touch down-web2; wait_for "web2=DOWN"
echo "web2 sick: $(state)"
echo "traffic: $(for i in 1 2 3 4; do curl -s 127.0.0.1:8080/; done | tr '\n' ' ')"
rm down-web2; wait_for "web2=DOWN 1/3"
echo "recovering: $(state)"
echo "traffic: $(for i in 1 2 3 4; do curl -s 127.0.0.1:8080/; done | tr '\n' ' ')"
wait_for "web2=UP web3"
echo "recovered: $(state)"
hap "show stat" | awk -F, '$2=="web2" {print "web2 last check: " $37 ", times down: " $23}'
kill $(cat haproxy.pid) %1 %2 %3Configuration file is valid
start: web1=UP web2=UP web3=UP
traffic: web1 web2 web3 web1 web2 web3
web2 sick: web1=UP web2=DOWN web3=UP
traffic: web1 web3 web1 web3
recovering: web1=UP web2=DOWN 1/3 web3=UP
traffic: web1 web3 web1 web3
recovered: web1=UP web2=UP web3=UP
web2 last check: L7OK, times down: 1
The DOWN 1/3 state is the hysteresis at work: web2 passed its first check, but it stays DOWN and gets no traffic until it has passed three in a row (rise 3). In the other direction a failing server shows UP 1/2 (still in rotation) before fall 2 takes it out. While it was down, its share went to the others with no failed requests, because the probe noticed before any client did. The last line reads two more show stat columns: the result of the last check and how often the server went down (chkdown), a number worth graphing.
Balancing algorithms
balance |
Picks | Use |
|---|---|---|
roundrobin |
in turn, by weight; weights can change at runtime | the default; stateless apps |
static-rr |
in turn, weights fixed | slightly cheaper; no runtime weight changes |
leastconn |
fewest active connections | long or uneven requests, WebSockets, databases |
first |
the first server with free maxconn slots |
pack load onto few servers (autoscaling down) |
source |
hash of the client address | stickiness without cookies |
uri / url_param / hdr(name) |
hash of the URI / a query parameter / a header | cache servers; shard by tenant |
random(2) |
best of two random picks | many load balancers sharing servers |
Add hash-type consistent to the hashing ones so that adding or removing a server moves as few keys as possible, the same idea as Nginx's hash … consistent.
Queues, slow start and backups
backend be_app
balance leastconn
timeout queue 5s # how long a request may wait for a free slot
default-server check maxconn 50 slowstart 30s
server web1 10.0.1.11:8000
server web2 10.0.1.12:8000
server sorry 10.0.9.9:8000 backup # only when every normal server is downmaxconn 50 per server is one of HAProxy's best features: instead of overloading an app that can handle 50 requests at once, HAProxy queues the excess and hands requests over as slots free up, keeping the app at its efficient concurrency. Requests that wait longer than timeout queue get a 503. slowstart 30s ramps a server's weight up over 30 seconds after it comes back, so a cold JVM or empty cache isn't flooded the moment its health check passes.
Test yourself
With inter 2s fall 3 rise 2, how is a server treated after one failed check?
- It is marked DOWN immediately
- It stays UP (shown as going down 1/3); only three consecutive failures mark it DOWN
- It is removed from the config
- It gets half the traffic
What does maxconn 50 on a server line do when 80 requests arrive at once?
- Rejects 30 with 503 immediately
- Sends 50 to the server and queues 30 in HAProxy until slots free up (or
timeout queueexpires) - Sends all 80
- Moves 30 to the backup server
Why can a health check that tests the shared database be dangerous?
- It is slow
- A database blip makes every server fail its check at once, taking the whole backend out
- It needs credentials
- HAProxy can't do HTTP checks