16. Retries, Timeouts & Resilience Patterns
Big picture: Distributed systems fail all the time β packets drop, pods restart, databases spike. Resilience patterns decide whether a blip becomes a slow page or a site-wide outage. This lesson teaches the toolkit: timeouts, retries, circuit breakers, bulkheads, and when to use each.
Lesson 15 introduced these ideas alongside security and observability. This lesson goes deep β with decision trees, numbers, and interview-ready phrases.
Prerequisites: 04. Clients, Servers & APIs (idempotency), 12. Queues & Async Processing (DLQ), 15. Reliability, Security & Observability, 06. HTTP & the Network Path (RTT, latency budget)
Read next: 17. Authentication & Authorization β sessions, JWT, OAuth, and where auth checks live.
Learning goals
By the end of this lesson you will be able to:
- Set a timeout hierarchy so inner calls fail before the user gives up
- Decide when to retry and when retries make things worse
- Combine idempotency keys with safe retries on writes
- Use exponential backoff + jitter to avoid thundering herds
- Explain circuit breaker states and when to open the breaker
- Isolate failures with bulkheads and optional hedging
- Reason about retry budgets in microservice call chains
- Place resilience patterns correctly in an HLD diagram
The failure cascade (why this matters)
One slow dependency can stall every thread, queue, and connection pool upstream.
Without resilience: every caller waits forever, retries at once, and amplifies load on the already-sick dependency.
With resilience: fail fast, retry selectively, stop calling dead dependencies, protect critical pools.
Interview phrase: "I'd set aggressive internal timeouts, retry only idempotent or deduplicated operations, and open a circuit breaker so we degrade instead of cascading."
Timeouts β fail fast, fail in order
A timeout is a promise: "If I don't get an answer in X ms, I stop waiting and handle failure."
Timeout hierarchy (golden rule)
Inner timeouts must be shorter than outer ones. Leave slack for retries, fallbacks, and serialization.
User-facing deadline: 5,000 ms (mobile app gives up)
API gateway: 4,000 ms
Service A: 2,500 ms
Service B call: 800 ms
DB query: 500 ms
If the DB query waits 3 seconds while the user deadline is 5 seconds, you've burned the entire budget on one hop β no room for retries or a fallback UI.
Types of timeouts
| Timeout | What it limits | Example |
|---|---|---|
| Connect | TCP/TLS establishment | 200 ms to open socket |
| Request / read | Waiting for response bytes | 800 ms for JSON body |
| Idle | Gap between chunks on a long stream | 30 s between SSE events |
| End-to-end deadline | Total user-visible wait | 4 s checkout API |
Deadline propagation
Pass a deadline (absolute timestamp) or remaining budget downstream:
Gateway receives request at T=0, budget 4000 ms
β calls Service A with header: X-Deadline: T+4000
β Service A has 2500 ms left after auth
β Service A calls B with 800 ms max (not a fresh 2500 ms)
Why: Without propagation, each hop thinks it has the full client timeout and the chain silently exceeds the user's patience.
Worked example β latency budget
Checkout API, user deadline 5 s, RTT to API 100 ms (see lesson 06).
| Step | Budget |
|---|---|
| Network in + out | ~200 ms |
| Auth + validation | 100 ms |
| Inventory reserve | 800 ms (timeout 700 ms) |
| Payment authorize | 1,500 ms (timeout 1,200 ms) |
| Order persist | 400 ms |
| Async email enqueue | 50 ms (best-effort) |
| Slack for retries/fallback | ~1,950 ms |
If payment routinely needs 2 s, don't set a 5 s timeout and hope β shorten inventory, async what you can, or return "processing" and poll.
Retries β when they help vs hurt
A retry repeats a failed operation, hoping the failure was transient (network blip, pod restart, brief overload).
Retry decision tree
Retry safely vs never
| Retry safely | Do not retry |
|---|---|
| GET, HEAD (reads) | 400 Bad Request, 401, 403, 404 |
| PUT with same body to same URL | 409 conflict you can't resolve |
| POST/DELETE with idempotency key (see lesson 04) | Payment charge without dedup |
| 408, 429 (with Retry-After), 502, 503, 504 | Unknown side effect already applied |
| Connect timeouts on idempotent ops | Error body says "duplicate" |
429 Too Many Requests: honor Retry-After header; blind retries punish a rate-limited service.
How many retries?
| Context | Typical policy |
|---|---|
| User-facing sync API | 0β2 retries, tight total deadline |
| Internal service-to-service | 2β3 retries with backoff |
| Background worker / queue | More attempts β then DLQ |
| Payment / ledger | 0β1 with idempotency key only |
Rule of thumb: Each retry multiplies load. Three retries Γ 10,000 QPS = up to 40,000 attempts on a dependency that may already be drowning.
Exponential backoff and jitter
Exponential backoff: wait longer after each failure so a recovering service gets breathing room.
base = 100 ms, multiplier = 2, max = 5 s
attempt 1 fail β wait 100 ms
attempt 2 fail β wait 200 ms
attempt 3 fail β wait 400 ms
attempt 4 fail β wait 800 ms
β¦ cap at 5 s
Full jitter (common in AWS / Google patterns): pick a random delay in [0, current_backoff] so retries don't align.
without jitter: 10,000 clients all retry at T+400 ms β second spike
with jitter: spread across T+0 β¦ T+400 ms β smoother
| Pattern | Formula (conceptual) | Use when |
|---|---|---|
| Fixed delay | always 200 ms | Rarely β still herds |
| Exponential | base Γ 2^attempt | Default for most retries |
| Exponential + jitter | randomize the wait | Always in multi-client systems |
| Decorrelated jitter | random(base, prevΓ3) | High-scale clients |
Thundering herd
When a dependency recovers, everyone retrying at once can knock it over again.
Fix: jitter + circuit breaker + rate limits on the caller side.
Idempotency + retry (writes that must not double-charge)
Retries on POST without deduplication can create two orders or charge twice.
Pattern: client sends Idempotency-Key: uuid-v4 on the first attempt; server stores (key β result) for 24β72 hours.
Attempt 1: POST /pay Idempotency-Key: abc-123 β timeout (unknown result)
Attempt 2: POST /pay Idempotency-Key: abc-123 β server returns same receipt, no second charge
| Layer | Responsibility |
|---|---|
| Client | Generate key once per logical action; reuse on retry |
| API | Dedup on key before side effects |
| DB | Unique constraint on idempotency key or business id |
Interview phrase: "Retries are safe only with idempotency keys or naturally idempotent verbs β otherwise I use at-most-once or outbox + async settlement."
Circuit breaker β stop hammering the sick dependency
A circuit breaker tracks recent failures. When too many fail, it opens and fails fast without calling the dependency.
| State | Behavior | User impact |
|---|---|---|
| Closed | Normal traffic | Full features |
| Open | Immediate fallback / error | Degraded but fast |
| Half-open | One or few probe requests | Testing recovery |
Typical thresholds (starting points)
| Setting | Example value | Tune by |
|---|---|---|
| Failure rate to open | 50% over last 20 calls | SLO, dependency criticality |
| Cooldown before half-open | 30 s | Recovery time of dependency |
| Probes in half-open | 3β5 requests | Confidence vs risk |
Analogy: A home circuit breaker trips when wiring overheats β you don't keep flipping it every second; you wait, then test carefully.
Fallback when open
| Dependency | Fallback when breaker open |
|---|---|
| Recommendations | Omit block; show core feed |
| Product reviews | "Reviews temporarily unavailable" |
| Fraud scoring | Fail closed (block) or fail open (risky) β business decision |
| Payment gateway | Never fake success β queue or show retry UI |
Bulkhead β don't let one leak sink the ship
A bulkhead isolates resource pools so one slow or failing dependency can't exhaust all threads, connections, or CPU.
Thread pool β payments: 50 threads
Thread pool β recommendations: 20 threads
HTTP client pool β inventory: 30 connections max
If recommendations hang, payments still have their own 50 threads.
| Implementation | Bulkhead idea |
|---|---|
| Separate thread pools | JVM / .NET executors |
| Separate deployments | K8s: payments vs recs pods |
| Connection pool limits | Max 20 conns to legacy monolith |
| Semaphores | Max 5 concurrent calls to fragile API |
vs rate limiting: rate limiting caps requests per second; bulkhead caps concurrent in-flight work and resource sharing.
Hedging (awareness β use sparingly)
Hedging: after a primary call is slow, send a duplicate request to another replica; take whichever answers first.
T=0: call replica A
T=300: no response β hedge: also call replica B
T=320: B responds β cancel A if possible
| Pros | Cons |
|---|---|
| Cuts tail latency | Doubles load at exactly the worst time |
| Helps read-heavy, idempotent paths | Dangerous on writes |
Interview phrase: "I'd hedge only for idempotent reads with strict tail-latency SLOs β and only if the backend can absorb the extra QPS."
Most designs prefer timeouts + good replicas + cache over hedging.
Retry budgets in call chains
In microservices, retries multiply across hops.
1 user request β Service A retries B 3Γ β B retries C 3Γ
Worst case: 1 Γ 3 Γ 3 = 9Γ load on C from ONE user action
A retry budget caps total retry attempts (or extra latency) per incoming request:
| Policy | Effect |
|---|---|
| Max 2 retries total downstream | Prevents exponential fan-out |
| Retry only on connect, not on 500 | Avoids retry storms on logic bugs |
| Prefer async + DLQ for long recovery | Keeps sync path fast |
Link to lesson 14: deep call graphs need stricter resilience, not more retries.
End-to-end example β checkout
| Step | Pattern |
|---|---|
| Inventory | Short timeout, 1 retry with jitter, breaker if 503 sustained |
| Payment | Idempotency key, max 1 retry, no breaker that returns fake success |
| Async queue β failure goes to DLQ, not user-facing error | |
| Recommendations on same page | 200 ms timeout, breaker open β hide widget |
Where this lives in an HLD
When you draw diagrams in lesson 20, annotate:
- Timeouts on every external arrow
- Sync vs async (queue for non-critical)
- Fallback when breaker open
- Idempotency on write paths
Check your understanding
1. Why must the DB query timeout be shorter than the API gateway timeout?
So inner failures surface before the outer layer exhausts the user's deadline. That leaves time for retries, fallbacks, or a clear error instead of hanging until the client disconnects.
2. A POST /transfer returns 503 after 30 s. Should the client retry immediately five times?
No. First check idempotency β without a dedup key, retries risk double transfer. Use bounded retries with backoff + jitter, honor Retry-After on 429, and prefer a single logical retry with the same idempotency key for writes.
3. Circuit breaker is open on the recommendations service. What should the product do?
Fail fast β skip recommendations and render the core page. Do not block checkout or feed loading waiting for recs. Metrics should show breaker state; alerts fire if open too long.
4. What's the difference between a bulkhead and a circuit breaker?
Bulkhead limits shared resources (threads, connections) so one dependency can't starve others. Circuit breaker stops calling a dependency that is failing at high rate. Use both: bulkhead prevents local exhaustion; breaker stops remote overload.
Common beginner mistakes
| Mistake | Better |
|---|---|
| One global 30 s timeout everywhere | Layered timeouts matched to latency budget |
| Retry every 500 error including 400 | Retry only transient + safe operations |
| Retry POST payments without idempotency key | Idempotency key or at-most-once |
| No jitter β all clients retry together | Exponential backoff + full jitter |
| Circuit breaker open β return fake payment success | Business-safe fallback or explicit error |
| Infinite retries in sync API | Cap attempts; async + DLQ for long recovery |
| "We'll add resilience later" | Design timeouts on every dependency arrow in HLD |
Recap
- Timeouts in layers β inner shorter than outer; propagate deadlines.
- Retries only for transient, safe operations; cap count and total time.
- Backoff + jitter prevents thundering herds after outages.
- Idempotency keys make write retries safe.
- Circuit breaker fails fast and protects sick dependencies.
- Bulkhead isolates pools; hedging is rare and read-only.
- Retry budgets matter in deep microservice graphs β retries multiply load.
Previous: 15. Reliability, Security & Observability
Next: 17. Authentication & Authorization