CapstoneVol. 19 · Part XIX
0 / 0

Trails / Capstone

CP·212A

Failure Exercises I: Dependencies, Resources and Capacity

The first ten of the capstone's twenty failure exercises, run against TiffinBox: database outage, cache outage, Kafka outage, slow dependency, CPU saturation, memory leak, disk pressure, pod crash, region loss and a traffic spike; how to run a failure exercise safely, and for each incident how to detect, mitigate, recover and prevent; with a lab that actually stops PostgreSQL and Redis under load, pushes a service past its capacity, sheds load, kills a worker mid-request, leaks memory into an OOM kill and fills a disk.

28 topics · ~14 min read · 16-question quiz
Updated Suggest a correction

Start here: don't stop at "it works"

The roadmap's instruction for the capstone is blunt: do not stop at "it works." A system that works on a good day tells you little. What matters is what happens on a bad one: the database restarts during the lunch peak, a dependency hangs, a pod runs out of memory. For each failure the roadmap asks four questions:

Text
How do we detect it?    → telemetry and alerts tell us before customers do
How do we mitigate it?  → stop the damage now, even crudely
How do we recover?      → return to normal, including data
How do we prevent recurrence? → change the design, tests or process

What breaking things taught, measured

The lab ran a slice of TiffinBox (nginx → a Python API → PostgreSQL and Redis) and broke it on purpose:

Exercise What happened The lesson
PostgreSQL stopped for ~10 s at 100 req/s every request waited ~6 s then failed; after recovery a backlog took ~5 s to drain without a fail-fast timeout, an outage becomes a queue
Redis stopped for 10 s at 200 req/s, with a "fallback" to the database 1,424 of 6,000 failed: the client library retried for 4.4 s per request, the proxy ran out of connections a fallback is useless if reaching it takes 4 s
same, with retries off 0 of 6,000 failed
2,500 req/s against a service that tops out near 1,600 p99 3.3 s and the load generator couldn't even send a third of the requests
same, with load shedding p99 of successful requests 119 ms; the rest got an instant 503 refuse some work quickly rather than all work slowly
one of two workers killed with kill -9 GET requests: 0 failures (the proxy retried); POST requests: 20 failures proxies only retry what's safe to retry
memory leak inside a 200 MB limit killed after ~9.5 s, no error message, no last log line OOM kills are silent; watch the trend
disk filled by logs and data together after half the space went to logs, every new order failed logs can take down the database

How deep to go

Volume 17 defines six mastery levels. For failure exercises:

Level What you can do
L1 List the failures and what each threatens
L2 Run a scripted exercise in staging and record what happens
L3 Explain each outcome from first principles (pools, retries, queues, kernel behaviour)
L4 Find the hidden cause of a surprising outcome (client defaults, proxy limits) and fix it
L5 Design the system so each failure degrades gracefully, and prove it
L6 Run game days in production with confidence; on-call that handles the unexpected

Volume 11, chapter 120 (chaos testing), Volume 9, chapter 103 (incidents) and Volume 16 (readiness and recovery) teach the method.

Running a failure exercise

  1. State a hypothesis: "If Redis is down for 60 s, menu pages stay available with p95 < 500 ms."
  2. Limit the blast radius: staging first; in production, one zone, a small traffic slice, or a time of low traffic; a named person with authority to stop.
  3. Define abort conditions: "stop if the order-API error rate exceeds 1% for 2 minutes."
  4. Observe through normal telemetry: if you need special tools to see what happened, your monitoring has a gap, which is itself a finding.
  5. Inject, watch, and restore.
  6. Write it up with the four answers (detect, mitigate, recover, prevent), the timeline, and actions with owners.
  7. Automate the ones that pass, so they keep passing (a weekly chaos job in staging).

The ten exercises

1. Database outage

What happens: every request needing PostgreSQL fails. The lab showed how: with the pool's default 30 s wait, requests hung until the client gave up (~6 s), and after the database returned, the accumulated backlog took ~5 s to drain; with a 0.5 s pool timeout, failures were immediate and there was no backlog, but the pool's reconnection back-off delayed recovery by 3–4 s after PostgreSQL was back.

Answer for TiffinBox
detect readiness failures; error-rate burn alerts; pool wait time and "connection refused" counts; managed-database events
mitigate fail fast (pool wait timeout); serve cached menus and "orders temporarily unavailable" with retry guidance; stop non-essential workers to reduce reconnection pressure
recover managed failover to the standby (typically under a minute); verify replication and data; drain queues
prevent HA with a standby in another zone; tested failover drills; tuned pool timeouts and reconnect back-off; connection limits sized for failover storms

