Workbench / Volume 3 Companion: The Backend
V3·52
Resilience — Timeouts, Retries, Circuit Breakers and Load Shedding
Companion to Volume 3, chapter 52: how why systems fail, timeouts and retries, isolating failure and behaving under overload connect; new angles (a convoy behind one slow truck, a shop that says "come back later", a stuck worker with a stopwatch); what the chapter simplifies, measured on the build's stage 53 with a disk made slow on purpose: one instance with a slow disk dragged two instances behind a load balancer from 36,513 orders in 20 seconds to 41, because orders queued behind a per-customer lock where no queue metric could see them; load shedding on the right signal, with readiness that holds still, brought it back to 40,194; and a scheduled job that hung, which no error report would ever show; the theory behind them (queues you can't see, admission control, hysteresis, fault injection); how Spring 7's @ConcurrencyLimit chooses to block by default, from its source; four debugging drills; interview questions with how to approach each.
Understanding it better
Concept map
Chapter 52 covers why systems fail (failure as the normal case), timeouts and retries (timeouts, retries, retry amplification, non-idempotent operations), isolating failure (circuit breakers, bulkheads, rate limiting) and behaving under overload (load shedding, graceful degradation and fallbacks, hedging), with implementations across stacks and a per-dependency checklist.
The links worth remembering:
- Every wait needs a limit, and every limit needs a decision about what happens at it: fail, retry, degrade or queue.
- Queues hide overload until they're full. Latency is the earliest signal, if you measure it where the waiting happens.
- Resilience is mostly saying no early. A fast refusal lets the caller, or the load balancer, go somewhere useful.
Explain it differently
1. A convoy behind one slow truck. On a single-lane road, one slow truck sets everyone's speed, however fast the cars are. TiffinBox's per-customer lock is a single lane: one write waiting on a slow disk, and every write for that customer waits behind it (Gaps 1).
2. A shop that says "come back later". A shop that lets everyone in when the counter is overwhelmed makes everyone wait an hour; a shop that says at the door "busy, try the branch next door" serves the people inside and sends the rest somewhere quicker (Gaps 2).
3. A worker with a stopwatch. A job that's stuck doesn't fail; it just never finishes. Someone has to time it and call it, and not send a second worker to stand behind the first (Gaps 4).
Gaps and misconceptions
What the chapter oversimplifies
All outputs are real, from OpenJDK 21.0.12, haproxy (checking /health/ready every 500 ms) and the build's stage 53 server (exp/53), unless stated. Shedding is a setting (shed-after), so "stage 52's behaviour" is the same build with it off.
1. A slow dependency behind a lock is an outage. The chapter's dependencies are remote services; TiffinBox's is its disk. Stage 53 adds fault injection for drills (fault-fsync-delay: each fsync takes longer, as on a degraded disk). Two instances behind haproxy, instance a's fsync 2 s slower, eight clients placing orders for 20 seconds:
# no fault, shedding off
36513 orders from 8 clients in 20 s
201 x36513 p50 3.1 ms p99 21.6 ms max 148.3 ms
# a's fsync +2s, shedding off (stage 52's behaviour)
41 orders from 8 clients in 20 s
201 x 25 p50 5.4 ms p99 8133.1 ms max 8133.1 ms
504 x 16 p50 10002.2 ms p99 10003.1 ms max 10003.1 ms
placed on a (slow disk): 5, on b: 20
One slow instance out of two, and the pair served 41 orders instead of 36,513. Instance b was fine and served 20: every client was stuck waiting on a. Orders for one customer take a lock (one order at a time per customer, so "first order" is decided once), and the lock was held across the slow write, so every later order waited for it: a convoy. Round-robin sent each client's next request to a again, and haproxy's 10-second timeout turned waits into 504s. Readiness (stage 48) said ready throughout, because nothing it checked was wrong.
2. Shed on the wait you can see, and hold the decision. The obvious overload signal is the log's queue: how long the oldest unwritten record has waited. Stage 53's first version shed new orders when that passed 1 second, and served 2,158 orders (exp/53/sick-first-version.out): the waiting was on the lock, before the log's queue, and the log's lag hardly ever passed one fsync, so a was rarely marked overloaded. The version that worked measures the oldest write in progress anywhere in the order service, lock waits included; refuses new orders above shed-after (503, Retry-After: 2, "nothing was saved: retry with the same Idempotency-Key"); refuses kitchen events only at twice that (food already cooking matters more than new orders); and says "not ready: overloaded" for 5 seconds after the last refusal, so the load balancer doesn't flap between checks:
# a's fsync +2s, shed-after 1s (stage 53)
40194 orders from 8 clients in 20 s
201 x40191 p50 2.3 ms p99 7.3 ms max 9972.7 ms
504 x 3 p50 10001.5 ms p99 10001.9 ms max 10001.9 ms
placed on a (slow disk): 5, on b: 40186
Three requests were already inside a when it went slow; everything after went to b. The chapter's lab shows shedding beating queueing within one server; across servers, shedding's main value is the signal: readiness turns a slow instance into a removed one.
3. A refusal is only safe if nothing was half-done. Shedding happens before the order joins the log's queue, so a 503 means nothing was written, and a retry with the same idempotency key places the order once. Timing out a write already queued would be different: the record may still reach the disk after the client was told it failed, and the key must stay reserved until it does (the order service's byKey future). Stage 53 doesn't time out queued writes for that reason, and says so in its 503's detail. "Retry on 503" is safe only when the server makes it safe.
4. A hung job raises no errors. Stage 52's jobs counted failures, but a job that never returns never fails. Stage 53 gives each run a deadline: the work runs on its own virtual thread, is interrupted at the deadline, and counts as a failure; while it's still alive (code that ignores interrupts can't be stopped), later runs are skipped and counted rather than stacked behind it:
job stuck failed: java.util.concurrent.TimeoutException: timed out after 100 ms
job stuck: still running after its deadline: run skipped
(From JobsTest.aHungJobTimesOutAndLaterRunsAreSkippedNotStacked.) A thread that ignores interrupts leaks until the process restarts; the counts make that visible instead of silent.
Common misconceptions
| Misconception | What's actually true | Where it's shown |
|---|---|---|
| "One bad instance out of two halves capacity." | It can take everything, if clients wait on it. | Gaps 1 |
| "Measure queue depth to detect overload." | Measure the age of the oldest waiter, where it waits. | Gaps 2 |
| "Readiness should follow the instant's health." | Without hysteresis it flaps faster than checks. | Gaps 2 |
| "Retrying a 503 is always safe." | Only when the server guarantees nothing was done. | Gaps 3 |
| "Timeouts on calls are enough." | Background work needs deadlines too. | Gaps 4 |
| "Retries make systems more reliable." | Uncapped, they multiply load on the struggling part. | The chapter's lab, Experiment 1 |
Theoretical gaps: the ideas behind the chapter
1. Queues you can't see. Every lock, connection pool, semaphore and thread pool is a queue. Little's law (waiting work = arrival rate × time in system) holds for all of them; the one that's full sets the latency. Measure time in system at the point of entry, not depth in one structure.
2. Admission control. Decide at the door whether a request will finish in time; refuse quickly if not. Priority classes (kitchen events before new orders) let the important work through as capacity shrinks. CoDel and its relatives decide by how long the oldest item has waited, which is Gaps 2's signal.
3. Hysteresis. A signal that switches on and off around one threshold oscillates; using a hold time (or two thresholds) makes a load balancer's decisions stable. Circuit breakers use the same idea: a cool-down before half-open.
4. Fault injection. You find failure modes by causing them: slow disks, dropped connections, full disks, clock jumps. Built-in fault points (like fault-fsync-delay, or etcd's failpoints) make drills repeatable and safe to run in staging, and the drill's measurements become the regression test for the fix.
Applying it
Code walkthrough
Spring Framework 7 brought resilience annotations into the core framework. Gaps 2's choice, queue or refuse, is a default there. From spring-projects/spring-framework, main at commit 7ce40c8 (18 November 2026).
@ConcurrencyLimit blocks by default
spring-context/src/main/java/org/springframework/resilience/annotation/ConcurrencyLimit.java:
/**
* The policy for throttling method invocations when the limit has been reached.
* <p>The default behavior is to block further concurrent invocations once the
* specified limit has been reached: {@link ThrottlePolicy#BLOCK}.
...
ThrottlePolicy policy() default ThrottlePolicy.BLOCK;
...
enum ThrottlePolicy {
BLOCK,
REJECT
}
And the blocking itself, spring-core/src/main/java/org/springframework/util/ConcurrencyThrottleSupport.java:
protected void beforeAccess() {
...
this.concurrencyLock.lock();
try {
if (this.concurrencyCount >= this.concurrencyLimit) {
onLimitReached();
}
...
this.concurrencyCount++;
...
protected void onLimitReached() {
boolean interrupted = false;
while (this.concurrencyCount >= this.concurrencyLimit) {
...
try {
this.concurrencyCondition.await();
}
A method annotated @ConcurrencyLimit(10) admits ten callers; the eleventh waits on a condition until one leaves, with no time limit. That's a bulkhead that protects the resource behind it (never more than ten at once) and makes callers queue: Gaps 1's convoy, by design, when the resource slows down. policy = REJECT (since 7.0.3) throws InvocationRejectedException instead: Gaps 2's fast refusal. Which one is right depends on whether the caller has somewhere better to go; with a load balancer and a retry, it usually has.
Debugging drills
D1. Everything is slow, and only one node is unhealthy
Two of three nodes look healthy, but users see timeouts on most requests. The unhealthy node's CPU is low.
D2. The overload alarm never fires
A service melted down under load, yet its "queue depth" metric stayed near zero throughout.
D3. Readiness flaps
During an incident, the load balancer added and removed one node many times a minute, and it kept getting bursts of traffic.
D4. The cleanup stopped running, and nothing alerted
A nightly cleanup job "succeeded" for weeks by not running at all; its dashboard showed zero failures.
Career-oriented
Interview prep
Mid-level 1: choosing a timeout
Question. "How long should the timeout on a call to the payments service be?"
How to get there. Start from what the caller can afford, then check what the callee normally needs.
Mid-level 2: 503 or 429
Question. "When should a server return 503 and when 429?"
How to get there. Whose problem is it?
Senior 1: a game day
Question. "Plan a game day for one service."
How to get there. Pick failures, predict, inject, measure, fix.
Senior 2: the per-key lock
Question. "Our service takes a lock per account while it writes. Under a slow database, everything stalls. What would you change?"
How to get there. What does the lock protect, and does it need to be held during the write?
Staff 1: overload across a fleet
Question. "Design overload protection for a fleet of services calling each other."
How to get there. Where should requests be refused, and how do callers learn about it?
Staff 2: resilience defaults in a framework
Question. "Your platform's HTTP client and concurrency limiter are used by 100 services. What defaults would you choose?"
How to get there. What happens to a team that never changes them?