Lesson 19 of 38Running in production
Timeouts, Retries, and Circuit Breakers
Stop one slow dependency from taking down everything: timeouts, safe retries with jitter, circuit breakers, bulkheads, load shedding, and honest health checks.
Your product page calls a recommendations service. One afternoon that service gets slow: not down, just slow, answering in 30 seconds instead of 30 milliseconds. Your page has no timeout on that call, so every request thread ends up waiting on it. Within two minutes the product page is down, then the checkout that shares the same server pool, and the on-call is staring at a dashboard where everything is red and the root cause is a widget nobody needed. Most large outages look like this: a small failure that spreads. This lesson is the set of patterns that stop it spreading.
Why slow is worse than down
A dependency that is down fails fast: the connection is refused in a millisecond, you get an error, you move on. A dependency that is slow holds on to your resources. Each waiting request keeps a thread, a connection, a socket, and some memory. By Little's law, the number of requests in flight equals arrival rate times time in the system. At 200 requests per second and a 30 ms call, about 6 requests are in flight. Make the call take 30 seconds and you need 6,000. Your pool of 200 workers is exhausted in one second, and now requests that never touch the slow service queue behind the ones that do.
Every pattern below is about one of three things: bounding how long you wait, bounding how much you send, and bounding how much of your system one dependency can occupy.
Timeouts everywhere
A missing timeout is behind more outages than any clever bug. Many client libraries ship with no timeout or a very long one by default, so check every HTTP client, database driver, and SDK you use.
There are two timeouts on most network calls:
- Connect timeout: how long to wait to establish the connection. Keep it short (often well under a second inside a data centre). If the host is not answering, waiting longer rarely helps.
- Read (or request) timeout: how long to wait for the response once connected. Set it from the dependency's latency distribution: a bit above its p99 or p99.9, not a round number you guessed.
import httpx
# Connect fast or give up; allow up to 800 ms for the response itself.
client = httpx.Client(timeout=httpx.Timeout(0.8, connect=0.2))Deadlines beat per-hop timeouts. Suppose the user-facing request has 2 seconds in total. The API calls service A with a 2 s timeout, A calls B with a 2 s timeout, and B calls the database with a 2 s timeout. When the database is slow, B is still working after the user has given up, and so is A. That is wasted work at the worst possible time. A deadline is an absolute time ("finish by 12:00:02.000") passed along with the request. Each hop subtracts its own time spent and gives the next call only what is left. gRPC builds this in: a deadline set by the client propagates to every downstream call, and the server can check whether the caller has already gone. Over HTTP you pass the remaining budget in a header and enforce it yourself.
Retries without the storm
Many failures are transient: a dropped packet, a pod restarting, a leader election. One retry often succeeds. But a retry is also extra load sent to a system that is already struggling, so retries need rules.
Retry only what is safe. Retry only idempotent operations (GET, PUT, DELETE) or requests carrying an idempotency key (as in Payments). A blind retry of POST /charge after a timeout can charge twice, because a timeout means "I do not know", not "it failed".
Retry only transient errors. Timeouts, connection resets, 503, and 429 (honouring Retry-After) may heal. A 400 or 404 will fail the same way forever.
Back off with jitter. As Notifications showed, wait longer after each attempt and randomise the wait. AWS's "full jitter" formula is sleep = random(0, min(cap, base * 2 ** attempt)). Without jitter, every client that failed at the same moment retries at the same moment, and the waves of retries keep the dependency down.
Retry at one layer only. If the browser, the API gateway, the API, and the service client each retry 3 times, one user click can become 3 x 3 x 3 x 3 = 81 calls to the database during an incident. Pick one layer (usually the one closest to the failing call), and make the others fail fast.
Use a retry budget. Cap retries as a share of normal traffic, for example "retries may add at most 10% to the requests we send". When the dependency is healthy, the few retries you need fit easily. When it is failing, the budget runs out almost at once and you stop amplifying the outage. gRPC's retry throttling and Envoy's retry budgets implement this idea.
Three services call each other in a chain, and each makes up to 3 attempts per incoming request. The last service's database is down. How many database calls does one user request cause?
attempts_per_layer = 3 layers = 3 print(attempts_per_layer ** layers)
Circuit breakers
A retry helps when failure is rare and short. When a dependency is clearly down, retrying every request is pointless, and even making the first call is waste: each one costs a timeout's worth of waiting. A circuit breaker wraps calls to a dependency and tracks recent failures.
Closed is normal. Calls pass through, and the breaker counts outcomes over a sliding window, say the last 100 calls or 10 seconds.
Two details matter in practice. Count slow calls as failures, not just errors, or a dependency that hangs never trips the breaker. And keep one breaker per dependency (sometimes per host), so a broken search service does not cut you off from a healthy payments service. Libraries such as resilience4j (Java) and Polly (.NET) provide breakers in code, and service meshes like Envoy and Istio offer outlier detection that ejects failing hosts from the load-balancing pool.
Bulkheads
A ship's hull is split into watertight compartments so one leak does not sink it. A bulkhead in software gives each dependency its own limited share of resources: a separate connection pool, thread pool, or concurrency limit. If recommendations get slow, they can fill their own pool of 20 connections, and then calls to them fail fast. The other 180 workers keep serving checkout. Without bulkheads, one shared pool is a single point of failure for every dependency at once. The opening story is exactly a missing timeout plus a missing bulkhead.
Backpressure and load shedding
When demand exceeds capacity, something will be dropped. The only question is whether you choose what, or the system chooses for you by timing everything out.
- Bound every queue. An unbounded in-memory queue in front of a worker pool turns an overload into ever-growing latency and then an out-of-memory crash. A bounded queue rejects new work when full, which is a signal the caller can act on.
- Reject early and cheaply. Shed load at the edge, before doing expensive work, with
503 Service Unavailableand aRetry-Afterheader so well-behaved clients wait. A request rejected in 1 ms costs almost nothing. A request that times out after 10 s of work cost you 10 s and still failed. - Shed by priority. Not all traffic is equal. Drop prefetches, analytics beacons, and batch jobs before checkout and login.
- Use adaptive concurrency limits. A fixed limit of "500 in flight" is wrong as soon as the hardware or the dependency changes. Adaptive limiters (Netflix's concurrency-limits library, Envoy's adaptive concurrency filter) watch latency and shrink the allowed concurrency when latency rises, much like TCP congestion control.
Rate Limiting covered per-client limits. Load shedding is the server protecting itself regardless of who is asking.
Cascading and metastable failures
A cascading failure spreads from one component to the next: B slows, A's threads pile up behind B, A's callers time out and retry, and the retries hit A harder. A metastable failure is worse: the system stays broken after the original trigger has gone. The trigger (a 5-second network blip, a deploy) pushes the system into overload, and a feedback loop keeps it there. Retries are the usual loop: failing requests create retries, retries create more load, more load creates more failures. Other loops: a cache that was flushed by a restart sends every read to the database, which is too slow to refill the cache; or thousands of clients reconnect at once after an outage (the thundering herd).
The simulation below has a dependency that is fully down for 5 seconds, then healthy again. Watch what each client strategy does to it.
Press Run (⌘ Enter) to see what happens.The naive client retries immediately, up to 3 times. The 5-second outage leaves a pile of retries on top of normal traffic, which pushes the dependency past capacity, where goodput collapses, which creates more failures and more retries. Forty-five seconds after the dependency recovered, the naive client is still only getting about half its requests through: a metastable failure caused entirely by the clients. The careful client (jittered backoff, a 10% retry budget, and a breaker that fails fast during the outage) sends fewer calls than no retries at all and is fully healthy at the end. Try raising CAPACITY to 300 and the naive client recovers too, and even serves more users than the careful one, because spare capacity absorbs the retries. Metastable failures need the system to be running close to its limit, which is exactly where busy production systems run. Caution costs a few extra failures during the outage; in return, it removes the feedback loop.
The defences: jitter and retry budgets, request coalescing (one cache-miss fetch per key, with other requests waiting for it, as in Caching), warming caches before a node takes traffic, and staggered reconnects with jitter.
Graceful degradation and hedged requests
When a dependency fails, the best response is often a smaller answer rather than an error. Show the product page without recommendations. Serve the cached price list from five minutes ago, marked as possibly stale. Hide the "people also bought" row. Fall back to a static page from the CDN. Decide these fallbacks at design time, per dependency: which features are critical (checkout cannot fake a payment) and which can disappear quietly.
For tail latency, the opposite trick helps. A hedged request sends the same idempotent read to a second replica if the first has not answered within, say, its p95 latency. Use whichever answer comes first and cancel the other. Because only the slowest 5% get a second copy, it adds about 5% load and can cut p99 sharply. It only works for reads that are safe to duplicate, and it needs a cap so it does not become a retry storm of its own.
Health checks: liveness vs readiness
Load balancers and Kubernetes decide where to send traffic, and whether to restart a process, from health checks. There are two different questions, and mixing them up causes outages.
- Liveness: "is this process stuck beyond repair?" If it fails, Kubernetes restarts the container. Check only the process itself: can it answer at all?
- Readiness: "should this instance get traffic right now?" If it fails, the instance is taken out of the load balancer but left running. Use it during startup (caches loading) and when the instance is overloaded.
The classic mistake is a deep liveness check that also checks the database. When the database has a brief problem, every pod fails liveness at once, Kubernetes restarts all of them together, they all come back with cold caches and reconnect at the same moment, and a database blip becomes a full outage. Keep liveness shallow. Even with readiness, think twice before failing it on a shared dependency: if every instance goes unready at once, the load balancer has nowhere to send traffic, and a degraded answer would have been better than none.
Match each failure to the pattern that addresses it.
Put the stages of a retry-driven metastable failure in order.
- Tap the steps below in the right order.
- deadline
- An absolute time by which a request must finish, passed to every downstream call so each gets only the time that is left.
- full jitter
- Backoff where each wait is random between 0 and the exponential ceiling, so retries from many clients spread out.
- retry budget
- A cap on retries as a share of normal traffic, so retries cannot multiply load during an outage.
- circuit breaker
- A wrapper that stops calling a failing dependency (open), tests it with a few probes (half-open), and resumes when healthy (closed).
- bulkhead
- A separate, bounded pool of resources per dependency, so one slow dependency cannot use up all of them.
- load shedding
- Rejecting some work early and on purpose, often by priority, when demand exceeds capacity.
- metastable failure
- An overload that a feedback loop such as retries keeps going after the original trigger has gone.