2. Cache outage

What happens (the lab): with no fallback, cache-dependent endpoints fail; with a fallback but the client's default retries, each request waits ~4.4 s, connections pile up and the proxy collapses; with fast failure (no retries, 200 ms timeouts) and fallback to the database, no requests failed, latency rose from ~1.2 ms to ~1.9 ms.

Answer
detect Redis connection errors; hit rate drops to zero; database load rises
mitigate fall back to the database with fast failures; shed low-value traffic if the database nears saturation
recover restart or fail over Redis; it warms itself through read-through; stagger TTLs to avoid synchronised expiry
prevent explicit client timeouts and retry settings (never defaults); fallback paths tested in CI; capacity for the database to serve uncached peak load (or a replica for that)

3. Kafka outage

What happens: the outbox relay can't publish; consumers stop. Thanks to the outbox, business operations keep working: orders and skips commit, their events wait in the outbox.

Answer
detect outbox age and size rising; producer errors; consumer lag frozen; broker health
mitigate nothing urgent for users; pause non-critical producers; make sure the outbox table has room to grow
recover brokers back → relay publishes the backlog in order → consumers catch up (watch for consumer and downstream overload; throttle catch-up)
prevent managed Kafka with RF 3 across zones; outbox capacity planning; alerts on outbox age long before users notice late notifications

4. Slow dependency

What happens: chapter 211C's lab: without timeouts a hung dependency exhausted the shared threads and took down an unrelated endpoint; timeouts limited the damage; a circuit breaker removed it.

Answer
detect dependency latency (client spans) and breaker state; thread and connection pool saturation
mitigate breakers open; fallbacks; reduce timeout if it's too generous; disable the feature flag
recover breakers close after successful probes; review partial operations
prevent timeouts, bulkheads and breakers on every outbound call, tested by injecting latency in CI

5. CPU saturation

What happens (the lab): the API kept p99 around 7–20 ms up to 1,000 requests per second; at 1,500 p99 jumped to 248 ms; at 2,000 the median was 237 ms and p99 1.6 s, while completed throughput stayed near ~1,600 per second. Past the knee, extra load adds only queueing.

Answer
detect CPU utilisation and throttling; latency rising faster than load; queue lengths
mitigate scale out (HPA); shed load; disable expensive features (assistant, ranking) by flag
recover scale back after the peak; find the hot code with a profiler (async-profiler, JFR)
prevent load tests that find the knee for each release; HPA targets below the knee; capacity for peak + one zone lost

6. Memory leak

What happens (the lab): a process leaking ~20 MB/s inside a 200 MB limit was killed by the kernel after ~9.5 s, exit code 137, with no exception and no final log line.

Answer
detect memory growth slope per pod; restarts and OOMKilled reasons; GC time rising in JVMs
mitigate restarts keep it alive (Kubernetes does this); roll back the release that introduced it
recover capture a heap dump before the limit (JVM: -XX:+HeapDumpOnOutOfMemoryError catches Java heap exhaustion; for container kills, take dumps when memory crosses a threshold); find the retaining path
prevent soak tests (hours at steady load) watching memory; memory limits on every pod; leak checks in review (unbounded caches, listeners never removed)

7. Disk pressure

What happens (the lab): logs and data shared an 8 MB disk; logs used half, then every new order failed with "disk is full", while the logging library printed 10,932 errors to stderr and carried on.

Answer
detect free space and inode alerts with time-to-full projections; write errors; kubelet eviction events
mitigate free space (rotate or ship logs, delete temp files); stop the noisiest writer
recover database writes resume; check integrity; reprocess failed operations from user retries or queues
prevent logs to stdout and shipped off the node, never on data volumes; log rotation; separate volumes for data; storage autoscaling with alerts

8. Pod crash

What happens (the lab): killing one of two workers mid-traffic failed 0 GET requests (nginx retried them on the surviving worker) and 20 POST requests (not retried, since they might have taken effect); the supervisor started a replacement.

Answer
detect restarts, crash loops, exit codes; brief error spikes
mitigate enough replicas that one loss doesn't matter (PDBs, anti-affinity); clients retry with idempotency keys
recover automatic restart; for crash loops, roll back
prevent idempotency keys for all important POSTs so clients can retry safely; graceful shutdown; investigate every crash's cause

