System DesignVol. 12 · Part XII
0 / 0

Shelves / System Design

SD·130

Reliability Patterns

The patterns that stop failures from spreading: why failures cascade, timeouts and deadline propagation, retries done safely (idempotency, budgets, where to retry), exponential backoff with jitter, circuit breakers and their states, bulkheads and concurrency limits, rate limiting at the edge, load shedding and admission control with priorities, adaptive concurrency limits, queue-based load leveling, graceful degradation and fallbacks, hedged requests, and how to combine them with Resilience4j, Polly, Go, Python, Rust tower and Envoy/Istio.

28 topics · ~24 min read · 31-question quiz
Updated Suggest a correction

Start here: stopping one failure from becoming many

Most large outages aren't one failure; they're one failure amplified: a slow database makes callers wait, waiting callers pile up, retries multiply the load, and services that were fine run out of threads. Reliability patterns are the habits that stop that chain reaction. This chapter's experiments look at the two most common amplifiers: retries and missing deadlines.

Retries multiply

Three services in a chain, A → B → C, and C is failing (overloaded). One client request; every layer retries 3 times:

Text
every layer tries 3 times:          A saw 3, B saw 9, C saw 27 requests
only the client retries (3 tries):  A saw 3, B saw 3, C saw 3

Each layer's retries multiplied the next layer's: 3 × 3 × 3 = 27 requests hit the service that was already overloaded, for a single user action. With five layers it would be 243. The rule: retry at one layer (usually the edge, or the layer closest to the failure), use a retry budget (for example, retries may add at most 10% to normal traffic), and only retry operations that are safe to repeat.

When everyone retries at once

1,000 clients all failed at the same instant (the dependency is down for 10 seconds), then retried with different policies:

Text
fixed 1 s                       10,000 retries   busiest 100 ms: 1,000   served after recovery: at once
exponential 1, 2, 4, 8 s         4,000 retries   busiest 100 ms: 1,000   median +5.0 s
exponential + full jitter        5,277 retries   busiest 100 ms:   145   median +2.2 s

Fixed retries hammered the failing service ten times over. Exponential backoff cut the total, but every client still retried at exactly the same moments, so each wave arrived as one 1,000-request spike. Adding jitter (each client waits a random time between 0 and its backoff) spread those waves out: the busiest moment dropped from 1,000 to 145 requests per 100 ms. Spikes are what knock recovering services back over.

Deadlines: stop working for callers who have gone

The client allows 500 ms; service C takes 800 ms:

Text
no deadline propagation:  client gave up at 0.5 s; C still finished its work after the client had gone
deadline passed along in a header (X-Deadline): C checked it and abandoned the work

Without the deadline travelling with the request, every layer behind the client kept working on an answer nobody would receive, holding threads and connections that real requests needed. gRPC propagates deadlines automatically; with HTTP you pass one yourself (a header with the absolute deadline or the time remaining) and check it before expensive steps.

How deep to go in reliability patterns

Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.

Level What you can do
L1 Explain cascading failures and name timeouts, retries, breakers, bulkheads and shedding
L2 Apply timeouts, bounded retries with jitter and idempotency keys to a service's calls
L3 Explain retry amplification, budgets, deadline propagation, breaker states and adaptive concurrency
L4 Find amplification and missing timeouts in a running system with experiments and traces
L5 Design a system-wide resilience policy across layers (where to retry, budgets, shedding, fallbacks)
L6 Set resilience standards and shared libraries or meshes across an organisation

How failures cascade

In a distributed system, one slow or failing component can take down everything that depends on it:

  1. A dependency (database, downstream service, third-party API) becomes slow, not even down.
  2. Callers wait; their threads, connections or in-flight request slots fill up.
  3. Callers become slow or unresponsive to their callers, who also exhaust resources.
  4. Clients retry, multiplying load on the already-struggling dependency.
  5. Health checks fail, instances restart, caches go cold, autoscaling adds instances that also hammer the dependency…

This is a cascading failure, often with metastable behaviour: the system stays broken even after the original trigger disappears, because retries and cold caches sustain the overload. Slow is often worse than down: a dependency that fails fast frees resources immediately; one that hangs consumes them.

