Volume 3 Exercises: The BackendPractice for Volume 3
0 / 0

Workbench / Volume 3 Exercises: The Backend

V3·52

Resilience

Exercises for Volume 3, chapter 52: why systems fail; timeouts and retries; retry amplification; non-idempotent operations; circuit breakers; bulkheads; rate limiting; load shedding; graceful degradation and fallbacks; hedging and tail-latency techniques; implementations across stacks; and a resilience checklist per dependency. 9 theory questions, 9 programming exercises, 3 cumulative projects, the concepts the chapter leaves out, and 5 senior-level exercises.

32 exercises · ~15 min to read
Updated Suggest a correction

Start here: how this chapter's exercises work

The four sets and the locking work as before. The code uses Spring Framework 7.0.9's built-in resilience annotations (@Retryable, @ConcurrencyLimit, @EnableResilientMethods), running for real, plus plain JDK 21 for the breaker, shedding, rate-limiting and hedging experiments. Resilience4j wasn't available offline, so its exercises give expected behaviour, marked as such. Every quoted output is real, and five of them catch experienced developers:

  • P1. @Retryable(maxRetries = 3, delay = 100, multiplier = 2) retried at 16, 119, 320 and 721 ms, as designed. But with timeout = 500, the caller got the plain last IllegalStateException, not a timeout exception, after only 3 calls.
  • P2. @Retryable on a payment charge whose response timed out made the provider charge 3 times.
  • P2. Calling a @Retryable method from the same bean made 1 call, no retries. Reading a field directly on the CGLIB proxy returned null.
  • P4. A hand-written breaker noticed the dependency's recovery at 2,000 ms only at 2,836 ms, because its half-open trial at about 1,830 ms failed and restarted the 1-second cool-down.
  • P6. Hedging a second request after 50 ms cut p99 from 501 ms to 61 ms for 6% more backend calls (212 against 200).

The chapter's lab already covered these, and the exercises build on them rather than repeat them:

  • retry amplification: 64 database calls for one request when three layers retried;
  • synchronised retries: a peak of 1,000 in one window without jitter, 154 with full jitter;
  • a breaker cutting 100 hanging calls from 20,206 ms to 1,003 ms;
  • a bulkhead keeping the menu at 5 ms instead of 5,937 ms;
  • an unbounded queue (p99 3,101 ms) against shedding (p99 121 ms).

Coverage map.

Chapter component Exercises
why systems fail T1
timeouts; deadlines T2, P1
retries; backoff and jitter T2, P1
retry amplification; budgets T3, P7
non-idempotent operations T3, P2
circuit breaker T4, P4
bulkheads T5, P3
rate limiting T6, P5
load shedding T6, P5
graceful degradation; fallbacks T7, P8
hedging; tail latency T8, P6
implementations across stacks T9, P9
the per-dependency checklist T9, S1

Theory

T1. Why systems fail, and what "resilient" means

  1. List TiffinBox's failure modes: - a dependency is down (fast failures); - a dependency hangs (slow failures, the worst kind); - partial failures (one replica, one partition); - overload; - bad deploys; - expired certificates; - exhausted connection pools (ch49); - full disks; - clock skew (ch50's tokens); - retry storms.

Why are slow failures worse than fast ones? 2. Define availability (successful requests / valid requests), SLOs, error budgets, and the difference between reliability (doing the right thing) and resilience (degrading gracefully and recovering). What's the availability of a request that depends on 5 services at 99.9% each, called in series? 3. For each TiffinBox dependency (payments, loyalty, maps ETA, recommendations, the SMS provider, the database), classify it as critical (no checkout without it), degradable (checkout works with a fallback) or optional (hide the feature). How does that classification drive timeouts, retries, breakers and fallbacks?

