Day 4: Failures at the load balancer
Goal: Deliberately crash instances, take a machine off the network, restart, and stop the database, counting the errors each time, and configure HAProxy and the app so that users notice nothing · Duration: approx. 75 min · Prerequisite: Day 3
Briefing
- Two instances only help if the failure of one of them does not mean a failure for the users. That has to be measured, not assumed.
- Failures look very different:
| Failure | What HAProxy sees | How quickly it is clear |
|---|---|---|
| Process dies | Connection refused (RST) | immediately |
| Machine gone, network dead | nothing at all, packets vanish | only after timeouts |
| Restart during deploy | briefly refused, in-flight requests abort | immediately |
| Dependency gone (database) | Health check fails on all of them | after fall checks |
- Today k6 runs at 800 requests per second via HAProxy while you inject faults. The result of each drill is the number of failed requests.
Drill 1: The process dies
# on s1
mkdir -p ~/sd/tag04 && cd ~/sd/tag04 && cp ~/sd/tag01/codes.txt ~/sd/tag01/mix.js .
sed -i 's/rate<0.01/rate<1/' mix.js
(ZIEL=http://localhost RATE=800 DAUER=20s k6 run --quiet mix.js > k6-kill9.txt 2>&1 &)
sleep 6
ssh s2 'sudo kill -9 $(pidof kurz); sleep 1; systemctl show kurz -p NRestarts'
sleep 16
grep -E 'http_req_failed\.|http_reqs\.' k6-kill9.txt | sed 's/ */ /g'The sed raises the error threshold so that k6 keeps
measuring on errors today instead of aborting.
Expected:
NRestarts=2
http_req_failed................: 0.00% 0 out of 15963
http_reqs......................: 15963 797.853333/s
Not a single error. Restart=on-failure in the unit makes
systemd restart the process after 100 ms, and NRestarts
keeps count. For the few requests in between, HAProxy takes a new
connection, and that already works again. A crashing process on a
healthy machine is the most harmless failure.
Save your progress? Sign up for free
Drill 2: The machine disappears
Worse is a machine that simply stops answering: power failure, hung kernel, network gone. A firewall rule that drops all packets to port 8080 reproduces this:
# on s1
(ZIEL=http://localhost RATE=800 DAUER=40s k6 run --quiet mix.js > k6-drop.txt 2>&1 &)
sleep 8
ssh s2 "sudo iptables -I INPUT -p tcp --dport 8080 -j DROP"
for i in $(seq 1 12); do
echo "$(date +%T) $(echo 'show stat' | sudo nc -U /run/haproxy/admin.sock | cut -d, -f2,18,37 | sed -n 4p)"
sleep 1
done
sleep 8
ssh s2 "sudo iptables -D INPUT -p tcp --dport 8080 -j DROP"
sleep 14
grep -E 'http_req_duration\.|http_req_failed\.|http_reqs\.' k6-drop.txt | sed 's/ */ /g'Expected:
20:47:02 s2,UP,L7OK
20:47:04 s2,UP,* L7OK
20:47:06 s2,UP 2/3,L4TOUT
20:47:09 s2,UP 1/3,L4TOUT
20:47:13 s2,UP 1/3,* L4TOUT
20:47:14 s2,DOWN,L4TOUT
http_req_duration..............: avg=23.69ms min=1ms med=3.14ms max=26.83s p(90)=24.15ms p(95)=34.21ms
http_req_failed................: 0.02% 8 out of 31931
http_reqs......................: 31931 798.197659/s
Expected shows only every second line of the loop.
From the cutoff (20:46:59) to DOWN, 15
seconds pass: each check waits 2 s for a connection
(timeout connect) and comes only every 2 s
(inter), and only the third failure counts
(fall 3). L4TOUT means a timeout at layer 4,
that is TCP.
Still only 8 errors, and that is thanks to yesterday’s
leastconn: connections to s2 hang, so s2 quickly has the
most open connections and gets no new ones. For comparison, the same
failure with round robin:
# on s1
sudo sed -i "s/^ balance .*/ balance roundrobin/" /etc/haproxy/haproxy.cfg
sudo systemctl reload haproxy && sleep 4
(ZIEL=http://localhost RATE=800 DAUER=40s k6 run --quiet mix.js > k6-drop-rr.txt 2>&1 &)
sleep 8; ssh s2 "sudo iptables -I INPUT -p tcp --dport 8080 -j DROP"
sleep 20; ssh s2 "sudo iptables -D INPUT -p tcp --dport 8080 -j DROP"
sleep 14
grep -E 'http_req_failed\.|http_reqs\.|dropped' k6-drop-rr.txt | sed 's/ */ /g'
sudo sed -i "s/^ balance .*/ balance leastconn/" /etc/haproxy/haproxy.cfg
sudo systemctl reload haproxyExpected:
http_req_failed................: 2.12% 444 out of 20916
http_reqs......................: 20916 522.826018/s
dropped_iterations.............: 11085 277.085791/s
444 errors, and throughput collapses to 523/s: until
DOWN, round robin stubbornly sends every second request
into the void, and each one waits 2 s until HAProxy gives up.
Save your progress? Sign up for free
Drill 3: Try somewhere else
That leaves the 8 errors with leastconn. They are
requests whose connection setup to s2 failed. HAProxy then tries again,
but on the same server. Two lines change that:
# on s1
sudo sed -i "s/^ timeout server 30s/ timeout server 30s\n retries 2\n option redispatch/" \
/etc/haproxy/haproxy.cfg
sed -n '/^defaults/,/^frontend/p' /etc/haproxy/haproxy.cfg
sudo haproxy -c -f /etc/haproxy/haproxy.cfg && sudo systemctl reload haproxyExpected:
defaults
mode http
log global
option httplog
timeout connect 2s
timeout client 30s
timeout server 30s
retries 2
option redispatch
frontend web
retries 2: two more attempts after a failed connection
setup. option redispatch: the last attempt may go to a
different server. The same failure once more:
# on s1
(ZIEL=http://localhost RATE=800 DAUER=40s k6 run --quiet mix.js > k6-drop-rd.txt 2>&1 &)
sleep 8; ssh s2 "sudo iptables -I INPUT -p tcp --dport 8080 -j DROP"
sleep 20; ssh s2 "sudo iptables -D INPUT -p tcp --dport 8080 -j DROP"
sleep 14
grep -E 'http_req_duration\.|http_req_failed\.|http_reqs\.' k6-drop-rd.txt | sed 's/ */ /g'Expected:
http_req_duration..............: avg=29.16ms min=962.67µs med=3.01ms max=26.76s p(90)=25.05ms p(95)=35.51ms
http_req_failed................: 0.00% 0 out of 31959
http_reqs......................: 31959 798.909572/s
0 errors, although a machine was dead for 20
seconds. One blemish remains: max 26.8 s. Requests that had
already reached s2 when the network went down hang until s2 is back.
HAProxy only retries connection setups, not requests already sent,
because it does not know whether s2 processed them. How long to wait for
them is controlled by timeout server. That is the topic of
Day 13.
Save your progress? Sign up for free
Drill 4: Restart during deploy
The most common “failure” is planned: a restart for a new version. Three times in a row, in two runs:
# on s1
for run in 1 2; do
(ZIEL=http://localhost RATE=800 DAUER=20s k6 run --quiet mix.js > k6-restart$run.txt 2>&1 &)
sleep 6
for i in 1 2 3; do ssh s2 "sudo systemctl restart kurz"; sleep 3; done
sleep 8
echo "== Lauf $run"
grep -E 'http_req_failed\.|http_reqs\.' k6-restart$run.txt | sed 's/ */ /g'
doneExpected:
== Lauf 1
http_req_failed................: 0.00% 1 out of 15908
http_reqs......................: 15908 795.284962/s
== Lauf 2
http_req_failed................: 0.00% 1 out of 16001
http_reqs......................: 16001 799.904553/s
One error per three restarts each. Little, but not zero, and with ten
deploys a day it adds up. kurz exits immediately on
SIGTERM: http.ListenAndServe knows no graceful shutdown, so
in-flight requests abort.
Save your progress? Sign up for free
Drill 5: Graceful shutdown
Go comes with the tool: http.Server.Shutdown stops
accepting new connections and waits until the in-flight requests are
answered. A new file server.go takes over starting the
server; in main.go, one call replaces the last three
lines:
# on s1
cd ~/kurz
cat > server.go <<'EOF'
package main
import (
"context"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
)
// serve beantwortet Anfragen, bis SIGTERM kommt (systemctl stop/restart),
// und beantwortet dann die laufenden Anfragen noch fertig.
func serve(handler http.Handler) {
srv := &http.Server{Addr: env("KURZ_ADDR", ":8080"), Handler: handler}
go func() {
log.Printf("%s lauscht auf %s", instanz, srv.Addr)
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatal(err)
}
}()
stop := make(chan os.Signal, 1)
signal.Notify(stop, syscall.SIGTERM, syscall.SIGINT)
<-stop
log.Printf("%s fährt herunter", instanz)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
log.Printf("Shutdown: %v", err)
}
db.Close()
}
EOF
perl -0pi -e 's/\taddr := env.*?ListenAndServe\(addr, handler\)\)\n/\tserve(handler)\n/s' main.go
tail -3 main.go
go vet . && go build -o kurz .
sudo install kurz /usr/local/bin/kurz && sudo systemctl restart kurz
scp -q kurz s2:/tmp/kurz && ssh s2 "sudo install /tmp/kurz /usr/local/bin/kurz && sudo systemctl restart kurz"Expected:
})
serve(handler)
}
The same test, this time in three runs:
# on s1
cd ~/sd/tag04
for run in 1 2 3; do
(ZIEL=http://localhost RATE=800 DAUER=20s k6 run --quiet mix.js > k6-v2-$run.txt 2>&1 &)
sleep 6
for i in 1 2 3; do ssh s2 "sudo systemctl restart kurz"; sleep 3; done
sleep 8
echo "== Lauf $run"; grep -E 'http_req_failed\.' k6-v2-$run.txt | sed 's/ */ /g'
done
ssh s2 "journalctl -u kurz --since -2min --no-pager | grep -c herunter"Expected (combined from two series of measurements):
== Lauf 1
http_req_failed................: 0.00% 1 out of 15951
== Lauf 2
http_req_failed................: 0.00% 1 out of 15952
== Lauf 3
http_req_failed................: 0.00% 0 out of 15990
Honest result: barely better. The app now shuts down gracefully (the
journal shows fährt herunter (“shutting down”)), but
HAProxy knows nothing about it. It keeps connections to s2 open to reuse
them, and occasionally sends a request exactly at the moment s2 closes
an idle connection. Graceful shutdown is necessary, but only half the
solution.
Save your progress? Sign up for free
Drill 6: Deregister first, then restart
The other half: tell HAProxy beforehand that s2 is about to go away.
In the drain state, a server gets no new requests, and the
in-flight ones run to completion:
# on s1
for run in 1 2; do
(ZIEL=http://localhost RATE=800 DAUER=24s k6 run --quiet mix.js > k6-drain$run.txt 2>&1 &)
sleep 4
for i in 1 2 3; do
echo "set server kurz/s2 state drain" | sudo nc -U /run/haproxy/admin.sock >/dev/null
sleep 2
ssh s2 "sudo systemctl restart kurz"
sleep 1
echo "set server kurz/s2 state ready" | sudo nc -U /run/haproxy/admin.sock >/dev/null
sleep 2
done
sleep 8
echo "== Lauf $run"; grep -E 'http_req_failed\.|http_reqs\.' k6-drain$run.txt | sed 's/ */ /g'
doneExpected:
== Lauf 1
http_req_failed................: 0.00% 0 out of 19148
http_reqs......................: 19148 797.594239/s
== Lauf 2
http_req_failed................: 0.00% 0 out of 19155
http_reqs......................: 19155 798.024991/s
0 errors in six restarts. That is the pattern for every deploy: deregister, wait until the in-flight requests are done, restart, check, register. A deploy tool does exactly that, server by server.
Save your progress? Sign up for free
Drill 7: When everyone is sick at once
And what if the database goes away?
# on s1
(ZIEL=http://localhost RATE=200 DAUER=40s k6 run --quiet mix.js > k6-pg.txt 2>&1 &)
sleep 5
ssh s3 "sudo systemctl stop postgresql@18-main"
for i in $(seq 1 8); do
echo "$(date +%T) $(echo 'show stat' | sudo nc -U /run/haproxy/admin.sock | cut -d, -f2,18 \
| sed -n 3,4p | tr '\n' ' ')"
sleep 1.5
done
curl -s http://localhost/MPKfz5D | head -3
ssh s3 "sudo systemctl start postgresql@18-main"
sleep 15
grep -E 'http_req_failed\.|http_reqs\.' k6-pg.txt | sed 's/ */ /g'Expected (abridged):
20:52:35 s1,UP s2,UP 2/3
20:52:38 s1,UP 2/3 s2,UP 1/3
20:52:39 s1,UP 1/3 s2,DOWN
20:52:41 s1,DOWN s2,DOWN
<html><body><h1>503 Service Unavailable</h1>
No server is available to handle this request.
</body></html>
http_req_failed................: 45.00% 3601 out of 8001
http_reqs......................: 8001 200.002041/s
Nine seconds after the stop, both instances are out, and HAProxy
answers with 503 itself. That is correct here: without a database,
kurz can neither create nor redirect. Two seconds after
PostgreSQL starts, both are back (rise 2). But remember the
trap: a health check that checks a shared dependency takes
all instances out at once when that dependency fails.
From Day 5 on, kurz can also answer many redirects from the
cache. Then this health check would be too strict (challenge of Day
6).
Save your progress? Sign up for free
Exercise: Speed drills
- Take s2 out of traffic via the admin socket and bring it back. Target time: 1 min
- Show how often systemd has already restarted
kurzon s2. Target time: 30 s - Show how long HAProxy needs in the worst case to detect a dead server. Target time: 1 min
Solution
# on s1
echo "set server kurz/s2 state drain" | sudo nc -U /run/haproxy/admin.sock
echo "set server kurz/s2 state ready" | sudo nc -U /run/haproxy/admin.sock
ssh s2 systemctl show kurz -p NRestarts
grep -E 'inter|timeout connect' /etc/haproxy/haproxy.cfgfall 3 times (inter 2s +
timeout connect 2s) gives about 12 seconds; in the lab it
was 15.
Save your progress? Sign up for free
Checkpoint
# on s1
grep -cE '^ (retries 2|option redispatch)$' /etc/haproxy/haproxy.cfgExpected: 2
# on s1
ls ~/kurz/server.go && echo "show stat" | sudo nc -U /run/haproxy/admin.sock | cut -d, -f2,18 \
| sed -n 3,4pExpected: server.go,
s1,UP, s2,UP
Challenge
Write the commands for deploying a new version to both instances, one after the other and without errors. How do you know that an instance is really ready after the restart, before you register it again?
Hint: The health check queries /readyz.
So can you.
Solution
The loop also goes to s1 itself via SSH. For this, s1 must know its own key:
# on s1
grep -qf ~/.ssh/id_ed25519.pub ~/.ssh/authorized_keys || cat ~/.ssh/id_ed25519.pub >> ~/.ssh/authorized_keys
ssh -o StrictHostKeyChecking=accept-new s1 hostnameExpected:
Warning: Permanently added 's1' (ED25519) to the list of known hosts.
s1
# on s1
for s in s1 s2; do
echo "set server kurz/$s state drain" | sudo nc -U /run/haproxy/admin.sock >/dev/null
sleep 2
scp -q ~/kurz/kurz $s:/tmp/kurz
ssh $s "sudo install /tmp/kurz /usr/local/bin/kurz && sudo systemctl restart kurz"
until curl -sf http://$s:8080/readyz >/dev/null; do sleep 0.5; done
echo "set server kurz/$s state ready" | sudo nc -U /run/haproxy/admin.sock >/dev/null
echo "$s fertig"
doneExpected:
s1 fertig
s2 fertig
/readyz only answers once the instance is listening
and reaches the database. Only then does it get traffic
again.
Save your progress? Sign up for free
Clean-up
# on s1
rm -f ~/sd/tag04/k6-*.txtThe firewall rules on s2 have been removed; retries and
redispatch stay, and so does server.go.
Interview note
- How does a load balancer detect a dead server? Actively via health checks (interval × number of failures) and passively via failed requests. A server that gives no answer at all is harder to detect than one that refuses connections.
- How do you deploy without errors? Deregister the server (drain), wait for in-flight requests, restart, check readiness, register again. The app must shut down gracefully on SIGTERM.
- Why doesn’t the load balancer simply retry every failed
request? Because a request that was already sent may have been
processed. A duplicate
POSTcreates two links. Only idempotent requests can be retried safely (Day 11).
Enterprise note
- Kubernetes does Drill 6 by itself: a Pod in
Terminatingdisappears from the endpoints, the container gets SIGTERM, and apreStophook bridges the time until all load balancers have noticed. The gap from Drill 5 exists there just the same. - Health checks usually come in two kinds: liveness (is the process alive? otherwise restart) and readiness (can it answer requests? otherwise no traffic). Dependencies belong at most in readiness, never in liveness; otherwise a database outage restarts all instances in a loop.