9. Region loss

What happens: everything in one cloud region is unavailable. Not measurable on one machine; it's a planning and drill exercise.

Answer
detect external synthetic checks from other regions fail; provider status
mitigate communicate; decide to fail over (a human decision with criteria written in advance)
recover per the DR plan: restore the database in the standby region from cross-region backups or promote a cross-region replica (RPO = its lag), apply infrastructure code there, point DNS, warm caches; later, fail back
prevent for TiffinBox's targets (RTO 1 h, RPO 5 min): cross-region replicas or backups, infrastructure code that can build the region, container images replicated, regular timed drills. Active-active multi-region is rarely worth its complexity at this scale.

10. Traffic spike

What happens (the lab): at 2,500 requests per second against a capacity of ~1,600, p99 reached 3.3 s and the load generator itself couldn't send 12,202 of its requests; with a simple in-flight limit (16 per worker) returning 503 with Retry-After, the 54% of requests accepted had p99 119 ms.

Answer
detect request rate far above forecast; latency and saturation; queue growth
mitigate shed load; rate-limit per user and per IP at the edge; serve cached pages; scale out (with limits the database can take)
recover scale back; review whether the spike was legitimate (a promotion) or abusive (bots)
prevent load tests to 2–3× the expected peak; admission control and rate limits in place before they're needed; pre-scale for known events

Done when

  • All ten exercises have been run in staging (and the safe ones in production), each with a written four-part answer and a timeline.
  • Every surprise (client defaults, proxy limits, silent OOMs) has become a fix and a regression test.
  • The exercises that can be automated run weekly in staging.

Common traps

  • Testing only clean failures (connection refused) and not slow ones (hangs).
  • Trusting library defaults for timeouts and retries.
  • Fallbacks that were never exercised.
  • No abort conditions in production experiments.
  • Write-ups without owners for the actions.

Lab: breaking dependencies and resources

Setup. The slice of TiffinBox from chapter 211A's lab on one 2-CPU machine: nginx → a FastAPI app (uvicorn, 2 workers, httptools) → PostgreSQL 16 (1 M orders) and Redis 7. An open-model load generator (Python aiohttp, fixed arrival rate, 5 s client timeout) recorded each second's successes and failures; k6 with a constant arrival rate measured the capacity curve. Experiments use environment switches in the app: pool wait timeout (POOLTIMEOUT), Redis fallback (FALLBACK), Redis client retries off (NORETRY), and an in-flight limit (LIMIT).

1. Database outage (100 req/s for 40 s; PostgreSQL stopped at ~10 s and restarted ~10 s later)

