Summary#
Resilience patterns are the small, local mechanisms that stop a failure in one component from spreading through a distributed system. They are:
- timeouts, to stop waiting;
- retries with exponential backoff and jitter, to recover from transient errors without stampeding;
- retry budgets, to stop retries from multiplying load;
- circuit breakers, to stop calling a dependency that is clearly failing;
- bulkheads, to isolate resources so one bad dependency can't exhaust them all;
- fallbacks and graceful degradation, to keep serving something useful;
- load shedding and back pressure, to keep an overloaded system doing useful work instead of collapsing.
Each pattern is simple. The skill lies in combining them so that they don't fight each other.
Why It Exists#
In a distributed system, every remote call can fail in three ways: it succeeds, it fails quickly, or it hangs. The Distributed Systems Fundamentals page explains why the third case is unavoidable. A request that hasn't returned may be slow, lost, or completed with the reply lost, and the caller can't tell which. Hangs are the dangerous case, because they consume resources while they wait.
Here is how an ordinary slowdown becomes an outage.
- Service A handles requests with a pool of 200 worker threads. Each request calls service B, which normally answers in 50 ms. With 200 threads × (1 s ÷ 50 ms) = 4,000 requests/s of capacity, A is comfortable at 2,000 requests/s.
- B develops a problem. A slow disk, garbage-collection pauses or its own overloaded dependency push its latency to 5 s.
- A's threads now each spend 5 s waiting. Its capacity falls to 200 × (1 s ÷ 5 s) = 40 requests/s. At 2,000 requests/s of arriving traffic, all 200 threads are busy within a fraction of a second, and A stops responding to everything. That includes requests that don't need B at all.
- A's callers now see A hang, exhaust their threads, and fail in turn. Users retry, mobile apps retry, and the load balancer retries. The offered load multiplies just as capacity collapses.
- When B recovers, it is hit by a flood of queued and retried requests, and falls over again.
This is a cascading failure: one component's trouble propagating up the call graph and amplifying as it goes. The SRE book (Beyer et al., 2016) devotes a chapter to it, and many large public outages follow this shape. The resilience patterns break the chain at each step:
- timeouts free the threads;
- bulkheads keep B's trouble from consuming the threads that other work needs;
- circuit breakers stop calling B while it is down;
- retry budgets and backoff keep retries from multiplying the load;
- load shedding and back pressure keep A, and B as it recovers, within capacity;
- fallbacks let A serve something useful without B.
How It Works#
The patterns divide into three groups.
- Patterns at the calling side: timeouts, retries with backoff and jitter, retry budgets, circuit breakers and fallbacks. They protect a caller from its dependencies, and protect dependencies from their callers' retries.
- Patterns at the resource level: bulkheads. They partition threads, connections and capacity, so a failure in one area can't drain the resources of another.
- Patterns at the receiving side: load shedding, back pressure and graceful degradation. They protect a service from more work than it can handle.
We'll build them up in that order, then cover how to handle errors at the web-request level, where they become visible to clients.
Timeouts#
A timeout is a limit on how long a caller waits for an operation before giving up. Without one, a hung call holds its thread, connection, memory and the user's patience indefinitely. Many client libraries default to no timeout, or to a very long one. Java's HttpURLConnection defaults to an infinite timeout unless one is set. Some database drivers wait for minutes. The first resilience rule is: every remote call gets an explicit timeout.
There are several kinds of timeout, and they protect against different things.
- Connect timeout: how long to wait to establish a TCP or TLS connection. Connections within a data centre complete in about 1 ms, so a connect timeout of 100–500 ms catches unreachable hosts quickly.
- Read (or socket) timeout: how long to wait between bytes once connected. It catches servers that stop responding mid-stream.
- Request (or total) timeout: the maximum time for the whole operation, including retries if the client retries internally. This is the one that matters to the caller's own latency budget.
- Idle timeout: how long an unused pooled connection stays open. If the client's idle timeout is longer than the server's, the client may send requests on connections the server has already closed. Set the client's lower.
Choosing the value. A timeout should be long enough that healthy requests rarely hit it, and short enough to free resources and leave the caller time to do something useful. A common starting point is the dependency's p99.9 latency under normal load, plus a margin. If a dependency's p99.9 is 120 ms, a timeout of around 200–300 ms means that only about 0.1% of healthy requests are cut off. AWS's Builders' Library article "Timeouts, retries, and backoff with jitter" (Marc Brooker) describes picking timeouts from the dependency's latency percentiles in just this way, choosing an acceptable rate of false timeouts.
Timeouts must nest. If an API request must finish in 1 s, and it calls three services in sequence, those calls' timeouts must fit inside the 1 s, with room for the API's own work. A downstream timeout longer than the caller's is wasted work: the caller has already given up, but the downstream keeps working on a request nobody will read.
Timeouts, in depth: deadlines, propagation and the tail#
Deadlines instead of timeouts. A per-hop timeout is relative ("wait 300 ms"). A deadline is absolute ("this request must be finished by 12:00:00.750"). It is set once at the edge and propagated with the request through every hop. gRPC builds this in. Clients set a deadline, it travels in the grpc-timeout header, and every server can see how much time is left, and pass the remainder on to its own calls. Two benefits follow:
- Each hop gets the remaining budget automatically. No configuration has to be kept consistent across services.
- Servers can drop work whose deadline has already passed. If a request has been queued for 900 ms of a 1 s deadline, there is no point starting a 200 ms operation. Discarding it frees capacity for requests that can still succeed. This matters enormously during overload, as the load-shedding section explains.
Fan-out makes the tail matter. A request that fans out to many backends is as slow as the slowest of them. If each backend has a 1% chance of taking longer than 1 s, a request fanning out to 100 backends hits at least one slow backend with probability 1 − 0.99¹⁰⁰ ≈ 63%. Dean and Barroso's "The Tail at Scale" (Communications of the ACM, 2013) made this point famous, and described tail-tolerant techniques.
- Hedged requests: send the request to one replica, and if it hasn't answered within the p95 latency, send it to a second replica too. Use whichever answers first. This adds only about 5% extra load, and cuts the tail sharply. In one Google benchmark described in the paper, hedging after a 10 ms delay reduced the 99.9th-percentile latency of a BigTable read from 1,800 ms to 74 ms, while sending only about 2% more requests.
- Tied requests: send the request to two servers at once, each knowing about the other. When one starts executing, it tells the other to cancel. This avoids most of the duplicated work.
- Good-enough results: for search-style fan-out, return when, say, 98% of shards have answered, rather than waiting for the last one.
Hedging is only safe for idempotent operations, usually reads. It also needs a cap, so that it can't double the load when everything is slow.
Adaptive timeouts. Static timeouts go stale as latency distributions change. Some systems compute timeouts from recently observed latency percentiles, like TCP's retransmission timeout, which is derived from smoothed round-trip time and its variance (RFC 6298). This needs floors and ceilings. Otherwise a slowly degrading dependency drags the timeout up with it, and the protection quietly disappears.
Timeouts on the server side too. Servers should bound how long they will work on a request: request timeouts in the web server, statement timeouts in the database (statement_timeout in PostgreSQL), and lock-wait timeouts. They should also cancel downstream work when the client disconnects. A server that keeps computing answers for clients that have gone away wastes capacity exactly when it is scarce.
Retries with exponential backoff and jitter#
Many failures are transient: a dropped packet, a server that restarted, a leader election in progress, a brief overload. Trying again a moment later often succeeds. A retry re-sends a failed request, and done carefully it hides a large class of failures from users. Done carelessly, it turns a small failure into a large one. Four rules make retries safe.
1. Retry only what can succeed on retry.
- Retryable: connection failures, timeouts, and errors that mean "try later": HTTP 503 Service Unavailable, 429 Too Many Requests (after the indicated delay), 502 and 504 from proxies, and gRPC
UNAVAILABLE. - Not retryable: errors that mean the request itself is wrong: 400 Bad Request, 401/403 (authentication or permission), 404, 409 Conflict, 422 validation errors.
- Generic 500s are ambiguous. They may be a transient bug or a deterministic one. A single retry is common, more is usually waste.
2. Retry only what is safe to repeat. A timed-out request may have succeeded on the server, with only the reply lost. Retrying a non-idempotent request ("charge the card") can charge twice. Reads are safe to retry, as are idempotent writes such as PUT and DELETE in their HTTP semantics. Non-idempotent writes are only safe to retry with an idempotency key. The client sends a unique key with the request, and the server stores the result per key, returning the stored result for duplicates. See Idempotency.
3. Wait longer between successive attempts (exponential backoff). Retrying immediately into an overloaded service adds load at the worst moment. Exponential backoff waits a base delay, then doubles it on each attempt: 100 ms, 200 ms, 400 ms, 800 ms… Each wait is capped at a maximum, such as 10 s or 20 s, and the number of attempts is capped too, typically at 3–5 for interactive requests.
4. Randomise the waits (jitter). Suppose 10,000 clients all fail at the same moment, because a server restarted. If they use the same backoff schedule, they all retry at the same moments too: a synchronised wave every 100, 200, 400 ms that hits the recovering server again and again. Jitter spreads each client's wait randomly, so retries arrive evenly over time.
Marc Brooker's analysis on the AWS Architecture Blog, "Exponential Backoff And Jitter" (2015), compared variants by simulation:
- No jitter: wait = min(cap, base × 2^attempt). Retries stay synchronised in waves.
- Full jitter: wait = random(0, min(cap, base × 2^attempt)). This spreads the retries most evenly, and produced the least total work in the simulation.
- Equal jitter: wait = half of the exponential value, plus random(0, the other half). It keeps a minimum wait.
- Decorrelated jitter: wait = min(cap, random(base, previous_wait × 3)). Each wait grows from the last one, randomly.
Full jitter and decorrelated jitter both perform well, and full jitter is the usual default. The AWS SDKs and many client libraries implement jittered exponential backoff by default.
Retries, in depth: durable retries with queues and acknowledgements#
Retrying in memory works for interactive calls that take milliseconds. For background work, such as fetching a web page, sending a webhook or processing a payment event, retries may need to span minutes or hours. They must also survive the worker crashing. An in-memory timer ("sleep 30 s and try again") is lost when the process dies, and it occupies the worker while it waits. For these cases, the retry state belongs in a durable queue.
SQS: visibility timeout as the retry clock. When a consumer receives an SQS message, the message becomes invisible to other consumers for the visibility timeout: 30 s by default, configurable up to 12 hours. If the consumer finishes, it deletes the message. If it crashes, or doesn't delete the message, the message reappears after the timeout and another consumer gets it. That gives automatic retry on crash. To add exponential backoff:
- read the message's
ApproximateReceiveCountattribute, which counts how many times it has been delivered; - on a failure, call
ChangeMessageVisibilityto hide the message for a backoff that grows with that count, such as min(12 h, 30 s × 2^count) with jitter; - configure a redrive policy with
maxReceiveCount, for example 5. After that many receives, SQS moves the message to a dead-letter queue (DLQ), for inspection or later replay.
A web crawler can treat a site as offline after 5 failed fetches spread over hours, without any custom retry infrastructure.
Kafka: retry topics. Kafka has no per-message retry or visibility timeout. A consumer that can't process a message must either block the whole partition (retrying in place, which stalls every message behind it), or move the message elsewhere. The usual pattern is a chain of retry topics with increasing delays, for example orders.retry.1m, orders.retry.10m and orders.retry.1h, followed by a DLQ topic.
- A failed message is republished to the next retry topic, with a header recording its attempt count and its not-before time.
- The retry consumer reads it and, if the not-before time is in the future, pauses the partition until then, then processes it.
- After the last retry topic, the message goes to the DLQ.
This works, but it is machinery you build and operate yourself. Frameworks such as Spring Kafka provide it ready-made. When a design needs flexible per-message retries and DLQs and doesn't need Kafka's ordering or replay, SQS or RabbitMQ (with dead-letter exchanges and delayed delivery) is often the simpler choice. Message Queues compares them.
Producer-side retries. Getting the message into the queue can fail too. Kafka producers retry automatically. Enabling the idempotent producer (enable.idempotence=true, the default in recent Kafka versions) attaches a producer ID and sequence numbers, so a retried send that actually succeeded the first time isn't written twice. Without idempotence, producer retries can create duplicates, and with more than one in-flight request per connection, they can reorder messages.
Acknowledgement timeouts on push channels. Over a WebSocket or another push connection, the transport can look open while it is actually dead. TCP keepalives can take minutes to notice. A chat server that delivers a message and waits for an application-level ACK can retry if none arrives within, say, 0.5–2 s. After a few failed retries, it closes the connection, forcing the client to reconnect and sync missed messages from durable storage. That only detects dead connections when there is something to send. Heartbeats cover the quiet periods: a ping every 10–30 s, with a pong expected within a few seconds. They put an upper bound on detection time. With a 10 s interval and a 5 s timeout, a dead connection is noticed within 15 s. At very large connection counts, heartbeats add up. 200M connections at a 10 s interval means 20M tiny ping/pong exchanges a second, a cost that is real but usually acceptable. The Real-time Updates page covers this in depth.
Poison messages. A message that fails deterministically, because it is malformed or triggers a bug, will fail every retry. Retrying it forever blocks the queue (in ordered systems) or wastes capacity. A cap on attempts plus a DLQ is the essential guard. Then alert on the DLQ's depth, build tooling to inspect and replay messages, and remember that a DLQ nobody looks at is just a slower way to lose data.
Retry storms and retry budgets#
Retries help when failures are rare and independent. They hurt when failures are widespread, because then every client retries at once. Retries add load to an already overloaded system, which fails more, which causes more retries. This positive feedback loop is a retry storm.
Amplification across layers. In a call chain where every layer retries, the attempts multiply. A user request passes through an API gateway, a frontend service, a backend service and a database. If each of the three upper layers makes up to 3 attempts, a failing database receives up to 3 × 3 × 3 = 27 attempts for each user request. During an outage, this can multiply the load on the bottleneck by an order of magnitude, preventing recovery.
Three defences prevent storms.
- Retry at one layer only. Usually that is the layer closest to the user, or the one with the most context about the request. Inner layers fail fast and report the error. Some systems mark errors as "already retried, don't retry again", so outer layers don't multiply attempts. Google's SRE book recommends a convention of returning an "overloaded; don't retry" status from deeper layers.
- Retry budgets. Cap retries as a fraction of normal traffic, not just per request. Example: "retries may add at most 10% to the request rate". When failures are rare, every failed request can retry. When failures are widespread, the budget runs out, and most failures are returned immediately, without retrying. The extra load from retries is then bounded at 10%, whatever happens. Implementations:
- Finagle's
RetryBudget, a token bucket where each request deposits a fraction of a token and each retry withdraws a whole one; - Envoy's retry budgets, as a percentage of active requests;
- gRPC's retry throttling, which disables retries when the failure ratio crosses a threshold.
- Finagle's
- Client-side adaptive throttling. Google's SRE book describes clients that track, over the last couple of minutes, their requests (attempts) and the backend's accepts (requests not rejected for overload). When the backend starts rejecting, the client rejects a fraction of new requests locally, before sending them:
- probability = max(0, (requests − K × accepts) / (requests + 1)), with K typically 2.
- When everything succeeds, requests ≈ accepts, and nothing is throttled.
- When the backend accepts only a fraction of requests, the client sheds the excess itself. That saves the backend the cost of rejecting it.
Retry storms, in depth: the maths of amplification and recovery#
Model one dependency with capacity C requests/s and offered load λ. If a fraction p of attempts fail, and each failure is retried up to r times, the effective load is:
- λ × (1 + p + p² + … + p^r) ≈ λ / (1 − p) for large r.
At p = 0.5 that doubles the load, and at p = 0.9 it multiplies it tenfold. But p itself grows with load: an overloaded server fails more requests. The system has two stable states:
- healthy: low p, load below capacity;
- overloaded: high p, retries keeping the load above capacity.
It can get stuck in the second even after the original trigger is gone. This is a metastable failure, in the terminology of Bronson et al. ("Metastable Failures in Distributed Systems", HotOS 2021). Recovery requires cutting the load well below capacity for long enough to drain the backlog: shedding, blocking retries, or even dropping traffic at the edge.
With a retry budget of fraction b, the effective load is at most λ × (1 + b). At b = 0.1, the worst case is 1.1 λ. This upper bound, independent of p, is why budgets are more robust than per-request caps alone.
Backoff is about synchronisation as well as total load. Even with modest attempt counts, synchronised retries create spikes far above the average rate. Consider 10,000 clients that failed together. If they all retry at exactly +100 ms, the server sees 10,000 requests in one instant. With full jitter over 0–100 ms, it sees about 100 requests per millisecond, spread evenly. The total is the same, but the peak is far lower, and peak load is what overflows queues and connection limits.
Retries hide problems. A system that retries successfully looks healthy from outside, while burning capacity on failures. Monitor the retry rate and the first-attempt success rate separately from the final success rate. A rising retry rate is an early warning that a dependency is degrading.
A real example of retry-driven overload. AWS's summary of the September 2015 DynamoDB disruption in us-east-1 described storage servers that couldn't get their membership data from an internal metadata service within their timeout. The responses had grown larger. The storage servers retried, and the retries kept the metadata service overloaded. Recovery required adding capacity to the metadata service, and pausing the retrying requests so it could catch up. The pattern of timeouts and retries sustaining an overload is the classic one.
Circuit breaker states#
A circuit breaker wraps calls to a dependency, and tracks their outcomes. When failures exceed a threshold, the breaker opens, and later calls fail immediately, without being sent. This saves the caller from waiting on timeouts, and the dependency from load it can't handle. After a cool-down, the breaker lets a few trial calls through. If they succeed, it closes again. Michael Nygard's book "Release It!" (2007) popularised the pattern for software, and Netflix's Hystrix library made it mainstream for microservices in the 2010s.
The breaker has three states.
- Closed: normal operation. Calls pass through, and the breaker records successes and failures, often over a sliding window of the last N calls or T seconds.
- Open: the failure rate crossed the threshold, for example 50% failures over at least 20 calls in the last 10 s. Calls are rejected immediately with an error or a fallback, for a configured wait duration, say 30 s.
- Half-open: after the wait, a limited number of trial calls (say 5) are allowed through. If they mostly succeed, the breaker closes. If they fail, it re-opens and waits again, often for a longer period.
A breaker turns a slow failure into a fast failure. When a dependency is down, waiting 2 s for each timeout ties up resources, and gives the user the same error 2 s later. Failing in under a millisecond releases the thread at once, and allows an immediate fallback.
Circuit breakers, in depth: tuning and the subtleties#
What counts as failure. Timeouts, connection errors and 5xx responses count. Client errors (4xx) usually don't, because they say nothing about the dependency's health. Slow calls are often counted as failures too. resilience4j can open the breaker if more than x% of calls exceed a duration threshold, even if they eventually succeed, because slowness exhausts the caller's resources just as failure does.
Minimum volume. At low traffic, two failures out of three calls is a 66% failure rate, but statistically meaningless. Breakers require a minimum number of calls in the window before evaluating the rate.
Window type. A count-based window looks at the last N calls. A time-based window looks at the calls in the last T seconds, usually bucketed for efficiency. Time-based windows react consistently regardless of traffic level.
Granularity: per host, or per service? A breaker per downstream service opens when the whole service is failing. But a single bad host among 50 would never push the service-wide rate over the threshold, while still failing 2% of requests. A breaker per host (or load-balancer outlier detection, which ejects bad hosts) handles that case. Envoy's outlier detection, which ejects hosts with consecutive 5xx errors or abnormal success rates, is effectively a per-host breaker inside the load balancer. Use both: outlier ejection for individual hosts, and a service-level breaker for when the whole dependency is down.
Breakers and retries together. The breaker should sit outside the retry loop, and count the logical call, or else it should see every attempt. Either way, when the breaker is open, no retries happen, which is exactly the point. Breakers are a natural complement to retry budgets. The budget limits extra load while failures are partial, and the breaker stops the load once failure is near total.
Half-open stampede. If many instances of a caller all open their breakers at the same moment, they will all go half-open at the same moment too, and send synchronised trial traffic. Add jitter to the wait duration, and keep the number of trial calls small.
The breaker is not a fix. It protects the caller and gives the dependency room to recover, but the caller still needs to decide what to do while the breaker is open: fail, degrade or fall back. A breaker without a plan for the open state just converts timeouts into fast errors. That's an improvement, but not a feature.
Breaker state is local. Each caller instance has its own breaker. With 100 callers, each must observe enough failures to open its own. That is usually fine, and avoids a shared dependency. Shared breaker state (in Redis, say) is rarely worth its cost and coupling.
Bulkhead#
A ship's hull is divided into watertight compartments called bulkheads, so that a breach floods one compartment instead of sinking the ship. In software, a bulkhead partitions a shared resource, such as threads, connections, memory, queue capacity or whole server pools, so that a problem in one area can only use up that area's share.
Go back to the cascading-failure example. Service A's 200 threads were shared by all of its work. When dependency B slowed down, B's calls took all 200 threads, and requests that never touched B failed too. With bulkheads, A gives calls to B their own pool of, say, 40 threads, or a semaphore limiting concurrent calls to B to 40. When B slows down, those 40 fill up, and further calls to B are rejected immediately, which the circuit breaker or fallback then handles. The other 160 threads keep serving everything else.
Bulkheads appear at every scale.
- Per-dependency concurrency limits inside a service: a thread pool or semaphore per downstream service. Hystrix offered both thread-pool and semaphore isolation. resilience4j offers
Bulkhead(a semaphore) andThreadPoolBulkhead. - Separate connection pools per database or per workload. Analytics queries get a small pool, so that they can't starve transactional queries.
- Separate server pools per traffic class: interactive API servers apart from batch workers, or a dedicated pool for a large, noisy customer.
- Per-tenant quotas in multi-tenant systems, so that one tenant's surge can only consume its quota.
- Priority queues with separate workers: urgent notifications on their own queue and workers, so that a marketing blast to millions of users can't delay a password-reset code.
- Cells and shuffle sharding at the infrastructure level, so one failure affects a bounded fraction of customers. See Designing for High Availability.
Bulkheads, in depth: sizing and the cost of isolation#
Sizing a bulkhead with Little's Law. The concurrency a workload needs is its arrival rate times its latency: L = λ × W. If A calls B 500 times a second, and B normally answers in 40 ms, then on average 500 × 0.04 = 20 calls are in flight. A bulkhead of 40 allows for twice the normal latency or rate before it starts rejecting. If B's latency rises to 400 ms, the 40 slots support only 100 calls/s, and the other 400 calls/s are rejected quickly. That is the intent. B's degradation costs B's calls, and nothing else.
Bulkheads waste capacity, deliberately. A shared pool of 200 is more efficient than 5 pools of 40, because shared capacity absorbs uneven spikes. This is statistical multiplexing. Isolation trades efficiency for containment. Common compromises:
- isolate only the dependencies that are slow, unreliable or critical, and share the rest;
- use semaphores (cheap counters on the caller's own threads) rather than dedicated thread pools when calls are non-blocking or already have timeouts;
- size pools from observed concurrency at p99, and review the sizes as traffic changes.
Threads versus semaphores. A thread-pool bulkhead runs the call on a separate pool, so the caller can abandon it after a timeout even if the call itself is stuck in blocking I/O. The cost is a thread hop and the pool's memory. A semaphore bulkhead only counts concurrent calls on the caller's thread. It's cheaper, but it relies on the call's own timeout to return. In asynchronous or event-loop runtimes (Node.js, Netty, Go), semaphores, or simple counters on in-flight requests, are the norm.
Bulkheads at the receiving side. A server can also partition its own capacity by caller or priority. For example, "batch clients may use at most 30% of worker slots". Then one caller's surge can't take the capacity other callers need. Per-client concurrency limits are a form of load shedding, discussed below.
Fallbacks#
A fallback is what a caller does when a call fails, times out, or is rejected by a breaker or bulkhead. The choice depends on the dependency's role in the product.
| Fallback | Example | When it fits |
|---|---|---|
| Fail fast with a clear error | Return 503 with Retry-After | The dependency is essential, and no reasonable substitute exists |
| Cached or stale value | Last known exchange rate; profile from a local cache | Slightly old data is acceptable; mark it stale if users care |
| Static default | Generic recommendations; default settings | Personalisation is nice-to-have |
| Alternative source | Second payment provider; secondary search cluster | A genuinely independent alternative exists and is tested |
| Degraded response | Results without ranking; page without a widget | The core of the response can be produced without the dependency |
| Defer the work | Accept the order, queue the confirmation email | The work can be done later, durably and idempotently |
| Fail silent | Drop an analytics event | The work has no user-visible value |
Fallbacks carry two warnings.
- A fallback must not depend on what failed. A cache fallback that reads from the same overloaded database helps nobody.
- Fallbacks are rarely exercised, so they are often broken. Amazon's Builders' Library article "Avoiding fallback in distributed systems" argues for preferring designs that don't need a separate fallback mode: a more robust primary path, data pushed ahead of time, or a "fallback" that runs all the time, such as always serving from a local cache that is refreshed in the background. Where fallbacks exist, test them continuously, by forcing a small slice of traffic through them.
Load shedding#
Load shedding is a server deliberately rejecting some requests when it's overloaded, so that it can serve the rest well. The alternative is accepting everything, which usually means serving nothing well.
To see why, consider what happens past capacity. A server that accepts more requests than it can process queues them. Queues grow, and so does latency. Clients time out. But the server keeps processing the timed-out requests, because it doesn't know their clients have gone. Eventually the server spends all its capacity on requests nobody is waiting for. Throughput (requests completed) may stay high, while goodput (requests completed in time to be useful) falls towards zero. Shedding keeps goodput high, by rejecting excess requests quickly, before they consume resources.
How servers decide what to shed:
- Concurrency limits: cap the number of in-flight requests (for example 200 per instance), and reject extras immediately with 503 or 429.
- Queue limits and queue time: cap the queue length, or drop requests that have waited longer than a threshold, because their clients have likely given up.
- Resource signals: shed when CPU, memory or the connection count crosses a threshold.
- Deadline awareness: drop requests whose propagated deadline has already passed, or can't be met.
- Priority: shed the least important work first, such as background syncs, prefetches and analytics, before user-facing reads, before checkout. Google's SRE book describes request criticality classes propagated with each request.
- Fairness: shed per client or tenant, so the client causing the overload absorbs most of the rejections. This is where load shedding meets rate limiting.
For write paths, a queue can absorb bursts. A durable queue in front of a write-heavy backend absorbs bursts, so that the backend processes at its own pace. A flash sale's order submissions go into Kafka or SQS, and workers drain them at the database's sustainable rate. That converts overload into latency, which is acceptable only if the burst is temporary and the work can be asynchronous. A queue isn't a fix for sustained overload. If arrivals exceed processing for long enough, the queue grows without limit, and the data in it goes stale. Combine it with shedding at the edge. When the queue depth or the age of its oldest message passes a threshold, reject or defer new low-priority work. For example, a metrics pipeline under extreme load might drop or sample debug-level data, while keeping alerts flowing.
Load shedding, in depth: queueing disciplines and adaptive limits#
Why FIFO queues fail under overload. In a first-in, first-out queue, every new request waits behind every older one. Once the queue is long enough that its wait exceeds client timeouts, every request is served too late. The server does full work for zero goodput. Two techniques fix this.
- Adaptive LIFO. Under overload, serve the newest requests first. Their clients are most likely still waiting. The oldest are left to time out, and are eventually discarded. Facebook described using adaptive LIFO, switching to LIFO only when a queue is building, in Ben Maurer's "Fail at Scale" (ACM Queue, 2015).
- Controlled-delay queueing (CoDel). Borrowed from networking (Nichols and Jacobson, "Controlling Queue Delay", ACM Queue, 2012). Track the minimum time requests spent in the queue over an interval. If even the best case exceeds a target, such as 5 ms in network terms or a few milliseconds to tens of milliseconds for RPC servers, the queue is persistently overloaded, so drop requests with a short timeout until it drains. Brief bursts that the queue absorbs aren't penalised. Facebook described combining CoDel-style timeouts with adaptive LIFO for its RPC queues in the same article.
Adaptive concurrency limits. A static concurrency limit is wrong half the time. It is too high after a deploy that made requests heavier, and too low after one that made them lighter. Adaptive limits discover capacity from latency, as TCP congestion control does.
- When latency stays near its minimum, there is spare capacity, so the limit can rise.
- When latency rises above its baseline, a queue is forming, so the limit must fall.
Netflix's open-source concurrency-limits library implements algorithms inspired by TCP Vegas and by gradient methods. It computes a limit as roughly limit × (min_latency ÷ current_latency), plus a queue allowance, and adjusts it continuously. Envoy offers an adaptive concurrency filter based on similar ideas. These algorithms let each server shed exactly the excess, without hand-tuned thresholds.
Shedding cheaply. Rejecting a request should cost far less than serving it. Otherwise the server can still be overwhelmed by rejections alone. Reject as early as possible:
- at the load balancer or gateway, based on per-instance health or concurrency;
- or at the very start of request handling, before authentication, deserialisation of large bodies, or database calls.
Return a small 503 or 429 with Retry-After, so well-behaved clients back off.
Shed by value, not at random. Random shedding of 20% of requests fails 20% of user sessions, possibly in the middle of a multi-step flow. Shedding by priority keeps important flows whole. Shedding by session keeps a sampled set of users fully served, rather than giving everyone a broken experience. For example, consistently reject the same 20% of session IDs.
Back pressure#
Back pressure is a signal from a consumer to a producer that says "slow down, I can't keep up". It propagates the limits of the slowest stage back towards the source, instead of letting work pile up in unbounded buffers in between.
Without back pressure, a fast producer feeding a slow consumer fills whatever buffer sits between them. That might be an in-memory queue, a socket buffer, or a broker topic. If the buffer is unbounded, memory grows until the process crashes. If it's bounded but full, something has to happen when the next item arrives, and that something should be designed, not accidental.
Producers have three choices when a consumer can't keep up:
- Block or slow down (true back pressure). The producer waits until there is room. TCP flow control works this way: the receiver advertises a window, and the sender can't exceed it. Reactive Streams (
request(n)in Reactor, RxJava and Akka Streams) makes the consumer pull a bounded number of items. Go channels with a fixed capacity block the sender when they are full. - Drop. Discard new items, or the oldest, when the buffer is full. This is appropriate when data is replaceable or sampled: metrics, telemetry, stale location updates. Make the dropping visible, with counters and alerts.
- Buffer durably and scale. Write to a durable log (Kafka) or queue (SQS), and scale consumers on queue depth or lag. Kafka consumers pull at their own pace, so a slow consumer simply falls behind. Its consumer lag grows, but the broker isn't harmed, and producers aren't blocked. Lag then becomes the scaling signal, for example through KEDA autoscaling on Kafka lag or SQS queue depth.
Back pressure, in depth: propagating limits through a system#
End to end, back pressure must reach someone who can act. Inside a service, back pressure between threads is easy. Across services, it has to be expressed in the protocol.
- HTTP: 429 Too Many Requests, or 503 Service Unavailable, with
Retry-After. - gRPC:
RESOURCE_EXHAUSTEDorUNAVAILABLE. - Streaming protocols: HTTP/2 and gRPC streams have flow-control windows. WebSocket servers can stop reading from slow clients' sockets.
- Message systems: queue depth and lag. Producers can check depth before sending low-priority work.
Eventually the pressure reaches the edge, where it becomes a user-visible delay or rejection, or the system decides to shed. Back pressure doesn't make overload disappear. It moves the decision to the place where it can be made cheaply and deliberately.
Bounded everything. Every queue, buffer, connection pool and in-memory cache should have a size limit, plus a defined behaviour at the limit. An unbounded queue is a latent outage, because it converts a throughput problem into a memory problem, and adds latency nobody is measuring. A useful review question: "what happens when this is full?"
Back pressure in long-running task systems. When jobs arrive faster than workers process them, the queue grows. The options are:
- Scale workers on queue depth, bounded by what the downstream systems can absorb. Adding 100 workers that all hammer one database just moves the bottleneck.
- Reject or defer new work at submission time when the queue's age exceeds the service-level target. Tell the user "we're busy, try in 10 minutes", rather than accepting a job that will finish in 6 hours.
- Separate queues by job type and priority, so that a flood of large, slow jobs can't block small, fast ones. This is a bulkhead for queues.
- Limit per-tenant in-flight jobs, so one customer's batch of 100,000 jobs can't monopolise the workers.
Long-Running Tasks covers worker pools and queue design.
Back pressure versus load shedding. They are complementary. Back pressure slows producers that can wait: internal services, batch pipelines and well-behaved clients. Load shedding rejects work when producers can't be slowed, or when waiting would make the work useless: users with timeouts, or uncontrolled external traffic. A robust system applies back pressure inside, and sheds at the edges.
Graceful degradation#
Graceful degradation is the system-level result of these patterns, as users see it. When dependencies fail or capacity runs short, the product stays usable by dropping less important functions, rather than failing entirely. The building blocks are those above. Breakers and timeouts detect the failure quickly, fallbacks supply substitutes, and load shedding by priority protects the most important flows. Degradation also needs decisions outside code. Which features are critical? Which can degrade, and how? Who can switch them off during an incident, and with which feature flags?
Brownouts are degradation as a control loop. Optional work is turned off automatically when latency or load crosses a threshold: recommendations, high-resolution images, expensive ranking. It is restored when conditions improve. Video players do this all the time through adaptive bitrate, which drops quality instead of stalling. Designing for High Availability covers planning degradation, and its trade-offs, at the architecture level.
Handling web request errors#
Most of these patterns become visible to clients as HTTP errors. Getting the error contract right lets clients, gateways and retry libraries react correctly.
Use status codes that mean what they say.
| Status | Meaning | Client should |
|---|---|---|
| 400 Bad Request, 422 Unprocessable Content | The request is invalid | Fix the request; don't retry as-is |
| 401 Unauthorized / 403 Forbidden | Authentication missing, or not permitted | Re-authenticate or stop; don't retry blindly |
| 404 Not Found | The resource doesn't exist | Don't retry (unless eventual consistency is expected) |
| 408 Request Timeout | The server gave up waiting for the client's request | Retry, possibly on a new connection |
| 409 Conflict | State conflict, such as a version mismatch | Re-read, then resolve; retry with new data |
| 429 Too Many Requests | Rate-limited or shed for fairness | Wait for Retry-After, then retry with backoff |
| 500 Internal Server Error | Unexpected server failure | Perhaps one retry if idempotent; otherwise report |
| 502 Bad Gateway / 504 Gateway Timeout | A proxy couldn't get a good or timely upstream response | Retry with backoff if idempotent |
| 503 Service Unavailable | Overloaded, or in maintenance | Wait for Retry-After, then retry with backoff |
Tell clients when to come back. Retry-After (seconds, or an HTTP date) on 429 and 503 responses lets the server spread out retries deliberately. Rate-limit headers tell clients how close they are to their limits: the widely used X-RateLimit-Limit, X-RateLimit-Remaining and X-RateLimit-Reset, or the IETF's RateLimit header fields draft. Rate Limiting and Throttling covers these headers.
Give errors a machine-readable body. RFC 9457, "Problem Details for HTTP APIs" (2023, which replaced RFC 7807), defines a JSON format with type, title, status, detail and instance fields, and room for extensions such as a retryable flag or a correlation ID. Consistent error bodies let SDKs map errors to exceptions, and decide whether to retry. See API Design.
Make writes retry-safe. Accept an Idempotency-Key header on POST requests that create things or move money. Store the response for each key for a period such as 24 hours, and return it for duplicate keys. Then the client can retry a timed-out "create payment" without fear. Stripe's API popularised this pattern.
Clients: one retry policy, in one place. Implement retries, backoff, jitter, deadlines, idempotency keys and the retryable-error list once, in a shared client library or SDK, or in the service mesh, not ad hoc in every call site. For user-facing applications:
- show a meaningful state instead of a spinner forever ("We're having trouble, retrying…");
- keep the user's input, so they don't lose a form;
- offer manual retry.
Servers: translate, don't leak. A server that receives a timeout from a dependency should return its own appropriate error: 503 or 504 with Retry-After, not a stack trace or the dependency's raw error. It should log the cause with a correlation ID (also called a request ID or trace ID), and return that ID to the client. Support teams and engineers can then find the full story in logs and traces. Observability covers tracing.
When to Use It#
- Every remote call: timeouts, always. There is no situation where an unbounded wait on a network call is right.
- Transient-failure-prone dependencies (networks, cloud APIs, databases during failover): retries with exponential backoff and full jitter, capped attempts, idempotency for writes.
- Many clients, or deep call chains: retry budgets, retrying at a single layer, and adaptive client throttling, so that retries can't amplify an outage.
- A dependency that can fail completely, or slow down badly: a circuit breaker, plus a decided behaviour for the open state.
- A service with several dependencies of differing reliability, or mixed traffic classes: bulkheads per dependency or class.
- Soft dependencies: fallbacks, tested continuously.
- Services exposed to unpredictable load (public APIs, flash sales, viral events): load shedding with priorities, at the edge and per instance, and adaptive concurrency limits.
- Pipelines with stages of different speeds (ingestion, job queues, streaming): back pressure with bounded buffers, and lag-based scaling.
- Background jobs needing retries over minutes or hours: durable retries in the queue (SQS visibility timeouts, or retry topics), with DLQs.
When NOT to Use It#
- Retries on non-idempotent operations without idempotency keys. A retried payment or "send email" without deduplication causes duplicate side effects. Make the operation idempotent first.
- Retries at every layer. Pick one layer. Inner layers should fail fast.
- Retrying non-retryable errors. Retrying 400s, 403s and validation errors only adds load.
- Circuit breakers on calls with very low volume, where the breaker can't gather meaningful statistics, or on local in-process calls. A timeout and a simple error suffice.
- Fallbacks that are more complex or less tested than the primary path, or that depend on the same failed resource.
- Queues as a cure for sustained overload. A queue buffers bursts. If arrivals exceed capacity indefinitely, it just delays the failure, and makes it bigger.
- Very aggressive timeouts without measurement. Timeouts below a dependency's normal p99 cause self-inflicted errors and retries, which can be worse than no timeout.
How to Implement It#
- List the dependencies of each service, and classify each as hard (the request can't succeed without it) or soft (the request can degrade without it). This decides the fallback for each.
- Set timeouts from measurements. Use the dependency's p99 or p99.9 latency plus a margin, inside an end-to-end deadline that is propagated with each request. Use separate connect and request timeouts.
- Pick one retry layer per call path. Usually that is the client nearest the user, or the service mesh. Use exponential backoff with full jitter, 2–3 attempts, a retry budget of about 10%, and a list of retryable errors. Add idempotency keys for writes.
- Wrap calls to unreliable hard dependencies in a circuit breaker. Count slow calls as failures, set a minimum request volume, and decide the open-state behaviour: fail fast or fall back.
- Isolate with bulkheads. Give each risky dependency a concurrency limit sized with Little's Law. Separate pools for batch and interactive traffic.
- Protect each server: a concurrency limit, adaptive if possible; priority-aware shedding; cheap early rejections with
Retry-After; dropping of requests whose deadline has passed. - Bound every queue, define behaviour when it's full, and scale consumers on depth or lag.
- Define the error contract: status codes, Problem Details bodies,
Retry-After, correlation IDs. - Instrument everything: timeouts, retries (as a fraction of requests), breaker state changes, bulkhead rejections, shed requests, queue depth and age, and DLQ size. Alert on changes.
- Test it. Use fault injection (latency, errors, dropped connections) in staging and, carefully, in production. Run game days that deliberately slow a dependency. Check that the breakers open, fallbacks serve, and retries stay within budget.
A client-side retry helper with full jitter, a deadline, and a token-based retry budget looks like this:
// Retry budget: each success earns 0.1 tokens; each retry spends 1 (≈10% retries).
class RetryBudget {
private tokens = 10;
onSuccess() { this.tokens = Math.min(10, this.tokens + 0.1); }
trySpend(): boolean {
if (this.tokens < 1) return false;
this.tokens -= 1;
return true;
}
}
const RETRYABLE = new Set([408, 429, 502, 503, 504]);
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
async function callWithRetry(
send: (timeoutMs: number) => Promise<Response>,
budget: RetryBudget,
deadlineMs: number, // absolute time, e.g. Date.now() + 2000
maxAttempts = 3, baseMs = 100, capMs = 2000,
): Promise<Response> {
for (let attempt = 0; ; attempt++) {
const remaining = deadlineMs - Date.now();
if (remaining <= 0) throw new Error("deadline exceeded");
const res = await send(remaining).catch(() => null); // null = network error or timeout
if (res && !RETRYABLE.has(res.status)) { budget.onSuccess(); return res; }
if (attempt + 1 >= maxAttempts || !budget.trySpend()) {
if (res) return res;
throw new Error("request failed");
}
const retryAfter = Number(res?.headers.get("Retry-After")) * 1000 || 0;
const backoff = Math.random() * Math.min(capMs, baseMs * 2 ** attempt); // full jitter
const wait = Math.max(backoff, retryAfter);
if (Date.now() + wait >= deadlineMs) {
if (res) return res;
throw new Error("deadline exceeded");
}
await sleep(wait);
}
}A few details matter here.
- The helper passes the remaining deadline to each attempt, so attempts shrink as time runs out.
- It honours
Retry-After. - It stops when the budget is empty. During a large outage, retries then stay at about 10% of traffic.
- It assumes the caller only uses it for idempotent requests, or ones carrying an idempotency key.
Production libraries such as resilience4j, Polly and the AWS SDKs implement the same ideas, with more care: thread safety, metrics, and per-host state.
Declarative configuration in resilience4j (Spring Boot) shows how the patterns combine for one dependency:
resilience4j:
timelimiter:
instances:
inventory: { timeoutDuration: 300ms }
retry:
instances:
inventory:
maxAttempts: 3
waitDuration: 100ms
enableExponentialBackoff: true
exponentialBackoffMultiplier: 2
enableRandomizedWait: true
retryExceptions: [java.io.IOException, java.util.concurrent.TimeoutException]
circuitbreaker:
instances:
inventory:
slidingWindowType: TIME_BASED
slidingWindowSize: 10 # seconds
minimumNumberOfCalls: 20
failureRateThreshold: 50 # percent
slowCallDurationThreshold: 250ms
slowCallRateThreshold: 50
waitDurationInOpenState: 10s
permittedNumberOfCallsInHalfOpenState: 5
bulkhead:
instances:
inventory: { maxConcurrentCalls: 40, maxWaitDuration: 0 }| Technology | Fits when |
|---|---|
| resilience4j (Java/Kotlin) | JVM services wanting retry, breaker, bulkhead, rate limiter and time limiter as composable decorators; the successor to Hystrix |
| Polly (.NET) | .NET services; resilience pipelines with retry, breaker, timeout, hedging and rate limiting |
| Envoy / Istio / Linkerd | Polyglot fleets; timeouts, retries with budgets, outlier detection, circuit breaking (connection and request limits) and adaptive concurrency at the mesh, without code changes |
| gRPC retry and hedging policy | gRPC services; per-method retry or hedging policies in service config, with retry throttling and deadline propagation built in |
| Finagle (Scala) | Twitter-style RPC stacks; retry budgets, failure accrual, and deadlines out of the box |
| failsafe-go, cenkalti/backoff, sony/gobreaker | Go services wanting retries, backoff and breakers as libraries |
| AWS SDK retry modes (standard, adaptive) | Calls to AWS APIs; standard mode adds retry quotas; adaptive mode adds client-side rate limiting on throttling errors |
| Netflix concurrency-limits | JVM servers or clients wanting adaptive concurrency limits (Vegas or gradient) instead of static ones |
| SQS / RabbitMQ / Kafka retry topics + DLQ | Durable retries of background work over minutes or hours; poison message isolation (Spring Kafka provides retryable topics) |
| Temporal / AWS Step Functions | Multi-step workflows needing per-step retries, timeouts and compensation, with durable state |
| Chaos tools (Gremlin, AWS FIS, Chaos Mesh, Toxiproxy) | Testing timeouts, breakers and fallbacks by injecting latency, errors and network faults |
Trade-offs#
| Option | Pros | Cons | Pick when |
|---|---|---|---|
| Short timeouts | Fail fast; free resources quickly | False timeouts; more retries if set below p99 | The latency distribution is well measured and tight |
| Long timeouts | Few false failures | Resource exhaustion and cascades when a dependency is slow | Rarely; only for known-slow operations, with bulkheads |
| Retries with backoff and jitter | Hide transient failures | Extra load; duplicates without idempotency; added latency | Transient failures dominate, and operations are idempotent |
| No retries (fail fast) | Simple; no amplification | Users see transient failures | Inner layers of deep call chains; non-idempotent operations |
| Hedged requests | Cut tail latency sharply | Extra load (a few percent); needs idempotent reads | Read-heavy fan-out with long tails |
| Circuit breaker | Stops wasted calls; lets dependencies recover | Tuning; false opens at low volume; local state per instance | Remote dependencies that can fail fully or slow badly |
| Thread-pool bulkhead | Strong isolation, even of blocking calls | Memory and context switching; wasted idle capacity | Blocking clients; critical isolation |
| Semaphore bulkhead | Cheap | Relies on the call's own timeout | Async or non-blocking calls |
| Fallback | Keeps the user experience going | Rarely tested; may hide failures; may depend on the same resource | Soft dependencies with a real, tested substitute |
| Static load shedding | Simple, predictable | Wrong limit after deploys or traffic-mix shifts | Stable workloads |
| Adaptive concurrency limits | Track real capacity | More complex; may oscillate | Variable workloads; large fleets |
| Back pressure (block) | No data loss; self-regulating | Producers stall; can propagate stalls widely | Internal pipelines where waiting is acceptable |
| Drop under pressure | Protects the system; bounded latency | Data loss | Replaceable data (metrics, telemetry, location) |
| Durable queue buffering | Absorbs bursts; decouples rates | Latency; growing backlog; stale work if sustained | Bursty, asynchronous work |
Common Pitfalls#
- No timeout at all. Many HTTP and database clients default to infinite or very long timeouts. Set them explicitly, everywhere.
- Timeouts longer than the caller's. If an inner call's timeout exceeds the outer request's, the inner work continues after nobody is waiting. Propagate deadlines.
- Retrying at every layer. Multiplicative amplification turns a partial outage into a total one.
- Backoff without jitter. Clients that back off in lockstep still arrive in synchronised waves.
- Retrying non-idempotent operations. This produces duplicate charges, emails or orders. Use idempotency keys and deduplication.
- Breakers that count only errors. A dependency that is slow but returns 200s never trips the breaker. Count slow calls.
- One breaker for a whole service, when one host is bad. Use per-host outlier ejection at the load balancer or mesh.
- Untested fallbacks. The first real outage is the fallback's first real test, and it fails.
- Unbounded queues and buffers. Memory grows until a crash, and latency grows invisibly.
- Expensive rejections. If rejecting a request costs nearly as much as serving it, shedding doesn't save the server.
- FIFO queues under overload. Everything is served too late. Use queue-time limits, adaptive LIFO or CoDel.
- Retrying poison messages forever. Use a maximum attempt count and a DLQ, plus alerting and a replay tool.
- Retries that ignore
Retry-After, or that retry 429s immediately. - No metrics for the resilience layer. Without retry rates, breaker states and shed counts, you can't tell whether the patterns are helping or hurting.
Real-World Examples#
- Netflix Hystrix. Netflix built Hystrix to isolate calls to dependencies with thread-pool bulkheads, timeouts, circuit breakers and fallbacks. It open-sourced the library in 2012, and the library popularised these patterns in the Java world. In 2018 Netflix moved Hystrix to maintenance mode, and pointed users towards adaptive approaches and libraries such as resilience4j.
- Amazon Builders' Library. Amazon's articles "Timeouts, retries, and backoff with jitter" and "Avoiding fallback in distributed systems" describe practices such as retrying at a single layer, using token-bucket retry quotas (as the AWS SDKs do), adding jitter, and preferring designs that don't need fallback modes. Marc Brooker's 2015 AWS Architecture Blog post "Exponential Backoff and Jitter" compared jitter strategies by simulation.
- Google SRE book (2016). The chapters on handling overload and addressing cascading failures describe client-side adaptive throttling, request criticality, per-client quotas, deadline propagation, and the danger of retries at multiple layers.
- Facebook "Fail at Scale" (ACM Queue, 2015). Ben Maurer described how Facebook used controlled-delay queueing and adaptive LIFO to keep servers responsive under overload, along with concurrency control, and with tooling for understanding failures.
- DynamoDB, September 2015. AWS's post-incident summary described a metadata service that was overwhelmed in us-east-1. Storage servers' requests timed out and were retried, which kept the metadata service overloaded. Recovery required reducing the load on it, an example of a retry-sustained, metastable failure.
- Stripe idempotency keys. Stripe's API accepts an
Idempotency-Keyheader, so clients can safely retry POST requests that create charges. Stripe's engineering blog has described why this makes retries with exponential backoff safe. - Envoy. The Envoy proxy implements retry budgets, outlier detection, circuit breaking through connection and request limits, and an adaptive concurrency filter. Meshes built on Envoy (Istio) expose these as configuration.
Case studies that use this pattern#
- Design a Web Crawler: retries of failed fetches with exponential backoff via queue visibility timeouts, DLQ after a maximum number of attempts, per-domain politeness limits as back pressure.
- Design a Chat System: message ACK timeouts with server-side redelivery, heartbeats to detect dead connections, idempotent message IDs.
- Design a Payment System: idempotency keys, retries against payment providers with backoff, breakers and fallback between providers, reconciliation for unknown outcomes.
- Design a Notification System: priority queues as bulkheads, provider retries and DLQs, rate limits per provider.
In the Interview#
Deep Dive: queueing maths of overload and goodput collapseShow
Model a server as a queue with arrival rate λ and service rate μ, and let utilisation be ρ = λ/μ. For a simple M/M/1 queue, the mean time in the system is W = 1/(μ − λ). This grows without bound as ρ approaches 1. With μ = 1,000 requests/s:
- at ρ = 0.5, W = 2 ms;
- at ρ = 0.9, W = 10 ms;
- at ρ = 0.99, W = 100 ms;
- at ρ ≥ 1, the queue grows forever.
Real servers have more variable service times, so the curve bends even earlier. That is why capacity targets of 60–70% utilisation are common for latency-sensitive services.
Now add client timeouts. Suppose clients time out after T = 1 s, and λ = 1,200 requests/s against μ = 1,000. The queue grows at 200 requests/s. After 5 seconds, it holds 1,000 requests, so a new request waits about 1 s, and every request now times out. The server still completes 1,000 requests a second, so its throughput is fine, but goodput is zero, because every completed response arrives after the client left. If each timed-out client retries, λ rises to around 2,400. The overload deepens, and stays even after the original surge ends. That is metastability.
Load shedding changes the outcome. Cap the queue at 100 requests, about 100 ms of wait. The server serves 1,000 requests/s with a latency of about 100 ms, and rejects 200/s immediately. Goodput is 1,000/s instead of 0. Rejected clients back off with jitter, and many succeed on retry once the surge eases. With adaptive LIFO, even an uncapped queue serves the newest requests first, so most completions arrive within the timeout. The arithmetic shows why the order of defences matters: bound the queue first, then shed cheaply, then make retries polite.
Deep Dive: adaptive concurrency limits as congestion controlShow
TCP solved a similar problem decades ago. Senders don't know the network's capacity, so they probe for it. TCP Reno grows its window additively and halves it on loss (AIMD: additive increase, multiplicative decrease). TCP Vegas (Brakmo and Peterson, 1994) instead watches round-trip time. If the RTT rises above the minimum observed, queues are forming, and the sender backs off before loss occurs.
Service concurrency limits can apply the same ideas.
- AIMD on errors or timeouts: raise the limit by 1 per successful window; cut it by, say, 10–50% on a timeout or a shed response. This is simple and robust, but it reacts only after damage.
- Vegas-style on latency: estimate the queue as limit × (1 − RTT_min ÷ RTT_current). If the queue estimate is below α, raise the limit. If it's above β, lower it. The limit hovers around the point where latency starts to rise, which is the knee of the throughput-latency curve.
- Gradient: compute gradient = RTT_noload ÷ RTT_current (≤ 1 when queueing), then set new_limit = limit × gradient + queue_allowance, smoothed over time. Netflix's concurrency-limits library describes a gradient algorithm of this kind.
Practical issues:
- RTT_min drifts. After a deploy, the true no-load latency changes. Algorithms periodically reset or slowly age the minimum, or probe by reducing the limit briefly.
- Mixed workloads. Cheap and expensive requests share a limit, so a shift in mix looks like a capacity change. Separate limits per request class, which are bulkheads, keep the signal clean.
- Client-side versus server-side. A server-side limit protects the server from all callers. A client-side limit, per destination, prevents one client from contributing to overload, and spreads the response across clients. Both can run at once.
- Stability. Aggressive gains oscillate. Smoothing, plus minimum and maximum bounds, keeps limits stable.
The result is load shedding that tracks real capacity. When a dependency of the server slows down, the server's latency rises, its limit falls, and it sheds the excess automatically. Nobody has to retune thresholds after each release.
Deep Dive: designing an end-to-end resilience policyShow
Patterns interact, so design them together for each call path, and write the policy down. Take a checkout path: browser → API gateway → order service → (inventory, payment, recommendations).
- Deadline: the browser request has a 3 s deadline, and the gateway propagates it. The order service passes the remaining deadline minus 50 ms to each dependency.
- Timeouts per dependency (from p99.9): inventory 200 ms, payment provider 2 s (it is known to be slow), recommendations 150 ms.
- Retries: only the gateway retries idempotent GETs, once, with full jitter. The order service retries the payment provider only with an idempotency key, at most twice, within the remaining deadline. When the outcome is unknown after a timeout, it queries the payment's status rather than blindly re-charging. Inventory and recommendations aren't retried inside the order service.
- Breakers: on the payment provider (an open breaker routes to a secondary provider, if one is contracted and tested; otherwise "payment temporarily unavailable"), and on recommendations (open → omit the widget).
- Bulkheads: 50 concurrent payment calls per instance (λ ≈ 20/s × W ≈ 1 s ≈ 20, doubled with headroom); 30 for recommendations; inventory shares a database connection pool partition that has been sized separately.
- Shedding: the gateway sheds browsing traffic before checkout traffic under overload. Each order-service instance caps in-flight requests at 300, with an adaptive limit.
- Async work: confirmation emails and loyalty points are queued, with retries, a DLQ after 5 attempts, and alerts on DLQ growth.
- Errors: the API returns Problem Details with a correlation ID. 503s carry
Retry-After. The browser shows "We're confirming your payment" if the outcome is unknown, and polls the order status.
Then verify the policy with fault injection.
- Add 2 s of latency to recommendations: the widget vanishes, and checkout's p99 barely moves.
- Make the payment provider return 503s for 30%: the breaker opens, the secondary takes over, and retries stay under budget.
- Kill an inventory replica: requests fail over, and the breaker doesn't trip fleet-wide.
Each test checks a number written in the policy. This is how resilience becomes an engineered property instead of a set of library defaults.
Key Takeaways#
- Most outages spread through slowness, not crashes. Timeouts, sized from measured percentiles and nested within propagated deadlines, are the first defence.
- Retry transient failures only, with exponential backoff, full jitter, a small attempt cap, idempotency keys, and a retry budget. Retry at one layer, not all of them.
- Circuit breakers stop calls to failing dependencies. Count slow calls as failures, require a minimum volume, and remember that breaker state is per instance.
- Bulkheads contain damage by partitioning threads, connections, queues and capacity. Size them with Little's Law, and accept the efficiency cost.
- Fallbacks must be independent of what failed, and tested continuously. Often a design that needs no fallback is better.
- Load shedding protects goodput: reject early and cheaply, by priority, with
Retry-After. Use queue-time limits, LIFO or CoDel, and adaptive concurrency limits. - Back pressure propagates limits upstream, through bounded queues, flow control and lag-based scaling. Shed at the edge, and push back inside.
- Give clients a clear error contract: honest status codes, Problem Details,
Retry-After, idempotency keys, correlation IDs.