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

TimeoutWhat it limitsExample
ConnectTCP/TLS establishment200 ms to open socket
Request / readWaiting for response bytes800 ms for JSON body
IdleGap between chunks on a long stream30 s between SSE events
End-to-end deadlineTotal user-visible wait4 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).

StepBudget
Network in + out~200 ms
Auth + validation100 ms
Inventory reserve800 ms (timeout 700 ms)
Payment authorize1,500 ms (timeout 1,200 ms)
Order persist400 ms
Async email enqueue50 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 safelyDo not retry
GET, HEAD (reads)400 Bad Request, 401, 403, 404
PUT with same body to same URL409 conflict you can't resolve
POST/DELETE with idempotency key (see lesson 04)Payment charge without dedup
408, 429 (with Retry-After), 502, 503, 504Unknown side effect already applied
Connect timeouts on idempotent opsError body says "duplicate"

429 Too Many Requests: honor Retry-After header; blind retries punish a rate-limited service.

How many retries?

ContextTypical policy
User-facing sync API0–2 retries, tight total deadline
Internal service-to-service2–3 retries with backoff
Background worker / queueMore attempts β†’ then DLQ
Payment / ledger0–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
PatternFormula (conceptual)Use when
Fixed delayalways 200 msRarely β€” still herds
Exponentialbase Γ— 2^attemptDefault for most retries
Exponential + jitterrandomize the waitAlways in multi-client systems
Decorrelated jitterrandom(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
LayerResponsibility
ClientGenerate key once per logical action; reuse on retry
APIDedup on key before side effects
DBUnique 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.

StateBehaviorUser impact
ClosedNormal trafficFull features
OpenImmediate fallback / errorDegraded but fast
Half-openOne or few probe requestsTesting recovery

Typical thresholds (starting points)

SettingExample valueTune by
Failure rate to open50% over last 20 callsSLO, dependency criticality
Cooldown before half-open30 sRecovery time of dependency
Probes in half-open3–5 requestsConfidence 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

DependencyFallback when breaker open
RecommendationsOmit block; show core feed
Product reviews"Reviews temporarily unavailable"
Fraud scoringFail closed (block) or fail open (risky) β€” business decision
Payment gatewayNever 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.

ImplementationBulkhead idea
Separate thread poolsJVM / .NET executors
Separate deploymentsK8s: payments vs recs pods
Connection pool limitsMax 20 conns to legacy monolith
SemaphoresMax 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
ProsCons
Cuts tail latencyDoubles load at exactly the worst time
Helps read-heavy, idempotent pathsDangerous 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:

PolicyEffect
Max 2 retries total downstreamPrevents exponential fan-out
Retry only on connect, not on 500Avoids retry storms on logic bugs
Prefer async + DLQ for long recoveryKeeps sync path fast

Link to lesson 14: deep call graphs need stricter resilience, not more retries.


End-to-end example β€” checkout

StepPattern
InventoryShort timeout, 1 retry with jitter, breaker if 503 sustained
PaymentIdempotency key, max 1 retry, no breaker that returns fake success
EmailAsync queue β€” failure goes to DLQ, not user-facing error
Recommendations on same page200 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

MistakeBetter
One global 30 s timeout everywhereLayered timeouts matched to latency budget
Retry every 500 error including 400Retry only transient + safe operations
Retry POST payments without idempotency keyIdempotency key or at-most-once
No jitter β€” all clients retry togetherExponential backoff + full jitter
Circuit breaker open β†’ return fake payment successBusiness-safe fallback or explicit error
Infinite retries in sync APICap 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