Pool configuration Failed requests Behaviour
defaults (wait up to 30 s for a connection) 967 of 4,000 requests during the outage waited 5.5–6 s and timed out; after restart, waiting requests completed with 4.7 s, then 3.8 s, … latency until the backlog drained ~5 s later; a short second burst of fast failures followed about 2 s after recovery (its cause wasn't pinned down; enabling the pool's connection check didn't remove it)
wait timeout 0.5 s 1,353 of 4,000 failures in ~0.5 s throughout, no backlog; but requests kept failing for ~3–4 s after PostgreSQL was back, while the pool's reconnection back-off waited to retry

Neither is free: waiting hides short blips at the cost of a pile-up; failing fast keeps the system responsive but needs quick reconnection (tune the pool's reconnect back-off).

2. Cache outage (200 req/s for 30 s to a cached endpoint; Redis stopped for 10 s)

Configuration Failed What the clients saw
no fallback 1,514 of 6,000 errors while Redis was down
fallback to PostgreSQL, Redis client defaults 1,424 of 6,000 906 dropped connections, 503 client timeouts, 27 socket errors; nginx logged "1024 worker_connections are not enough"
fallback, client retries off (200 ms timeouts) 0 of 6,000 latency 1.2 ms → ~1.9 ms during the outage

Diagnosis: with the client's default settings, a single GET against a stopped Redis took 4.4 s to raise its error (retries with back-off); with retries off, it failed in under a millisecond.

3. Capacity curve (k6, constant arrival rate, 15 s each, join endpoint)

Offered load Median p99 Not sent (generator ran out of capacity)
500/s 1.4 ms 6.8 ms 0
1,000/s 1.9 ms 20.4 ms 0
1,500/s 20.6 ms 248 ms 163
2,000/s 237 ms 1,616 ms 5,950
2,500/s 528 ms 3,725 ms 14,850
3,000/s 503 ms 3,305 ms 21,570

Completed throughput levelled off around 1,600–1,700 requests per second (the load generator shares the same CPUs).

4. Load shedding at 2,500/s

Requests sent Succeeded p99 of successes Rejected
no limit 25,299 (12,202 never sent) 25,299 3,292 ms 0
in-flight limit 16 per worker 37,201 20,234 (54%) 119 ms 16,967 instant 503 Retry-After: 1

At 1,000/s the same limit rejected 0.6% of requests: set limits from measurements, with headroom for bursts.

5. Worker crash (100 req/s to a 200 ms endpoint; one of two workers killed with kill -9 after 8 s)

Method Failed Why
GET 0 of 2,000 nginx retried requests that failed on the dead worker's connections against the other worker
POST 20 of 2,000 (502) nginx doesn't retry non-idempotent requests (proxy_next_upstream excludes them by default)

The uvicorn supervisor started a replacement worker within the 3 s check.

6. Memory leak (cgroup v1 memory limit 200 MB; a Python process allocating and touching 10 MB every 0.5 s)

Killed at ~9.5 s after reaching 199 MB RSS. Exit code 137 (SIGKILL); memory.failcnt 23; oom_kill 1. The process printed nothing at the end: no exception, no last log line.

7. Disk pressure (an 8 MB tmpfs holding both an app log and a SQLite orders database; 20,000 orders, each logged with ~400 bytes)

9,036 orders saved, then 10,964 failed with database or disk is full. The logging library hit the same full disk and printed 10,932 "Logging error" messages to stderr, then carried on. Final sizes: log 4.1 MB, database 4.0 MB.

What it shows

  • Defaults decide outages. A 30 s pool wait, a Redis client's retry policy, and nginx's 1,024 connections each turned a small failure into a bigger one. Set every timeout, retry and limit explicitly, then test them.
  • Fast failure plus fast recovery is the goal; one without the other moves the pain around.
  • Capacity has a knee, and beyond it only latency grows. Load shedding keeps the accepted work fast.
  • Idempotency decides what can be retried safely, by proxies as much as by clients.
  • Resource exhaustion is silent or misleading (no last log line; "disk full" in the database because of logs); watch trends, not just failures.

Try it yourself

  1. Tune the pool's reconnection settings (reconnect_timeout, back-off) and find a configuration that both fails fast and recovers within a second.
  2. Repeat the cache outage at 400 req/s with fallback on: does PostgreSQL keep up without the cache?
  3. Implement adaptive concurrency limits (based on latency) instead of a fixed 16, and rerun the spike.
  4. Give the leaking process a heap-growth alert at 150 MB (a script watching the cgroup) and measure how much warning you get.

Revision sheet: failure exercises I

Key ideas

  • For every failure: detect, mitigate, recover, prevent.
  • Exercises need a hypothesis, blast-radius limits, abort conditions and normal telemetry; automate the passing ones.
  • Database outage: fail fast and reconnect fast; HA standby; failover drills.
  • Cache outage: explicit timeouts, retries off, tested fallback, database capacity.
  • Kafka outage: the outbox holds events; watch outbox age; throttle catch-up.
  • Slow dependency: timeouts, bulkheads, breakers.
  • CPU: find the knee; scale and shed before it.
  • Memory: watch the slope; OOM kills are silent.
  • Disk: logs off the node and off data volumes.
  • Pod crash: replicas, PDBs, idempotency keys.
  • Region loss: written criteria, cross-region data, rebuildable infrastructure, timed drills.
  • Spikes: rate limits and admission control prepared in advance.

Numbers to remember

  • DB outage: default pool → ~6 s waits and a backlog; 0.5 s timeout → fast failures, 3–4 s reconnection lag.
  • Cache outage: default client retries 4.4 s per call → 1,424/6,000 failed; retries off → 0.
  • Knee ~1,000–1,500 req/s; shedding kept p99 at 119 ms vs 3.3 s.
  • Worker kill: GET 0 failures, POST 20.
  • OOM: exit 137, no last log line.

Pitfalls

  • Only clean failures tested; library defaults; untested fallbacks; no abort conditions; actions without owners.

Glossary

  • Game day: a planned failure exercise with the team watching.
  • Blast radius: how much can be affected by an experiment or failure.
  • Load shedding: rejecting excess work early to protect accepted work.
  • Knee: the load beyond which latency rises sharply.
  • Exit code 137: process killed by SIGKILL (128 + 9), typical of OOM kills.