Appendix A: Cheat sheet
The most important numbers, commands and traps from Day 0 to 16. The
days are in parentheses. Commands without a location run on s1. Replace
placeholders in angle brackets.
The path of a request
Redirect: k6 → HAProxy s1:80 (quota, load shedding, health check)
→ kurz s1/s2:8080 (timeout 2 s)
→ Valkey s3:6379 (cache-aside, TTL 10 min ± 20 %)
→ replica s2:5432 (300 ms) → primary via PgBouncer s3:6432
→ click to NATS s2:4222 → stream KLICKS → zaehler → PostgreSQL
Create: HAProxy → kurz → Idempotency-Key? → circuit breaker → dedupe lookup (url)
→ INSERT ... ON CONFLICT DO NOTHING (up to 3 codes)
Measuring (Day 1, 2, 15)
k6 run -q -e RATE=<n> -e DAUER=20s <skript>.js 2>&1 | grep -E 'http_req_duration\.|http_req_failed\.|http_reqs\.|dropped'
k6 run -q wettkampf.js 2>&1 | grep -E 'checks_failed|✗|↳|http_req_duration\.'
| Term |
Rule of thumb |
| p95 |
95% of requests were faster. Averages hide the slow ones |
open model (constant-arrival-rate) |
Load arrives whether or not the system keeps up, like real
users |
| closed model (VUs) |
waits for responses and makes itself look good under overload |
dropped_iterations |
k6 could not sustain the planned rate |
| Little’s Law |
concurrent = rate × duration, e.g. 1200/s × 5 ms ≈ 6 |
| Saturation |
from here on p95 rises steeply, throughput no longer does |
The load generator is often the bottleneck itself: k6 on s1 manages
around 3000 requests per second (Day 2). CPU per process during
load:
top -bn2 -d 3 -p "$(pgrep -d, -x haproxy),$(pgrep -d, -x kurz),$(pgrep -d, -x k6)" | awk '/^ *PID/ {n++} n==2 && $1 ~ /^[0-9]+$/ {print $9"% "$12}'
HAProxy (Day 3, 4, 12, 13)
backend kurz
balance leastconn
option httpchk GET /readyz
default-server inter 2s fall 3 rise 2 maxconn 16
timeout queue 20ms
retry-on conn-failure empty-response response-timeout
http-request disable-l7-retry if METH_POST
echo "show stat" | sudo socat stdio /run/haproxy/admin.sock | awk -F, '$1 == "kurz" {print $2, $18, $8, $44}' # Name, Status, Anfragen, 5xx
echo "clear counters all" | sudo socat stdio /run/haproxy/admin.sock
echo "set server kurz/s2 state drain" | sudo socat stdio /run/haproxy/admin.sock
echo "show table web" | sudo socat stdio /run/haproxy/admin.sock
sudo haproxy -c -f /etc/haproxy/haproxy.cfg && sudo systemctl reload haproxy
sudo tail -50000 /var/log/haproxy.log | awk '{print $7, $9}' | sort | uniq -c # Server, Status
Field in show stat |
Meaning |
5 scur |
currently open connections |
8 stot |
total requests |
18 status |
UP, DOWN, DRAIN |
37/38 check_status/check_code |
e.g. L7STS 404: health check gets the wrong status |
44 hrsp_5xx |
responses with 5xx |
leastconn instead of roundrobin as soon as
servers differ in speed (Day 3).
retries + redispatch rescue connection
errors, not hanging servers: for those use timeout server
and retry-on response-timeout (Day 4, 13). Never retry POST
automatically.
- Quota per key with
gpc_rate, only admitted requests
count (sc-inc-gpc after the 429 rule). Otherwise a customer
locks themselves out (Day 12).
- Load shedding:
maxconn per server plus a short
timeout queue. Better a fast 503 than a slow 201.
Cache with Valkey (Day 5, 6)
V="valkey-cli -h s3 -a lab-valkey-123 --no-auth-warning"
$V dbsize
$V info memory | grep -E '^used_memory_human|^maxmemory_human|^maxmemory_policy'
$V info stats | grep -E '^keyspace_(hits|misses)'
$V config resetstat
$V ttl link:<code>
$V del link:<code>
| Problem |
Countermeasure in kurz |
| cold start, many misses at once |
singleflight per code (Day 6) |
| all keys expire at the same time |
random TTL 80–120% (Day 6) |
| database overloaded, instance gets kicked out |
/readyz is ready if cache or database
responds (Day 6) |
| Valkey gone |
redirects from the database, slower (Day 6) |
| target changed in the database |
delete the key, otherwise up to 10 min stale (Appendix B) |
maxmemory reached |
allkeys-lru evicts old keys, noeviction
rejects every write |
PostgreSQL (Day 7, 8, 9, 14)
export PGPASSWORD=lab-kurz-123
psql -h s3 -U kurz -d kurz -c "explain (analyze, costs off) <abfrage>"
psql -h s3 -U kurz -d kurz -c '\di links*'
psql -h s3 -U kurz -d kurz -c "create index concurrently <name> on links (<spalte>)"
psql -h s3 -p 6432 -U kurz pgbouncer -c 'show pools'
ssh s3 "sudo -u postgres psql -c 'select client_addr, state, write_lag, flush_lag, replay_lag from pg_stat_replication'"
ssh s3 "sudo -u postgres psql -c 'select slot_name, active, pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn)) from pg_replication_slots'"
ssh s2 "sudo -u postgres psql -c 'select pg_get_wal_replay_pause_state(), now() - pg_last_xact_replay_timestamp()'"
- Connections are scarce (
max_connections). PgBouncer in
transaction mode spreads 20 server connections across
more than 100 clients. In session mode each client holds one (Day 7,
Appendix B).
- Reading from the replica means reading stale data: fresh links are
missing there for milliseconds to seconds.
kurz then asks
the primary (Day 8).
- A slot retains WAL until the replica is back. Hence
max_slot_wal_keep_size (Day 8).
synchronous_standby_names: no data loss on failover,
but writes hang when the replica is missing. The client sees an error,
yet the row is stored anyway (Day 14).
- Failover: stop the primary,
pg_promote() on the
replica, never simply start the old primary again,
otherwise you have two primaries (Day 14).
IDs and sharding (Day 9)
| Figure |
Value |
| Codes with 7 characters out of 57 |
57⁷ ≈ 1.95 trillion |
| Collision likely from |
about √N (birthday paradox) |
| Codes with 2 characters |
3249, noticeably full after just 1000 links |
| Shard of a code |
crc32(code) % n |
| Data moved when going from 2 to 3 shards |
modulo 66.7%, 64 fixed slots 32.8% |
NATS JetStream (Day 10, 11)
nats stream info KLICKS | grep -E 'Messages|Maximum|Discard'
nats consumer info KLICKS zaehler --json | jq '{num_pending, num_ack_pending, ack_floor: .ack_floor.stream_seq}'
nats stream edit KLICKS --max-msgs=-1 -f
nats pub --jetstream -H Nats-Msg-Id:<id> klicks <code>
- Core NATS without a subscriber: message gone. JetStream stores until
someone acknowledges.
- Durable consumer with
AckExplicit: the server remembers
how far it has been read.
- Batch instead of single message: batch 1 ≈ 280/s, batch 500 catches
up on 44,000 in 6 s (Day 10, Day 16).
- Counting exactly once = deliver at least once + dedupe at the
receiver (
klicks_verarbeitet in the same statement, Day
11).
- Limits by time (
max-age), not by count:
max-msgs with discard old loses data silently
as soon as the consumer stalls.
Reliability (Day 11, 12, 13)
| Pattern |
in kurz |
| Idempotency key |
middleware, table idempotenz, 422 on a different body,
Idempotent-Replayed |
| Retry with backoff |
full jitter: rand(0, basis × 2^versuch) (Day 11) |
| Dedupe without a key |
partial unique index on url +
ON CONFLICT DO NOTHING |
| Timeout per request |
KURZ_TIMEOUT 2 s, replica 300 ms |
| Circuit breaker |
5 server errors in a row → 5 s open → one probe |
| Quota |
1000 requests per 5 s per X-Api-Key, 429 +
Retry-After |
| Load shedding |
maxconn 16, timeout queue 20ms |
Cascade: a hanging dependency occupies slots in the load balancer,
and then the healthy requests get 503 too. Countermeasures in this
order: timeout, circuit breaker, separate quotas (Day 13).
Environment variables
| Variable |
Default |
Day |
KURZ_ADDR |
:8080 |
1 |
KURZ_INSTANZ |
kurz |
3 |
KURZ_DB |
postgres://kurz:…@s3:5432/kurz |
1, 7 |
KURZ_DB_LESEN |
empty = primary |
8 |
KURZ_CACHE, KURZ_CACHE_PASSWORT |
empty = no cache |
5 |
KURZ_CACHE_TTL |
600 (seconds) |
5 |
KURZ_SHARDS |
empty = 1 shard |
9 |
KURZ_CODELAENGE |
7 |
9 |
KURZ_KLICKS |
empty, sync or nats://… |
10 |
KURZ_VERZOEGERUNG |
0s |
11 |
KURZ_TIMEOUT, KURZ_TIMEOUT_LESEN |
2s, 300ms |
13 |
ZAEHLER_BATCH, ZAEHLER_PAUSE |
500, 0s |
10, 11 |
Drop-ins live under /etc/systemd/system/kurz.service.d/.
systemd reads them alphabetically; for the same setting, the last file
wins (Day 16):
grep -H <EINSTELLUNG> /etc/systemd/system/kurz.service.d/*.conf
systemctl show kurz -p CPUQuotaPerSecUSec
Estimating (Day 15)
| Quantity |
measured |
| Link in PostgreSQL including indexes |
194 bytes on average, 376 bytes for new ones |
| Entry in Valkey |
108 bytes |
| Click in the stream |
43 bytes |
Redirects per core (kurz) |
1500/s |
| HAProxy for 1500/s |
64% of a core |
| Creating, overall |
around 1050/s |
100 M/day ≈ 1157/s on average, × 3 = 3472/s peak (one day ≈ 100 000 s)
Storage = count × size × retention
Cores = peak ÷ capacity per core, then N+1
The traps from the book
| Trap |
Day |
| A pool with 4 connections limits throughput to 4 ÷ duration |
2 |
| k6 and the app on the same machine share the CPU |
2, 3 |
roundrobin keeps sending a slow server its share |
3 |
| Retry repeats nothing when the server hangs instead of
rejecting |
4 |
readyz with a shared context for cache and
database |
6 |
More connections per instance × instances >
max_connections |
7 |
| Reading from the replica does not find fresh links |
8 |
| Treating a lookup error as “not present” → duplicate links |
9, 11 |
| Transaction + second connection from the same pool → deadlock |
11 |
| Quota counts rejected requests too |
12 |
/usr/bin/pg_isready fails under keepalived, use the
versioned path |
14 |
| Old primary takes the VIP back → two primaries |
14 |
| Average over old data underestimates the storage of new data |
15 |
| A fallback masks a second failure |
16 |