Appendix B: Final exam
Goal: You solve ten tasks spanning the whole book in 120 minutes: find and fix faults, measure, estimate. Each task with cause and proof, then you grade yourself · Duration: 120 min · Prerequisite: Days 0–16
Rules of the game
- Time: 120 minutes, set a clock. Each task counts 10%.
- There is no certificate. Your own bar: from 70% on, you can design, operate and justify a system.
- An examiner (a colleague, or you yourself without looking) runs the task’s preparation before each task, if it has one. The task only describes the symptom or the assignment.
- Allowed:
--help, the official documentation of HAProxy, PostgreSQL, PgBouncer, Valkey, NATS and k6, and your files under~/sd. Not allowed: this course during the exam. - A task only counts with the cause in one sentence and a proof command. Anyone who switches off a building block instead of repairing it (removing the health check, flushing the cache, taking out load shedding) gets 0%.
- All commands run on s1 unless stated otherwise.
- The solutions are at the end. Read them only after time is up.
Preparation
Once before the first task:
# on s1
mkdir -p ~/sd/pruefung && cd ~/sd/pruefung
cp ~/sd/tag15/anlegen.js ~/sd/tag15/klick.js ~/sd/tag15/codes.txt ~/sd/tag16/wettkampf.js .
export PGPASSWORD=lab-kurz-123Task 1: Nothing works anymore (10%)
Examiner:
# on s1
sudo sed -i 's#option httpchk GET /readyz#option httpchk GET /ready#' /etc/haproxy/haproxy.cfg
sudo systemctl reload haproxy
clearEvery request to http://s1/ gets 503. Both
kurz instances are running,
curl s2:8080/readyz responds with 200. Bring the service
back.
Task 2: The old target (10%)
Examiner:
# on s1
cd ~/sd/pruefung
curl -s -X POST -H 'Content-Type: application/json' -d '{"url":"https://example.org/pruefung/alt"}' localhost/api/links > neu.json
C=$(jq -r .code neu.json); curl -s -o /dev/null localhost/$C
psql -h s3 -U kurz -d kurz -qc "update links set url = 'https://example.org/pruefung/neu' where code = '$C'"
clearSupport changed the target for the code in
~/sd/pruefung/neu.json directly in the database. The
redirect still points to the old target. Make sure it delivers the new
target immediately, without touching the rest of the
cache. Explain why this happens.
Task 3: After the load spike (10%)
Examiner:
# on s1
ssh s3 "sudo sed -i 's/^pool_mode = transaction/pool_mode = session/' /etc/pgbouncer/pgbouncer.ini && sudo systemctl restart pgbouncer"
clearA customer creates links in bursts of 600 per second
(anlegen.js with RATE=600). Since yesterday,
almost every fifth request fails with 503; before, it was under 1%.
Nobody changed anything on kurz.
Task 4: The growing lag (10%)
Examiner:
# on s1
ssh s2 "sudo -u postgres psql -tAc 'select pg_wal_replay_pause()'" >/dev/null
k6 run -q -e RATE=100 -e DAUER=10s ~/sd/pruefung/anlegen.js >/dev/null 2>&1
clearMonitoring reports: the replica’s replay_lag has been
growing for minutes, write_lag and flush_lag
are at a few milliseconds. Users notice nothing. What is going on, why
does nobody notice, and how do you fix it?
Task 5: Short codes (10%)
Examiner:
# on s2
printf '[Service]\nEnvironment=KURZ_CODELAENGE=2\n' | sudo tee /etc/systemd/system/kurz.service.d/kurz-codes.conf >/dev/null
sudo systemctl daemon-reload && sudo systemctl restart kurz
clearA customer is puzzled: some new links have only two characters, and every now and then creating one fails. Find the cause, fix it, and say what happens to the short codes already handed out.
Task 6: Lost clicks (10%)
Examiner:
# on s1
nats stream edit KLICKS --max-msgs=1000 -f >/dev/null
clearThe counter is to be taken down for maintenance for one minute tomorrow. A colleague fears that clicks will be lost. Check it with a measurement: stop the counter on s2, 500 clicks per second for 10 seconds, start the counter, compare the counted clicks. Fix what you find and measure again.
Task 7: Rejected by one instance (10%)
Examiner:
# on s2
printf '[Service]\nEnvironment=KURZ_TIMEOUT=10ms\n' | sudo tee /etc/systemd/system/kurz.service.d/schnell.conf >/dev/null
sudo systemctl daemon-reload && sudo systemctl restart kurz
clearwettkampf.js reports about 15% errors when creating
links, and a few hundred on redirects. Find out which instance produces
the errors and why.
Task 8: Thirty days of clicks (10%)
No preparation. Sales would like to keep the clicks in the stream for 30 days instead of 24 hours, at 100 million redirects per day. Does that fit on s2? How many days fit? Calculate with values you measure in the lab now.
Task 9: How many at once? (10%)
No preparation. How many requests are in progress at the same time on
average during wettkampf.js? Predict it with Little’s Law
from the k6 output and verify it at HAProxy during the load. Explain the
difference.
Task 10: Waiting instead of rejection (10%)
Examiner:
# on s1
sudo sed -i 's/timeout queue 20ms/timeout queue 5s/' /etc/haproxy/haproxy.cfg
sudo systemctl reload haproxy
clearUnder overload (anlegen.js with RATE=2400,
without a key), users wait one and a half seconds on average, and k6
does not even manage half of the planned requests. In the past, overload
quickly produced a rejection. Restore the old behavior and prove it.
Solutions
Solution 1
# on s1
curl -s localhost/abc
echo "show stat" | sudo socat stdio /run/haproxy/admin.sock | awk -F, '$1 == "kurz" {print $2, $18, $37, $38}'
curl -s -o /dev/null -w '%{http_code}\n' s2:8080/ready
grep -n httpchk /etc/haproxy/haproxy.cfgExpected:
<html><body><h1>503 Service Unavailable</h1>
No server is available to handle this request.
</body></html>
s1 DOWN L7STS 404
s2 DOWN L7STS 404
BACKEND DOWN
404
29: option httpchk GET /ready
Cause: The health check requests /ready
instead of /readyz, both instances respond with 404 and are
considered DOWN (L7STS: wrong status at layer 7, Day
3).
# on s1
sudo sed -i 's#option httpchk GET /ready$#option httpchk GET /readyz#' /etc/haproxy/haproxy.cfg
sudo haproxy -c -f /etc/haproxy/haproxy.cfg && sudo systemctl reload haproxy
sleep 6
echo "show stat" | sudo socat stdio /run/haproxy/admin.sock | awk -F, '$1 == "kurz" {print $2, $18, $37, $38}'
curl -s -o /dev/null -w '%{http_code}\n' localhost/$(head -1 ~/sd/pruefung/codes.txt)Expected:
s1 UP L7OK 200
s2 UP L7OK 200
BACKEND UP
302
After the reload it takes two successful checks (rise 2,
every 2 seconds), hence the pause.
Solution 2
# on s1
cd ~/sd/pruefung
C=$(jq -r .code neu.json)
curl -s -o /dev/null -w '%{redirect_url}\n' localhost/$C
psql -h s3 -U kurz -d kurz -tAc "select url from links where code = '$C'"
V="valkey-cli -h s3 -a lab-valkey-123 --no-auth-warning"
$V get link:$C
$V ttl link:$CExpected:
https://example.org/pruefung/alt
https://example.org/pruefung/neu
https://example.org/pruefung/alt
637
Cause: Cache-aside (Day 5): kurz reads
from Valkey first. Changing the database directly leaves the old entry
in place for up to 10 minutes, here another 637 seconds. Delete exactly
this one key, and the next request reloads it:
# on s1
$V del link:$C
curl -s -o /dev/null -w '%{redirect_url}\n' localhost/$CExpected:
1
https://example.org/pruefung/neu
In the code, deleting the key belongs in the same function as the
change in the database. kurz has no update function; it is
listed under “Non-goals” on Day 15.
Solution 3
# on s1
cd ~/sd/pruefung
k6 run -q -e RATE=600 -e DAUER=20s anlegen.js 2>&1 | grep -E '✗ 201|✗ 503|↳|http_req_duration\.' | grep -v '0% — ✓ 0 /'
psql -h s3 -p 6432 -U kurz pgbouncer -c 'show pools' | cut -d'|' -f1-4,7 | head -3
ssh s3 "sudo grep -E '^(pool_mode|default_pool_size)' /etc/pgbouncer/pgbouncer.ini"Expected:
✗ 201
↳ 80% — ✓ 9713 / ✗ 2288
✗ 503
↳ 19% — ✓ 2288 / ✗ 9713
http_req_duration..............: avg=10.83ms min=855.84µs med=6.87ms max=2.05s p(90)=15.41ms p(95)=20.17ms
database | user | cl_active | cl_waiting | sv_active
-----------+-----------+-----------+------------+-----------
kurz | kurz | 20 | 13 | 20
pool_mode = session
default_pool_size = 20
Cause: PgBouncer is running in session mode. Each
client connection holds a server connection until it is closed. Under
load, the two kurz pools want 16 connections each, so 32,
and the pool has 20. 13 clients wait, and requests on those connections
run into the 2-second timeout (max=2.05s). In transaction
mode (Day 7), all clients share the 20 server connections transaction by
transaction:
# on s1
ssh s3 "sudo sed -i 's/^pool_mode = session/pool_mode = transaction/' /etc/pgbouncer/pgbouncer.ini && sudo systemctl restart pgbouncer"
sleep 2
k6 run -q -e RATE=600 -e DAUER=20s anlegen.js 2>&1 | grep -E '✗ 201|✗ 503|↳|http_req_duration\.' | grep -v '0% — ✓ 0 /'Expected:
✗ 201
↳ 99% — ✓ 11966 / ✗ 34
✗ 503
↳ 0% — ✓ 34 / ✗ 11966
http_req_duration..............: avg=10.26ms min=2.91ms med=8.42ms max=153.5ms p(90)=16.12ms p(95)=20.27ms
The remaining 34 are the load shedding from Day 12 during spikes, 0.3%. The first run right after the restart may show a few more, because all pools reconnect.
Solution 4
# on s1
ssh s3 "sudo -u postgres psql -c 'select client_addr, state, write_lag, flush_lag, replay_lag, pg_size_pretty(pg_wal_lsn_diff(sent_lsn, replay_lsn)) as rueckstand from pg_stat_replication'"
ssh s2 "sudo -u postgres psql -c 'select pg_get_wal_replay_pause_state(), now() - pg_last_xact_replay_timestamp() as alter'"Expected:
client_addr | state | write_lag | flush_lag | replay_lag | rueckstand
--------------+-----------+-----------------+-----------------+-----------------+------------
172.16.0.228 | streaming | 00:00:00.001947 | 00:00:00.009351 | 00:00:10.003899 | 617 kB
(1 row)
pg_get_wal_replay_pause_state | alter
-------------------------------+-----------------
paused | 00:00:26.340942
(1 row)
Cause: The replica receives and stores the WAL
(write_lag, flush_lag small) but does not
replay it: recovery is paused. Users notice nothing because
kurz asks the primary for a code the replica does not know
(Day 8), and popular links come from the cache. The number that gives it
away is the age of the last replayed transaction.
# on s1
ssh s2 "sudo -u postgres psql -tAc 'select pg_wal_replay_resume()'"
sleep 2
ssh s3 "sudo -u postgres psql -c 'select client_addr, state, replay_lag, pg_size_pretty(pg_wal_lsn_diff(sent_lsn, replay_lsn)) as rueckstand from pg_stat_replication'"Expected:
client_addr | state | replay_lag | rueckstand
--------------+-----------+-----------------+------------
172.16.0.228 | streaming | 00:00:00.002411 | 0 bytes
(1 row)
The empty first line is the response of
pg_wal_replay_resume(), which returns nothing.
Solution 5
# on s1
for i in 1 2 3 4; do curl -si -X POST -H 'Content-Type: application/json' -d "{\"url\":\"https://example.org/pruefung/c-$i-$RANDOM\"}" localhost/api/links | grep -iE '^x-kurz-instanz|code' | tr -d '\r' | paste -sd' '; done
ssh s2 "grep -H CODELAENGE /etc/systemd/system/kurz.service.d/*.conf"Expected (your order will differ):
x-kurz-instanz: s1 {"code":"SXxZYz6","url":"https://example.org/pruefung/c-1-2624"}
x-kurz-instanz: s2 {"code":"Mx","url":"https://example.org/pruefung/c-2-28986"}
x-kurz-instanz: s2 {"code":"jf","url":"https://example.org/pruefung/c-3-4773"}
x-kurz-instanz: s1 {"code":"Cmh45Jd","url":"https://example.org/pruefung/c-4-16931"}
/etc/systemd/system/kurz.service.d/kurz-codes.conf:Environment=KURZ_CODELAENGE=2
Cause: s2 hands out codes with two characters. That
is only 57² = 3249 possible codes. The fuller the space, the more often
a new code hits one already taken, and after three attempts in
anlegen.go you get kein freier Code (no free
code) (Day 9, birthday paradox).
# on s1
ssh s2 "sudo rm /etc/systemd/system/kurz.service.d/kurz-codes.conf && sudo systemctl daemon-reload && sudo systemctl restart kurz"
sleep 2
curl -s -X POST -H 'Content-Type: application/json' -d "{\"url\":\"https://example.org/pruefung/nachher-$RANDOM\"}" s2:8080/api/links; echo
psql -h s3 -U kurz -d kurz -c "select length(code) as laenge, count(*) from links where angelegt > now() - interval '1 hour' group by 1 order by 1"Expected (your numbers will differ):
{"code":"K4DSj58","url":"https://example.org/pruefung/nachher-25996"}
laenge | count
--------+-------
2 | 4
7 | 43956
(2 rows)
The short codes already handed out stay. Customers have shared them, and they work. A code is a promise you do not take back.
Solution 6
# on s1
cd ~/sd/pruefung
ssh s2 "sudo systemctl stop zaehler"
vor=$(psql -h s3 -U kurz -d kurz -tAc "select sum(anzahl) from klicks")
k6 run -q -e RATE=500 -e DAUER=10s klick.js 2>&1 | grep -E 'http_reqs\.'
ssh s2 "sudo systemctl start zaehler"
sleep 5
nach=$(psql -h s3 -U kurz -d kurz -tAc "select sum(anzahl) from klicks")
echo "gezählt: $((nach - vor))"
nats stream info KLICKS | grep -E 'Maximum Messages|Maximum Age|Discard'Expected:
http_reqs......................: 5001 499.971105/s
gezählt: 1000
Discard Policy: Old
Maximum Messages: 1,000
Maximum Age: 1d0h0m0s
Cause: The stream holds at most 1000 messages and
throws away the oldest on overflow (Discard Policy: Old).
As long as the counter is running, nobody notices. As soon as it stops,
all clicks except the last 1000 are lost (Day 10). The limit belongs on
time (24 hours), not on count:
# on s1
nats stream edit KLICKS --max-msgs=-1 -f >/dev/null
nats stream info KLICKS | grep 'Maximum Messages'
ssh s2 "sudo systemctl stop zaehler"
vor=$(psql -h s3 -U kurz -d kurz -tAc "select sum(anzahl) from klicks")
k6 run -q -e RATE=500 -e DAUER=10s klick.js 2>&1 | grep -E 'http_reqs\.'
ssh s2 "sudo systemctl start zaehler"
sleep 5
nach=$(psql -h s3 -U kurz -d kurz -tAc "select sum(anzahl) from klicks")
echo "gezählt: $((nach - vor))"Expected:
Maximum Messages: unlimited
http_reqs......................: 5001 499.947586/s
gezählt: 5001
Solution 7
# on s1
cd ~/sd/pruefung
k6 run -q wettkampf.js 2>&1 | grep -E 'checks_failed|✗|↳|http_req_duration\.'
sudo tail -40000 /var/log/haproxy.log | awk '$9 >= 500 {print $7, $9}' | sort | uniq -cExpected:
checks_failed......: 0.55% 201 out of 36468
✗ klick 302
↳ 99% — ✓ 35756 / ✗ 111
✗ anlegen 201
↳ 85% — ✓ 511 / ✗ 90
http_req_duration..............: avg=5.76ms min=890.62µs med=3.45ms max=193.94ms p(90)=10.91ms p(95)=16.43ms
12 kurz/<NOSRV> 503
189 kurz/s2 503
Field 7 in the log is backend and server: almost all 503s come from s2. What does s2 itself say?
# on s1
ssh s2 "journalctl -u kurz --since -2min --no-pager | cut -d' ' -f7- | sed 's/[0-9]\{2\}:[0-9:]*//' | sort | uniq -c | sort -rn | head -3"
ssh s2 "grep -H TIMEOUT /etc/systemd/system/kurz.service.d/*.conf"Expected:
99 weiterleiten: context deadline exceeded
92 cache get: context deadline exceeded
18 anlegen: context deadline exceeded
/etc/systemd/system/kurz.service.d/schnell.conf:Environment=KURZ_TIMEOUT=10ms
Cause: s2 gives each request only 10 ms instead of 2
seconds (Day 13). Creating a link, with the dedupe lookup and the write,
often takes longer; redirects only when the cache happens to respond
slowly. The 12 <NOSRV> are load shedding, while s2
holds slots longer because of the errors.
# on s1
ssh s2 "sudo rm /etc/systemd/system/kurz.service.d/schnell.conf && sudo systemctl daemon-reload && sudo systemctl restart kurz"
sleep 3
k6 run -q wettkampf.js 2>&1 | grep -E 'checks_failed|✗|↳|http_req_duration\.'Expected:
checks_failed......: 0.00% 0 out of 36599
http_req_duration..............: avg=4.77ms min=858.38µs med=3.34ms max=146.46ms p(90)=8.85ms p(95)=12.23ms
Solution 8
# on s1
nats stream info KLICKS --json | jq '.state.bytes / .state.messages | floor'
ssh s2 "df -h / | tail -1"
awk 'BEGIN { b = 43; t = 100e6 * b; printf "pro Tag: %.1f GB\n", t/1e9; printf "30 Tage: %.0f GB\n", 30*t/1e9; printf "passt: %.1f Tage auf 24 GB\n", 24e9/t }'Expected:
43
/dev/sda1 29G 4.8G 24G 17% /
pro Tag: 4.3 GB
30 Tage: 129 GB
passt: 5.6 Tage auf 24 GB
Answer: No. 30 days need 129 GB, s2 has 24 GB free, and the PostgreSQL replica lives off that too. Even without the replica, at most 5 days fit. A better answer than a bigger disk: after counting, the clicks are in PostgreSQL anyway. Anyone who needs 30 days of individual clicks writes them aggregated (per code and hour) into a separate table, and the stream stays at 24 hours as a buffer (Day 10 and 15).
Solution 9
# on s1
cd ~/sd/pruefung
k6 run -q wettkampf.js > last.log 2>&1 &
sleep 5
for i in $(seq 40); do echo "show stat" | sudo socat stdio /run/haproxy/admin.sock | awk -F, '$1 == "kurz" && $2 == "BACKEND" {print $5}'; sleep 0.5; done | awk '{s += $1; n++} END {printf "%d Proben, im Mittel %.1f gleichzeitig\n", n, s/n}'
wait
grep -E 'http_req_duration\.|http_reqs\.' last.logExpected:
40 Proben, im Mittel 4.9 gleichzeitig
http_req_duration..............: avg=5.07ms min=897.25µs med=3.51ms max=90.26ms p(90)=9.68ms p(95)=13.3ms
http_reqs......................: 36566 1218.581841/s
Answer: Little’s Law (Day 2): L = λ × W = 1218.6/s ×
0.00507 s ≈ 6.2 concurrent requests. HAProxy counts 4.9 open connections
to the servers on average (scur, field 5). The difference
is the time that k6 measures but HAProxy does not attribute to the
servers: the path from k6 to HAProxy, evaluating quota and rules, and
the responses HAProxy gives itself. 40 samples are also only a rough
estimate. For capacity this means: maxconn 16 per server is
three times enough at this load.
Solution 10
# on s1
cd ~/sd/pruefung
k6 run -q -e RATE=2400 -e DAUER=20s anlegen.js 2>&1 | grep -E '✗ 201|✗ 503|↳|http_req_duration\.|http_reqs\.|dropped' | grep -v '0% — ✓ 0 /'
grep -n 'timeout queue' /etc/haproxy/haproxy.cfgExpected:
✗ 201
↳ 99% — ✓ 22748 / ✗ 158
✗ 503
↳ 0% — ✓ 150 / ✗ 22756
http_req_duration..............: avg=1.4s min=0s med=1.53s max=2.76s p(90)=2.01s p(95)=2.56s
http_reqs......................: 22906 1054.31628/s
dropped_iterations.............: 25095 1155.071468/s
32: timeout queue 5s
Cause: The queue in HAProxy may wait 5 seconds
instead of 20 ms. Everything that does not immediately get one of the 32
slots waits instead of being rejected. The system works at its limit of
around 1050 per second (Day 12), every request waits one and a half
seconds, and k6 runs out of virtual users
(dropped_iterations). Load shedding means: better a fast no
than a slow yes.
# on s1
sudo sed -i 's/timeout queue 5s/timeout queue 20ms/' /etc/haproxy/haproxy.cfg
sudo haproxy -c -f /etc/haproxy/haproxy.cfg && sudo systemctl reload haproxy
sleep 5
k6 run -q -e RATE=2400 -e DAUER=20s anlegen.js 2>&1 | grep -E '✗ 201|✗ 503|↳|http_req_duration\.|http_reqs\.|dropped' | grep -v '0% — ✓ 0 /'Expected:
✗ 201
↳ 46% — ✓ 21216 / ✗ 24278
✗ 503
↳ 53% — ✓ 24278 / ✗ 21216
http_req_duration..............: avg=42.23ms min=6.11ms med=37.41ms max=218.59ms p(90)=68.97ms p(95)=82.7ms
http_reqs......................: 45494 2268.350061/s
dropped_iterations.............: 2496 124.451615/s
Almost as many links created as before (21,216 versus 22,748), but p95 at 83 ms instead of 2.6 seconds. Whoever is rejected learns it within milliseconds and can retry with backoff (Day 11).
Scoring
| Result | Rating |
|---|---|
| 90–100% | System architect: you design, measure and justify |
| 70–80% | Solid: the fundamentals are in place, and now you know your gaps |
| below 70% | Repeat the days covering the tasks you missed |
Clean-up
All solutions restore the target state. If you did not solve a task, run its solution commands anyway. Finally, compare with the state after Day 16:
# on s1
grep -nE 'httpchk|ge 1000|timeout queue' /etc/haproxy/haproxy.cfg
ssh s2 "ls /etc/systemd/system/kurz.service.d/; sudo -u postgres psql -tAc 'select pg_get_wal_replay_pause_state()'"
ssh s3 "sudo grep -E '^pool_mode' /etc/pgbouncer/pgbouncer.ini"
nats stream info KLICKS | grep 'Maximum Messages'Expected:
21: acl zu_viel sc_gpc_rate(0,0) ge 1000
29: option httpchk GET /readyz
32: timeout queue 20ms
cache.conf
cpu.conf
klicks.conf
lesen.conf
pool.conf
not paused
pool_mode = transaction
Maximum Messages: unlimited