In a distributed system, partial failure is normal: some dependency is always slow, restarting or overloaded. Resilience patterns contain the damage. Timeouts bound how long you wait, retries with backoff absorb transient faults, circuit breakers stop hammering a sick dependency, bulkheads keep one failure from sinking everything, and graceful degradation keeps the core experience working. The simulation above shows a circuit breaker reacting to a failing dependency.
Think of it like
The electrical system in your house
When an appliance shorts out, a breaker trips and cuts power to that one circuit, instead of letting the wiring overheat and burn the house down. The kitchen and bedrooms are on separate circuits (bulkheads), so a fault in one leaves the lights on elsewhere. After a while you flip the breaker back to test whether the fault is gone (half-open). And a backup generator keeps the fridge running during an outage (fallback).
Why failures cascade
A dependency that is slow is often more dangerous than one that is down. A dead service fails fast; a slow one holds your threads, connections and memory hostage while callers pile up behind it.
- 1
A dependency slows down
The database's p99 latency jumps from 20 ms to 2 s because of a bad query plan.
- 2
Resources pile up
Every request now holds a worker thread 100 times longer. A pool of 200 threads is exhausted within seconds.
- 3
Callers time out and retry
Upstream services and users see timeouts and retry, adding even more load to the struggling system.
- 4
Retries multiply
With three layers each retrying three times, one user click becomes up to 27 calls to the database.
- 5
The blast radius spreads
Unrelated endpoints that share the same thread pool stall too. The whole site is down because of one slow query.
Timeouts
Every network call needs a timeout, and the defaults are often dangerous: Python's requests waits forever unless you pass timeout, and Java's HttpURLConnection defaults to an infinite read timeout. A missing timeout turns a slow dependency into a hung caller.
- Connect vs read timeouts: connecting should take milliseconds inside a data center; reading depends on the operation. Set both.
- Base them on data: start slightly above the dependency's p99.9 latency, not on a round number like 30 s.
- Propagate deadlines: if the user-facing request has 1 s left, pass the remaining budget downstream (gRPC deadlines do this) so nobody keeps working on a request the user has abandoned.
- Budget across retries: the total time across all attempts must fit within the caller's own timeout.
Retries with exponential backoff and jitter
Many failures are transient: a dropped connection, a leader election, a brief overload. Retrying fixes them, but only if you retry the right errors and spread retries out so they don't become an attack on a struggling service.
Retry these
- Connection resets and timeouts
503 Service Unavailable,502,504429 Too Many Requests(honorRetry-After)- Only for idempotent operations, or with an idempotency key
Never retry these
400 Bad Request,401,403,404,422: they will fail again- Non-idempotent writes without an idempotency key (double charges)
- Errors that indicate the callee is overloaded, without backoff
- Anything once the caller's deadline has passed
| Attempt | Ceiling (base 100 ms, cap 10 s) | Actual sleep with full jitter |
|---|---|---|
| 0 | 100 ms | uniform in 0 to 100 ms |
| 1 | 200 ms | uniform in 0 to 200 ms |
| 2 | 400 ms | uniform in 0 to 400 ms |
| 3 | 800 ms | uniform in 0 to 800 ms |
| 4 | 1.6 s | uniform in 0 to 1.6 s |
| 7 | 10 s (capped) | uniform in 0 to 10 s |
Retry budgets and amplification
- Retry at one layer, usually the one closest to the failing dependency, and make the others fail fast.
- Cap attempts per request: Google's SRE book suggests at most three attempts per request.
- Use a retry budget per client: for example, retries may be at most 10% of total requests. When the budget is spent, stop retrying: the dependency is clearly not having a transient blip. Linkerd and gRPC's retry throttling implement this.
- Make retried operations idempotent so a retry after an ambiguous timeout is safe. See Idempotency & Delivery Guarantees.
Circuit breaker
Popularized by Michael Nygard's Release It!, a circuit breaker wraps calls to a dependency and tracks their outcomes. When failures cross a threshold it opens and fails calls immediately, without touching the dependency, giving it room to recover and freeing the caller's resources. The simulation above lets you push a dependency into failure and watch the breaker move between its three states.
| State | Behavior | Transition |
|---|---|---|
| Closed | Calls pass through; outcomes are recorded in a sliding window | Failure rate (or slow-call rate) above threshold, with enough calls in the window → Open |
| Open | Calls fail immediately (or go to a fallback); the dependency gets no traffic | After a wait duration (say 30 s) → Half-open |
| Half-open | A limited number of trial calls are allowed through | Trials succeed → Closed; any trial fails → Open again |
resilience4j:
circuitbreaker:
instances:
recommendations:
slidingWindowType: COUNT_BASED
slidingWindowSize: 50
minimumNumberOfCalls: 20
failureRateThreshold: 50 # % failed calls that opens the breaker
slowCallDurationThreshold: 2s
slowCallRateThreshold: 80 # slow calls can open it too
waitDurationInOpenState: 30s
permittedNumberOfCallsInHalfOpenState: 5
bulkhead:
instances:
recommendations:
maxConcurrentCalls: 20 # at most 20 in-flight calls to this dependency
maxWaitDuration: 0ms # reject immediately when full
timelimiter:
instances:
recommendations:
timeoutDuration: 300msBulkheads
Ships are divided into watertight compartments so a hull breach floods one section, not the whole vessel. In software, a bulkhead gives each dependency (or class of work) its own bounded pool of threads, connections or concurrency permits. When one dependency hangs, it can exhaust only its own pool.
One shared pool
- 200 threads serve calls to Payments, Search and Recommendations
- Recommendations hangs; all 200 threads end up waiting on it
- Checkout fails even though Payments is perfectly healthy
Bulkheaded pools
- Payments 100, Search 60, Recommendations 40 threads (or semaphores)
- Recommendations hangs; only its 40 slots fill up and extra calls are rejected
- Checkout and search keep working normally
The same idea scales up: separate connection pools per tenant, separate clusters for critical and batch workloads, and cell-based architectures that split a whole service into independent cells, each serving a slice of customers, so one bad deploy or poison request affects only one cell.
Load shedding and rate limiting
When demand exceeds capacity, a server that tries to serve everyone ends up serving no one well: latencies soar and every request times out. Load shedding deliberately rejects excess work early and cheaply (503 or 429) so the remaining requests succeed.
- Shed on a real signal: in-flight requests, queue wait time or CPU, not just a fixed requests-per-second limit.
- Prioritize: drop prefetches and analytics before checkout and login. Tag requests with a criticality level at the edge.
- Reject early: refuse work at the front door, before it has consumed database connections and downstream calls.
- Adaptive concurrency limits (such as Netflix's concurrency-limits library) adjust the limit automatically from observed latency, like TCP congestion control.
- Rate limit per client to protect against abusive or buggy callers. See Rate Limiting.
Fallbacks and graceful degradation
Decide in advance what each feature does when its dependency is unavailable. The goal is to keep the core of the product working while non-essential parts degrade.
| Feature | Normal | Degraded fallback |
|---|---|---|
| Recommendations | Personalized model output | Cached best-sellers for the category |
| Search | Live index with personalization | Unpersonalized results, or a cached results page |
| Reviews | Live ratings and comments | Hide the section |
| Pricing | Real-time dynamic price | Last known price with a short TTL |
| Payments | Synchronous authorization | No silent fallback: fail clearly, or queue for later only if the business accepts the risk |
Health checks and backpressure
- Liveness: "Is this process stuck?" Failing it gets the instance restarted. Keep it shallow and dependency-free.
- Readiness: "Should I receive traffic?" Failing it removes the instance from load balancing (during startup, cache warming or shutdown draining).
- Startup probes: give slow-starting apps time to boot before liveness checks begin.
Backpressure is how a slow consumer tells a fast producer to slow down. TCP flow control does it with window sizes, Reactive Streams with request(n), and pull-based consumers (Kafka) by fetching only what they can handle. The anti-pattern is an unbounded queue: it hides overload by turning it into ever-growing latency and, eventually, an out-of-memory crash. Bound every queue and decide what happens when it is full: block, drop, or reject.
Chaos engineering
You only know your resilience patterns work if you see them work. Chaos engineering, pioneered by Netflix with Chaos Monkey (randomly terminating production instances), runs controlled experiments that inject real-world failures.
- 1
Define steady state
Pick a business metric that shows the system is healthy, such as successful checkouts per minute.
- 2
Form a hypothesis
"If one Recommendations instance dies, checkout success stays within 1% of normal."
- 3
Inject a real failure
Kill instances, add latency, drop packets, fill a disk, or fail an availability zone (Gremlin, AWS Fault Injection Service, Chaos Mesh, LitmusChaos).
- 4
Limit the blast radius
Start in staging or with a small slice of production traffic, with an abort button.
- 5
Learn and automate
Fix what broke, then run the experiment continuously so regressions are caught. Game days rehearse larger scenarios with the on-call team.
Putting it together
| Pattern | Protects against | Key setting | Classic mistake |
|---|---|---|---|
| Timeout | Hung or slow dependencies | Slightly above p99.9 | No timeout, or one longer than the caller's |
| Retry + backoff + jitter | Transient faults | ≤ 3 attempts, retry budget | Retrying non-idempotent calls or at every layer |
| Circuit breaker | Hammering a failing dependency | Failure-rate threshold, wait duration | Counting 4xx as failures; no minimum call count |
| Bulkhead | One dependency exhausting shared resources | Per-dependency pool size | One giant shared thread pool |
| Load shedding | Overload collapse | Concurrency or queue-time limit | Queuing everything without bound |
| Fallback | Total feature loss | Cached or default response | Fallback that calls another fragile service |
Implementation
Retries only transient errors, with a randomized delay that grows exponentially up to a cap.
import random
import time
from typing import Callable, TypeVar
T = TypeVar("T")
class TransientError(Exception):
"""Raise for failures worth retrying: timeouts, 503s, connection resets."""
def retry_with_backoff(
op: Callable[[], T],
max_attempts: int = 4,
base_delay: float = 0.1,
max_delay: float = 10.0,
) -> T:
for attempt in range(max_attempts):
try:
return op()
except TransientError:
if attempt == max_attempts - 1:
raise # out of attempts: surface the error
# Full jitter: sleep a random time in [0, min(cap, base * 2^attempt)]
ceiling = min(max_delay, base_delay * (2 ** attempt))
time.sleep(random.uniform(0, ceiling))
raise AssertionError("unreachable")Key takeaways
- Slow dependencies are more dangerous than dead ones: by Little's law, latency spikes multiply the resources held by in-flight requests.
- Every network call needs a timeout, ideally a propagated deadline that fits within the caller's own budget.
- Retry only transient errors on idempotent operations, with exponential backoff, full jitter, a small attempt cap and a retry budget.
- Circuit breakers move between closed, open and half-open to fail fast and give a failing dependency room to recover.
- Bulkheads, load shedding and backpressure keep overload contained; fallbacks keep the core product working while extras degrade.
- Prove it works: chaos experiments exercise failure paths before real outages do.
Common pitfalls
- Calling remote services with library defaults that never time out.
- Retrying at every layer without jitter or budgets, turning a blip into a self-inflicted outage.
- Retrying non-idempotent operations such as payments without an idempotency key.
- Sharing one thread or connection pool across all dependencies, so one slow service starves the rest.
- Writing fallbacks that are never tested, or that depend on yet another fragile remote call.
Interview tips
- For every synchronous arrow in your design, state the timeout, retry policy and what happens when the call fails.
- Explain the circuit breaker's three states and transitions crisply, including why half-open allows only a few probe calls.
- Mention retry amplification (3 layers × 3 attempts = 27 calls) to show you understand how retries cause outages.
Real-world applications
- Netflix's Hystrix (now in maintenance) and its successor Resilience4j protecting JVM services.
- AWS SDKs, which retry throttled and transient errors with exponential backoff and jitter by default.
- Service meshes (Istio, Linkerd) applying timeouts, retries and outlier ejection uniformly across services.
Test yourself
Why add jitter to exponential backoff?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.