T2. Timeouts, deadlines and retries

  1. Timeouts at every level: connect, read or response (ch48's RestClient), pool acquisition (ch49's connectionTimeout), database statements (statement_timeout), lock waits (lock_timeout), and the overall request deadline. How do you choose values (the dependency's p99 under normal load, plus margin, and below the caller's deadline)? Why do default timeouts (infinite, or Hikari's 30 s) cause incidents?
  2. Deadline propagation. A checkout has an 800 ms budget. It spends 300 ms on payments, and loyalty is called with the remaining 500 ms. P1: @Retryable(timeout = 500) stopped after 3 calls (at 0, 101 and 301 ms), because the next retry at about 701 ms would exceed 500 ms, and threw the last exception. How do you pass a deadline across services (a grpc-timeout-style header, a request-scoped Deadline object), and what should a service do when the remaining budget is less than its typical latency?
  3. Retries. P1: maxRetries = 3, delay = 100, multiplier = 2 retried at 16, 119, 320 and 721 ms; an IllegalArgumentException not listed in includes gave 1 call and was rethrown immediately. What should be retried (timeouts, 503, 429 with Retry-After, connection resets) and what never (400, 401, 403, 404, 409, validation)? Why jitter (the lab's 1,000 against 154 peak)?

T3. Retry amplification, budgets and non-idempotent operations

  1. The lab: three layers each retrying 3 times sent 64 database calls for one user request; retrying only at the layer next to the database sent 4. P7 measured a retry budget: 1,000 requests against a dead dependency made 4,000 calls with 3 retries each, and 1,099 with retries capped at 10% of requests. Explain where retries should live and how budgets (Envoy's retry_budget, gRPC's retry throttling) protect a recovering service.
  2. P2: @Retryable on a charge whose response timed out after the provider had charged produced 3 charges. Explain why a timeout means "unknown outcome", and how idempotency keys (ch45), status queries ("did payment pay_123 succeed?") and reconciliation make retries safe.
  3. Which TiffinBox operations are naturally idempotent (GET, PUT of a full resource, DELETE, state transitions guarded by state) and which need keys (POST create, charges, sends)? Why must the key be generated once per user intent, not per attempt?

T4. Circuit breakers

  1. The lab: without a breaker, 100 calls to a hanging dependency took 20,206 ms and reached it 100 times; with a breaker opening after 5 failures, 1,003 ms and 5 calls. Explain the states (closed, open, half-open), what counts as a failure (exceptions, timeouts, slow calls), and Resilience4j's configuration: sliding windows (count or time based), failureRateThreshold, slowCallDurationThreshold, slowCallRateThreshold, minimumNumberOfCalls, waitDurationInOpenState, permittedNumberOfCallsInHalfOpenState.
  2. P4: the dependency recovered at 2,000 ms, but the breaker closed only at 2,836 ms. The half-open trial at about 1,830 ms failed, and the next trial waited a full second. What trade-off does waitDurationInOpenState make? What's exponential backoff for open-state waits, and why should a breaker be per dependency (and sometimes per endpoint or per host)?
  3. What should the caller do when the breaker is open (fallback, fail fast with a clear error, queue for later)? How do open breakers appear in metrics and alerts? When can a breaker hurt (one bad request type opening the breaker for all; too small windows flapping)?

T5. Bulkheads

  1. The lab: 60 slow reports (2 s each) filled a shared pool of 20 threads and the menu waited 5,937 ms; limiting reports to 5 concurrent kept the menu at 5 ms. P3 ran Spring 7's @ConcurrencyLimit(5): - REJECT: max 5 in flight, 15 rejected with InvocationRejectedException: Concurrency limit reached: 5, total 215 ms; - BLOCK (the default): max 5 in flight, 0 rejected, 807 ms (callers queued).

When should a bulkhead block, and when reject? 2. Bulkhead types: semaphores (@ConcurrencyLimit, Resilience4j Bulkhead), separate thread pools (ThreadPoolBulkhead), separate connection pools per dependency or per workload (interactive against batch), separate instances or deployments (a dedicated report service), and per-tenant limits. Which fits virtual threads (ch38), where thread pools no longer limit anything by default? 3. Size TiffinBox's bulkheads with Little's law: maps receives 300 req/s from checkout at a p99 of 80 ms; reports take 2 s and arrive at 2/s. What limits follow?

T6. Rate limiting and load shedding

  1. Rate limiting against shedding: - rate limiting enforces a contract per client: P5's token bucket (100/s, burst 20) allowed all 100 requests at 50/s, then 120 of a 300-request burst at 300/s, limiting 180; - load shedding protects capacity regardless of who is asking: the lab's bounded queue served 307 and shed 293 with p99 121 ms.

Where does each run (gateway, service, per tenant), and what does each return (429 with Retry-After and RateLimit headers against 503)? 2. Queue policies under overload. P5 at 200 req/s against a capacity of 100: - a queue bounded at 10: served 307, shed 293, p50 116, p99 121 ms; - CoDel-style (drop requests that already waited over 50 ms): served 302, shed 298, p50 68, p99 71 ms.

Explain why shedding by waiting time gives lower latency for the same throughput, and how adaptive concurrency limits (Netflix concurrency-limits, Envoy's adaptive concurrency) work. 3. Prioritised shedding: when overloaded, which TiffinBox traffic do you drop first (recommendations, analytics, menu browsing against checkout and kitchen updates)? How do you mark priority (routes, headers, separate pools), and how do clients behave well (backoff, respecting Retry-After, no tight retry loops)?

T7. Graceful degradation and fallbacks

  1. Design fallbacks for TiffinBox: - loyalty down: "points will appear later" plus a queued accrual; - maps down: an approximate ETA from historical averages, labelled; - recommendations down: hide the carousel, or show static bestsellers; - the menu service slow: serve the last known menu from cache (ch53) with a "prices may have changed" check at checkout; - search down: category browsing.

What makes a fallback honest (labelled, never inventing critical data like payment status)? 2. Fallback hazards: - fallbacks that are never exercised and fail when needed; - fallbacks that hit the same failing dependency; - fallbacks that are more expensive than the primary (a database query replacing a cache); - "fail open" against "fail closed" for authorisation and fraud checks.

How do you test fallbacks continuously? 3. Feature flags and kill switches: turn off recommendations under load, disable a misbehaving integration without a deploy, and progressive delivery (canaries, ch51's C3). Which flags must be checked locally (no network call to the flag service on the hot path)?

T8. Hedging and other tail-latency techniques

  1. P6: when 5% of requests took 500 ms, a single call gave p50 10 ms and p99 501 ms. Sending a second request if the first hadn't answered in 50 ms gave p99 61 ms for 212 backend calls instead of 200. Explain hedging, why its cost is small when the hedge delay is near p95, and why it's only safe for idempotent reads.
  2. Other tail techniques: - tied requests (send to two, cancel the loser); - client-side load balancing with least-outstanding-requests or peak-EWMA; - outlier ejection; - request coalescing (many identical requests share one call; ch53's stampede protection); - caching (ch53); - reducing fan-out width.

Why does fan-out make tails dominate ("The Tail at Scale": with 100 backends at p99 1 s, 63% of requests see a 1 s call)? 3. When does hedging hurt (an overloaded backend gets more load; non-idempotent writes; hedging at every layer multiplies like retries)? How do you cap it (a hedging budget, only hedge when the backend is healthy)?

T9. Implementations across stacks, and the per-dependency checklist

  1. Compare resilience tools: - Spring Framework 7: @Retryable (with maxRetries, delay, multiplier, jitter, maxDelay, timeout, includes, excludes, predicate), RetryTemplate, @ConcurrencyLimit (BLOCK or REJECT), enabled with @EnableResilientMethods (P1–P3); - Resilience4j: circuit breakers, retry, bulkhead, rate limiter, time limiter, with Micrometer metrics; - Spring Cloud Circuit Breaker; - service meshes (Istio, Linkerd: retries, timeouts, outlier detection, without code changes); - other languages: Polly in .NET, tenacity and pybreaker in Python, opossum and cockatiel in Node, sony/gobreaker and failsafe-go in Go.

What can a mesh not do (fallbacks with business meaning, idempotency keys)? 2. P2 also showed that annotation-based resilience runs through proxies: self-invocation bypassed @Retryable (1 call), and reading a field on the CGLIB proxy gave null. Which ch46 rules apply, and how do you test that the annotations are active? 3. Write the per-dependency checklist (the chapter's checklist, completed): - timeout; - retries (which errors, how many, backoff, jitter, at which layer); - idempotency; - circuit breaker; - bulkhead; - fallback; - rate limits on the dependency's side; - metrics and alerts; - load-test results; - owner.

Fill it for loyalty.

Programming exercises

P1. Spring 7 @Retryable: backoff, includes and deadlines

With Spring Framework 7 and @EnableResilientMethods: 1. annotate a loyalty client method with @Retryable(maxRetries = 3, delay = 100, multiplier = 2, jitter = 0, includes = IllegalStateException.class), and record the attempt times against a stub that fails 3 times; 2. throw an exception outside includes, and count calls; 3. add timeout = 500 with maxRetries = 5, and record what the caller receives; 4. set a realistic jitter, and plot attempt times over 100 runs.

P2. Proxies and non-idempotent retries

Show: 1. self-invocation bypassing @Retryable; 2. a field read on the CGLIB proxy returning null; 3. @Retryable on a charge whose response times out after the provider charged, counting charges.

Then fix the charge with an idempotency key generated once per intent, plus a status query before retrying, and write tests proving 1 charge across 3 attempts.

P3. Bulkheads with @ConcurrencyLimit

Run 20 concurrent 200 ms calls through @ConcurrencyLimit(5) with the REJECT and BLOCK policies, recording the maximum in flight, rejections and total time. Then reproduce the lab's menu-against-reports scenario on virtual threads (where nothing limits concurrency by default), and show the menu's latency with and without a report bulkhead plus a separate small connection pool for reports.

P4. A circuit breaker, measured

  1. Implement a minimal breaker (closed, open for 1 s, one half-open trial) around a dependency that's down until 2,000 ms and record the state transitions, the first success time and how often the dependency was reached.
  2. Then configure Resilience4j (expected) with a time-based window, slow-call detection, 3 half-open probes and exponential open-state waits, and compare recovery-detection delay and probe count.

P5. Rate limiting against shedding against CoDel

Drive a service with a capacity of 100 req/s at 200 req/s for 3 s, under: - a bounded queue of 10; - CoDel-style shedding (drop at dequeue if the request waited over 50 ms); - a token-bucket rate limiter (100/s, burst 20) with steady traffic, then a burst.

Record served, shed, p50 and p99. Then implement shedding as a servlet filter returning 503 problems with Retry-After, with priority classes.

P6. Hedged requests

Simulate a backend where 5% of requests take 500 ms and the rest 10 ms. Measure p50, p99 and backend calls for single calls and for a hedge after 50 ms. Then: - add cancellation of the losing request; - add a hedging budget (at most 10% extra); - disable hedging when the backend's error rate exceeds 20%; - implement it for an idempotent RestClient GET.

P7. Retry budgets and one-layer retries

Model a gateway → orders → loyalty → database chain with the database down: 1. retries at every layer (the lab: 64 calls); 2. retries only at the innermost layer (4); 3. a 10% retry budget with 1,000 requests (P7: 1,099 calls against 4,000).

Then implement a retry budget for the RestClient used by all of a service's clients (a token bucket that refills by 0.1 per request and spends 1 per retry), and add deadline propagation through an X-Request-Deadline header.

P8. Fallbacks, tested with fault injection

Implement checkout's dependencies with fallbacks (T7): loyalty, maps and recommendations. Then use Toxiproxy (or a stub with configurable latency and errors) to inject: - 2 s latency; - 50% 503s; - connection resets; - a full outage.

For each, assert checkout's status, latency and the labelled fallback in the response, plus the fallback.used metric.

P9. Resilience4j composition and observability

Compose Resilience4j (expected if unavailable) around the maps client: TimeLimiter(300 ms), CircuitBreaker, Retry(1, jitter), Bulkhead(50). Verify the decorator order, then: - expose all metrics through Micrometer; - build a dashboard panel per dependency (latency, errors, breaker state, rejections, retries, fallbacks); - write alerts; - compare the same configuration as a service-mesh policy (Istio DestinationRule and VirtualService).

Cumulative projects (chapters so far: Volume 1, Volume 2, and Volume 3's 33–52)

C1. Make checkout survive any one dependency failing

Harden checkout (ch44–51) so that any single non-critical dependency can fail, hang or slow down without breaking the SLO (99.9% within 800 ms): - deadlines from the edge; - per-dependency timeouts, retries (one layer, with budgets), breakers, bulkheads and fallbacks (T9's checklist for each); - payments failing closed with idempotency keys and status queries (P2); - queued side effects (ch51); - shedding with priorities (P5); - a fault-injection suite in CI (P8); - dashboards and alerts (P9); - a load test at 2× peak with each fault.

Combines: ch38's virtual threads, ch45's idempotency, ch47's observability, ch48's clients, ch49's pools, ch51's outbox and jobs, and this chapter.

C2. A game day for TiffinBox

Plan and run a game day in staging: - hypotheses ("if maps hangs, checkout p99 stays < 800 ms"); - experiments (maps latency, loyalty outage, database failover, one zone lost, a 3× traffic spike, the SMS provider down); - blast-radius limits and an abort plan; - observation (dashboards, traces); - findings and fixes.

Write the report.

Combines: ch47's operations and health, ch49's database failover, ch51's queues, ch53's caches (preview), and this chapter.

C3. Resilience for the event pipeline

Apply this chapter to ch51's event backbone: - consumers with bulkheads per handler type; - breakers around downstream calls in handlers, pausing consumption (not acknowledging and failing) when a dependency is down; - retry topics with backoff and jitter; - poison isolation; - lag-based autoscaling with limits so a backlog doesn't overwhelm downstream services on recovery; - recovery-rate limiting after an outage.

Measure recovery after a 10-minute downstream outage.

Combines: ch51's messaging, ch53's caches (preview), and this chapter.

What the chapter leaves out

Chaos engineering

Chaos engineering injects faults deliberately, in staging and eventually production, with hypotheses and small blast radii (Chaos Monkey, Gremlin, LitmusChaos, AWS Fault Injection Service). C2's game day is the manual form. Automate the experiments that pass, so regressions are caught.

Static stability and cell-based architecture

Static stability means a system keeps working with its last known configuration when its control plane fails: cached routes, pre-provisioned capacity, no dependency on the control plane for the data path. Cells (independent copies of the stack, each serving a subset of customers or kitchens) limit the blast radius of any failure or bad deploy to one cell. AWS's builders' library covers both.

Multi-region failover

Active-passive or active-active regions, DNS or global load-balancer failover, data replication (RPO and RTO targets), and conflict resolution for multi-writer data. These are expensive and complex. Most services should first make one region robust across zones.

Backpressure across distributed systems

Reactive Streams (ch48) handle backpressure in-process. Across services, it's done with queues and lag-based scaling (ch51), Retry-After, adaptive concurrency, and admission control at the edge. Pushing demand back to the source keeps the system stable instead of buffering everywhere.

Testing resilience in code review

Common review questions to ask: - Is there a timeout on every call? - Is the operation idempotent before retrying it? - Do retries happen at only one layer? - Is the fallback honest, and tested? - Are limits explicit with virtual threads? - Does it degrade, or fail closed, where it should?

S2 practises them.

Senior exercises

S1. TiffinBox's resilience standard

Write the standard: - dependency classification; - deadlines; - timeouts on everything; - retries (which errors, one layer, budgets, jitter); - idempotency before retries; - breakers with slow-call detection; - bulkheads with explicit limits (virtual threads); - shedding with priorities and CoDel-style limits; - honest fallbacks, tested in CI; - hedging rules; - flags and kill switches; - mesh against application responsibilities; - metrics and alerts; - game days.

Tie each to an output.

S2. Review a resilience pull request

A PR adds: - @Retryable(maxRetries = 5) on PaymentClient.charge; - @Retryable on a method called only from the same class; - a RestClient with no read timeout for maps "because it's fast"; - a circuit breaker counting 4xx responses as failures; - a fallback for fraud checks that returns "allowed"; - Istio retries of 3 on the same route where the application already retries 3 times.

Write the review.

S3. Analyse an incident: the retry storm

An incident: the loyalty database had a 3-minute failover. Afterwards, loyalty stayed down for 40 minutes. Graphs show loyalty request rate at 12× normal after the failover, CPU pinned, and many timeouts. Checkout success fell to 92% for the whole 43 minutes. Write the analysis: the causal chain, why recovery failed, the contributing factors, and the fixes in priority order.

S4. Teach "resilience by numbers" with five outputs

Prepare a 20-minute session using: - the lab's 64× amplification; - P2's 3 charges; - P3's REJECT against BLOCK (215 against 807 ms); - P5's CoDel (p99 121 → 71 ms); - P6's hedging (p99 501 → 61 ms for 6%).

S5. Plan a reliability programme

As the reliability lead, plan two quarters: - SLOs and error budgets for the top 5 user journeys; - the dependency registry and checklists (T9); - starter defaults (timeouts, retries, budgets, breakers, limits); - the fault-injection suite in CI (P8); - edge shedding with priorities (P5); - the incident follow-ups (S3); - quarterly game days (C2); - a policy for mesh against application retries; - dashboards per dependency; - training (S4).

Give milestones, risks and metrics.