Reliability patterns break this chain at each step:

clients edgerate limitload sheddingadmission service A bulkhead timeout retry+jitter circuit brk fallback / degrade dep Bslow/failing queue→workers goal: fail fast, contain damage, keep the core working, recover automatically
Where reliability patterns act along a call chain. At the edge, rate limiting and load shedding keep excess traffic out. Inside the service, bulkheads and concurrency limits isolate resources per dependency; timeouts bound waiting; retries with backoff and jitter handle transient errors within a budget; circuit breakers stop calling a failing dependency; fallbacks degrade gracefully. Queues level load for asynchronous work.

Timeouts

Every network call, lock acquisition, queue wait and pool checkout needs a timeout. Without one, a hung dependency holds resources forever.

Choosing timeouts

  • Base them on the dependency's latency distribution: somewhat above its p99 (or p99.9) under normal load, so slow outliers are cut without failing healthy requests.
  • Separate connect timeout (short: tens to hundreds of milliseconds within a region) from request/read timeout (depends on the operation).
  • Make them shorter than the caller's own timeout: if the client gives up after 2 s, waiting 5 s for a database query is wasted work.
  • Configure explicitly: library defaults are often infinite or very long (Java HttpURLConnection defaults to no timeout; Go's http.DefaultClient has none; Python requests has none unless given).

Deadline propagation

Rather than independent timeouts at each hop, propagate a deadline (absolute time by which the whole request must finish). Each hop computes its remaining budget and passes it on; work is abandoned as soon as the deadline passes:

  • gRPC carries deadlines automatically (grpc-timeout header); Go's context.Context carries deadlines and cancellation through all calls.
  • For HTTP, pass a header (e.g. X-Request-Deadline or remaining milliseconds) and create contexts from it.
  • Check the deadline before expensive work (don't start a 500 ms query with 50 ms left).
// Go: deadline flows via context; every call respects it
func (h *Handler) Checkout(w http.ResponseWriter, r *http.Request) {
    ctx, cancel := context.WithTimeout(r.Context(), 800*time.Millisecond)   // total budget
    defer cancel()

    cart, err := h.carts.Get(ctx, userID(r))                 // uses remaining budget
    if err != nil { fail(w, err); return }
    quote, err := h.pricing.Quote(ctx, cart)                 // gRPC: deadline propagated automatically
    if err != nil { fail(w, err); return }
    if dl, ok := ctx.Deadline(); ok && time.Until(dl) < 100*time.Millisecond {
        http.Error(w, "timeout", http.StatusGatewayTimeout)  // not enough time to charge safely
        return
    }
    res, err := h.payments.Charge(ctx, quote)                // HTTP client with ctx
    // ...
}

var httpClient = &http.Client{
    Timeout: 2 * time.Second,                                // overall cap
    Transport: &http.Transport{
        DialContext:           (&net.Dialer{Timeout: 200 * time.Millisecond}).DialContext,
        TLSHandshakeTimeout:   300 * time.Millisecond,
        ResponseHeaderTimeout: 1500 * time.Millisecond,
        MaxIdleConnsPerHost:   100,
    },
}

Retries

When retries help and hurt

Retries recover from transient failures (a dropped connection, a brief failover, a single overloaded instance, 503/429, deadlocks, serialization failures). They hurt when:

  • The failure is permanent (400, 404, validation errors, 401/403): retrying is pointless.
  • The operation isn't idempotent: retrying a non-idempotent POST /payments after a timeout may charge twice. Retry only idempotent operations or those protected by idempotency keys (Vol. 5 ch. 74).
  • The dependency is overloaded: retries add load exactly when it can least handle it. N layers each retrying 3 times can amplify one failure into 3ᴺ requests (retry storms).

Rules for safe retries

  1. Retry only transient errors and only idempotent/idempotency-keyed operations.
  2. Limit attempts (typically 2–3 total) and respect the overall deadline.
  3. Back off exponentially with jitter (below).
  4. Retry budgets: cap retries as a fraction of total requests (e.g. retries ≤ 10% of requests per client); when the budget is exhausted, don't retry. This bounds amplification during broad outages (Envoy/Istio retry_budget, gRPC retry throttling, Finagle).
  5. Retry at one layer only: usually the layer closest to the user with context (or the client SDK), not at every hop; or use deadline-aware retries that stop when time runs out.
  6. Honour server hints: Retry-After on 429/503; gRPC status codes (UNAVAILABLE is retryable, INVALID_ARGUMENT isn't).

Backoff and jitter

Exponential backoff waits increasingly long between attempts (base × 2ᵃᵗᵗᵉᵐᵖᵗ, capped). Without randomness, clients that failed at the same moment retry at the same moments, producing synchronised waves of load. Jitter randomises delays to spread retries out (AWS Architecture Blog analysis, "Exponential Backoff and Jitter"):

Variant Delay for attempt n Notes
No jitter min(cap, base × 2ⁿ) Synchronised waves
Full jitter random(0, min(cap, base × 2ⁿ)) Best spread, fewest total calls; recommended default
Equal jitter d/2 + random(0, d/2) with d = min(cap, base × 2ⁿ) Guarantees some minimum wait
Decorrelated jitter min(cap, random(base, previous × 3)) Good spread, grows from the previous delay
no jitter: synchronised spikes 100ms200ms400ms full jitter: spread out absorbable load
Retry timing with and without jitter. Without jitter, a hundred clients that failed together retry together at 100 ms, 200 ms, 400 ms, producing synchronised spikes that can knock the recovering service over again. With full jitter, each client waits a random time up to the exponential cap, so retries spread smoothly across each window.
// Resilience4j: retry with exponential backoff + randomisation, only for transient exceptions
RetryConfig cfg = RetryConfig.custom()
    .maxAttempts(3)
    .intervalFunction(IntervalFunction.ofExponentialRandomBackoff(Duration.ofMillis(100), 2.0, 0.5))
    .retryOnException(e -> e instanceof IOException || e instanceof TransientUpstreamException)
    .ignoreExceptions(ValidationException.class)
    .build();
Retry retry = Retry.of("pricing", cfg);
Supplier<Quote> call = Retry.decorateSupplier(retry, () -> pricingClient.quote(cart));

Circuit breakers

A circuit breaker wraps calls to a dependency and tracks failures. When failures exceed a threshold, it opens and fails calls immediately (no network call) for a cool-down period, giving the dependency room to recover and freeing the caller's resources. Then it allows a few trial calls (half-open); success closes it, failure reopens it.

CLOSEDcount errors OPENfail fast / fallback HALF-OPENfew trial calls failure/slow rate ≥ threshold after wait trials succeed fail
Circuit breaker states. Closed: calls flow and failures are counted in a sliding window. When the failure or slow-call rate exceeds the threshold, it opens: calls fail fast without touching the dependency. After a wait, it goes half-open and lets a few trial calls through; if they succeed it closes, if they fail it opens again.

Design notes:

  • Count slow calls as failures too (a dependency responding in 5 s is effectively down).
  • Use a sliding window (count- or time-based) and a minimum number of calls before evaluating, to avoid opening on two failures at low traffic.
  • Scope breakers per dependency and per meaningful partition (per downstream host or endpoint), so one bad instance doesn't open the breaker for all.
  • Pair with a fallback (cached value, default, degraded response) or a clear fast error.
  • Expose breaker state as metrics and alert on transitions.
  • Service meshes provide similar protection via outlier detection (eject failing endpoints from the pool) and connection-pool limits.
Java
// Resilience4j circuit breaker + fallback (Spring Boot annotations)
@CircuitBreaker(name = "recommendations", fallbackMethod = "popularItems")
@TimeLimiter(name = "recommendations")
@Bulkhead(name = "recommendations", type = Bulkhead.Type.SEMAPHORE)
public CompletableFuture<List<Item>> recommendations(String userId) {
    return CompletableFuture.supplyAsync(() -> recsClient.forUser(userId));
}

private CompletableFuture<List<Item>> popularItems(String userId, Throwable t) {
    return CompletableFuture.completedFuture(popularCache.top(20));    // graceful degradation
}
YAML
# application.yml (Resilience4j)
resilience4j:
  circuitbreaker:
    instances:
      recommendations:
        slidingWindowType: TIME_BASED
        slidingWindowSize: 30            # seconds
        minimumNumberOfCalls: 50
        failureRateThreshold: 50         # %
        slowCallDurationThreshold: 300ms
        slowCallRateThreshold: 50
        waitDurationInOpenState: 20s
        permittedNumberOfCallsInHalfOpenState: 5
  timelimiter:
    instances:
      recommendations: { timeoutDuration: 400ms }
  bulkhead:
    instances:
      recommendations: { maxConcurrentCalls: 30, maxWaitDuration: 0 }

Bulkheads

Named after ship compartments that contain flooding, bulkheads partition resources so a failure in one area can't consume everything:

  • Per-dependency concurrency limits / pools: at most 30 concurrent calls to recommendations, 50 to payments; if recommendations hangs, only its 30 slots are stuck and checkout keeps working.
  • Separate thread pools or semaphores per dependency (Resilience4j bulkheads, Polly bulkhead policies, Hystrix historically).
  • Separate connection pools per database or per workload (OLTP vs reporting).
  • Separate instances/deployments per workload class: internal batch traffic on different pods from customer traffic; premium tenants on dedicated capacity (chapter 133).
  • Cells and shuffle sharding at the architecture level (chapter 125).

With virtual threads (Java 21+), thread pools no longer limit concurrency naturally, so explicit semaphores for downstream calls matter even more; otherwise unlimited virtual threads can overwhelm a dependency.

Go
// Go: a per-dependency bulkhead with a semaphore (golang.org/x/sync/semaphore)
type Bulkhead struct{ sem *semaphore.Weighted }

func (b *Bulkhead) Do(ctx context.Context, fn func(context.Context) error) error {
    // fail fast if no slot frees up quickly
    acquireCtx, cancel := context.WithTimeout(ctx, 10*time.Millisecond)
    defer cancel()
    if err := b.sem.Acquire(acquireCtx, 1); err != nil {
        return ErrBulkheadFull                            // shed: return fallback or 503
    }
    defer b.sem.Release(1)
    return fn(ctx)
}

Rate limiting

Rate limiting caps the request rate per client, key, tenant or endpoint, protecting capacity and enforcing fairness and quotas (algorithms in Vol. 5 ch. 76; API aspects in Vol. 10 ch. 110). In reliability terms:

  • Apply at the edge (gateway, CDN/WAF) for coarse protection, and in services for expensive operations.
  • Prefer per-client limits (fairness: one runaway client can't starve others) plus global limits protecting total capacity.
  • Return 429 with Retry-After; well-behaved clients back off.
  • Rate limits protect against expected overload patterns; load shedding handles unexpected overload.

Load shedding and admission control

When demand exceeds capacity, a server that tries to serve everything serves everyone badly: queues grow, latency explodes, timeouts trigger retries, and goodput (useful completed work) collapses. Load shedding deliberately rejects some requests early and cheaply so the rest succeed:

  • Admission control: reject at the door when the server is at its concurrency limit, CPU is saturated, or queueing time exceeds a threshold, returning 503 (or 429) fast.
  • Prioritise: classify requests (critical: checkout, login; normal; sheddable: recommendations, analytics, prefetch, batch) and shed lowest priority first. Pass priority/criticality in headers across hops so downstream services shed consistently.
  • Shed on queue time: if a request has already waited longer than the client will wait (its deadline), drop it rather than doing useless work (CoDel-style queue management; LIFO queues under overload so fresh requests succeed).
  • Shed at multiple layers: edge, gateway, service, database (statement timeouts, connection limits).
  • Client cooperation: clients back off on 503/429; fewer retries during overload (retry budgets).
Python
# Python (Starlette/FastAPI middleware sketch): concurrency-based admission control with priority
import asyncio
from starlette.responses import JSONResponse

MAX_INFLIGHT = 200
inflight = 0

async def admission(request, call_next):
    global inflight
    priority = request.headers.get("x-priority", "normal")
    limit = MAX_INFLIGHT if priority == "critical" else int(MAX_INFLIGHT * 0.8)  # keep 20% for critical
    if inflight >= limit:
        return JSONResponse({"error": "overloaded"}, status_code=503, headers={"Retry-After": "1"})
    inflight += 1
    try:
        return await call_next(request)
    finally:
        inflight -= 1

Adaptive concurrency limits

Fixed limits are hard to tune and go stale as code and hardware change. Adaptive concurrency limiting discovers the limit dynamically, inspired by TCP congestion control: measure latency (or errors) and increase the allowed concurrency while latency stays near the no-load baseline; decrease it when latency rises (queueing detected).

  • Algorithms: AIMD (additive increase, multiplicative decrease), Gradient (Netflix concurrency-limits: compares long-term and short-term RTT), Vegas.
  • Implementations: Netflix concurrency-limits (Java), Envoy's adaptive concurrency filter, Go/Rust ports, gRPC-level limiters.

Benefits: the server protects itself without manual tuning, and shedding begins at the right point automatically.

Queue-based load leveling

Put a queue between producers and a consumer whose capacity is limited, so bursts are absorbed as backlog and processed at a steady rate (chapter 128):

  • Works for work that can be asynchronous (accept now, process soon): order fulfilment, notifications, imports, webhooks, video processing.
  • The consumer runs at its sustainable throughput; autoscale on queue depth/age.
  • Bound the queue (or monitor age) and define behaviour when it's too long: reject new work, degrade, or inform users of delays.
  • Keep latency SLOs for asynchronous work too (e.g. "95% of notifications delivered within 30 s").

Graceful degradation and fallbacks

Design the product so that losing a non-critical dependency reduces functionality instead of failing entirely:

Dependency down Degraded behaviour
Recommendations Show popular or recently viewed items
Personalised pricing Show standard price
Reviews service Hide reviews section
Search Show category browsing; serve cached results
Payment provider A Fail over to provider B; or accept order and capture later (if the business allows)
Inventory service (read) Show "availability confirmed at checkout"
Feature flag service Use last-known flags / safe defaults (static stability)
Analytics/telemetry pipeline Drop or buffer locally; never block the request

Techniques: fallbacks in code (above), stale caches (stale-if-error), feature flags to switch off expensive features ("kill switches") during incidents, brownout modes that reduce optional work under load, static fallback pages served from the CDN.

Identify critical paths (what must work: browse, cart, checkout, login) and make every other dependency optional on those paths. Test fallbacks regularly (chaos experiments, Vol. 11 ch. 120): an untested fallback often fails when needed.

Hedged requests

For latency-critical reads with variable tail latency, a hedged request sends a second copy of a request to another replica if the first hasn't responded within (say) the p95 latency, and uses whichever response arrives first, cancelling the other. Google's "The Tail at Scale" showed this cuts tail latency dramatically for a few percent more load. Use only for idempotent reads, cap the hedging rate, and avoid it when the system is overloaded (it adds load). gRPC supports hedging policies natively.

Combining patterns

Order matters when composing (from the outside in, typical for a client call):

  1. Bulkhead / concurrency limit: don't even start if too many calls are in flight.
  2. Circuit breaker: fail fast if the dependency is known bad.
  3. Retry (with backoff, jitter, budget), each attempt guarded by:
  4. Timeout per attempt, all within the overall deadline.
  5. Fallback if everything fails.

Libraries and platforms:

Ecosystem Tools
Java Resilience4j (retry, circuit breaker, bulkhead, rate limiter, time limiter), Spring Cloud Circuit Breaker, Failsafe, Netflix concurrency-limits
.NET Polly v8 resilience pipelines, Microsoft.Extensions.Http.Resilience
Go context deadlines, sony/gobreaker, failsafe-go, x/time/rate, x/sync/semaphore, gRPC retry/hedging config
Python tenacity, pybreaker, aiolimiter, asyncio.timeout
Rust tower middleware (timeout, retry with budgets, limit::ConcurrencyLimit, load_shed, buffer), backon, governor
Node.js cockatiel, opossum, p-retry, AbortSignal.timeout()
Platform Envoy/Istio/Linkerd: timeouts, retries with budgets, outlier detection, circuit-breaking thresholds, local/global rate limits, adaptive concurrency; API gateways
Rust
// Rust tower: compose load shedding, concurrency limit, timeout and retry around a client service
use tower::{ServiceBuilder, timeout::TimeoutLayer, limit::ConcurrencyLimitLayer, load_shed::LoadShedLayer};
let svc = ServiceBuilder::new()
    .layer(LoadShedLayer::new())                         // reject immediately when not ready
    .layer(ConcurrencyLimitLayer::new(64))               // bulkhead
    .layer(TimeoutLayer::new(std::time::Duration::from_millis(500)))
    .service(pricing_client);
YAML
# Istio: timeouts, bounded retries and outlier detection (circuit breaking) for the pricing service
apiVersion: networking.istio.io/v1
kind: VirtualService
metadata: { name: pricing }
spec:
  hosts: ["pricing"]
  http:
    - route: [{ destination: { host: pricing } }]
      timeout: 800ms
      retries: { attempts: 2, perTryTimeout: 300ms, retryOn: "5xx,reset,connect-failure,unavailable" }
---
apiVersion: networking.istio.io/v1
kind: DestinationRule
metadata: { name: pricing }
spec:
  host: pricing
  trafficPolicy:
    connectionPool:
      tcp: { maxConnections: 200 }
      http: { http2MaxRequests: 500, maxRequestsPerConnection: 0 }
    outlierDetection:
      consecutive5xxErrors: 5
      interval: 10s
      baseEjectionTime: 30s
      maxEjectionPercent: 50

Beware double configuration: retries in the application and in the mesh multiply (2 × 3 = 6 attempts); timeouts in the mesh shorter than in the app produce confusing errors. Decide which layer owns which pattern.

Testing and observing reliability patterns

  • Unit and integration tests with fault injection (Vol. 11 ch. 115, 120): hanging dependencies, error bursts, slow responses.
  • Load tests beyond capacity to verify shedding keeps goodput high (Vol. 11 ch. 119).
  • Metrics: timeouts, retries (and retry ratio), breaker state changes, bulkhead rejections, shed requests by priority, queue age; dashboards showing them next to latency and error SLIs.
  • Review incidents for missing or misconfigured patterns: most postmortems of cascading failures cite a missing timeout, unbounded retries, or a shared resource without a bulkhead.

Lab: retry amplification, jitter and deadlines

Three Python HTTP services on the lab machine chained A → B → C, each calling the next with configurable attempts and optional deadline propagation, plus a discrete simulation of 1,000 clients retrying against an outage. Volume 9's chapter 104 measured circuit breakers and bulkheads; this lab covers the patterns around them.

Experiment 1: retries multiply down a chain

Python
def call(url, attempts, deadline=None):
    for i in range(attempts):
        try: return urlopen(Request(url, headers=hdr), timeout=…).read()
        except (HTTPError, URLError, TimeoutError, OSError):
            if i == attempts - 1: raise
Policy A B C Amplification at C
every layer 3 attempts 3 9 27 27×
only the client retries 3 3 3 3×

In a real fleet the same multiplication happens per request across thousands of requests per second, so an overloaded C sees 27× its normal traffic exactly when it can handle least. Google's SRE guidance (retry at one layer, per-client retry budget of about 10%, and a server-side signal such as "overloaded; don't retry" that clients obey) exists because of this table. gRPC's retry policy supports throttling by token bucket for the same reason; Envoy has retry budgets (retry_budget) per cluster.

Experiment 2: backoff and jitter

1,000 clients fail at t = 0; the dependency recovers at t = 10 s; up to 8 s between attempts:

Policy Retries Busiest 100 ms Served after recovery (median / last)
fixed 1 s 10,000 1,000 +0.0 s / +0.0 s
exponential 1, 2, 4, 8 s 4,000 1,000 +5.0 s / +5.0 s
exponential + full jitter 5,277 145 +2.2 s / +7.7 s

The trade-off is visible: fixed retries recover fastest but put ten times the load on the failing service; backoff without jitter keeps the load down on average but in synchronised spikes; full jitter (sleep = random(0, min(cap, base × 2^n)), from the AWS Architecture Blog's analysis) spreads the spikes at the cost of a longer tail for unlucky clients. Decorrelated jitter (sleep = min(cap, random(base, previous × 3))) is a common middle ground. This is a simulation; to see the same thing for real, rerun it against the chapter 123 kitchen service behind Toxiproxy and plot request rate per 100 ms.

Experiment 3: deadline propagation

Setup Client Work done by C after the client gave up
client 500 ms, C takes 800 ms, no propagation TimeoutError at 0.5 s 1 (finished uselessly)
deadline passed in X-Deadline, C checks it TimeoutError 0

In this simple version C still slept its 800 ms before checking; real services check the deadline before starting expensive steps and pass the remaining time as the timeout of their own downstream calls (so B would have called C with at most ~500 ms minus its own elapsed time). In Go, context.WithDeadline carries it through every call; in Java, gRPC's Context and Deadline; in Python, asyncio.timeout() plus an explicit header across HTTP hops.

Experiment 4: putting the patterns together

Pattern Stops Lab where it's measured
timeouts / deadlines waiting forever, wasted work this lab; Vol 11 ch 120
retries with backoff, jitter, budget transient errors, without amplification this lab
idempotency keys duplicate effects on retry ch 121; Vol 11 ch 116
circuit breaker hammering a dependency that is down Vol 9 ch 104
bulkheads one slow dependency exhausting all threads Vol 9 ch 104
load shedding / admission control overload collapse Vol 9 ch 105
fallbacks / degradation total failure when partial service is possible Vol 11 ch 120

Try it yourself

  1. Add a retry budget to the chain (a token bucket allowing retries up to 10% of requests) and rerun Experiment 1 with 100 client requests.
  2. Make B call C with timeout = deadline − now − 50 ms and measure how much earlier B fails than without it.
  3. Implement decorrelated jitter in the simulation and compare peak load and recovery tail with full jitter.
  4. Add a Retry-After response from C when overloaded and make clients honour it; measure total retries.

Revision sheet: reliability patterns

Key ideas

  • Cascading failure: slowness → queueing → resource exhaustion → more failures; retries and missing timeouts amplify it.
  • Timeouts on every remote call, derived from latency requirements; deadlines propagated end to end.
  • Retries: only idempotent operations; one layer; exponential backoff with jitter; caps; retry budgets; honour Retry-After and "don't retry" signals.
  • Circuit breakers: closed → open (fail fast) → half-open (probe); per dependency.
  • Bulkheads: separate pools/concurrency limits per dependency or tenant.
  • Load shedding and admission control: reject early (429/503) when over capacity; prioritise important traffic; adaptive concurrency limits.
  • Fallbacks and graceful degradation: cached or default answers, feature shedding; mark degraded responses.
  • Idempotency: keys for writes; makes retries and redelivery safe.

Numbers to remember

  • Lab: 3 attempts at each of 3 layers → 27 requests at the bottom; retrying only at the edge → 3.
  • Simulation: full jitter cut the busiest 100 ms from 1,000 to 145 requests.
  • Common retry budget: about 10% extra load.

Pitfalls

  • Default timeouts of 30–60 s or none at all.
  • Retries at every layer; retrying non-idempotent writes.
  • Backoff without jitter; unlimited retries.
  • Breakers or bulkheads shared across unrelated dependencies.
  • Fallbacks that hide outages from monitoring.
  • Health checks that cascade failures (restarting healthy instances).

Glossary

  • Retry amplification: retries multiplying load across layers.
  • Full / decorrelated jitter: randomised backoff schemes.
  • Retry budget: limit on retries relative to normal traffic.
  • Half-open: breaker state allowing trial requests.
  • Adaptive concurrency: limits that adjust to observed latency (e.g. Netflix's concurrency-limits, Envoy's adaptive concurrency filter).