Systemsfor Aravinda
0 / 78 core
Week 6 · Reliability

Retries, backoff, and circuit breakers

2.5 hours · core path

Read first: Idempotency and the exactly-once myth, Networking for request paths

In one sitting

Retry a call only when repeating it is safe, and only when the attempts still fit in the deadline. Exponential backoff with full jitter keeps the retries from arriving as one wave. A circuit breaker fails fast when a dependency is already dead so it cannot pin every thread, which is what Little's law predicts when latency jumps to seconds.

A retry is a second arrival you chose to create. Sometimes the first arrival never reached the dependency, and the second one saves the request. Sometimes the first arrival committed and the response died on the way back, and the second one does the work again. The whole design is telling those two cases apart, and then refusing to create so many second arrivals that you knock over the thing you were trying to reach.

Core concepts

Retry only when the call is safe to repeat. Idempotency means doing the operation twice has the same effect as doing it once. A natural idempotent write sets state: “balance is 40” lands on 40 no matter how many times you send it. An increment does not. A charge does not. An imposed idempotency key is a client-generated name for this attempt. The server stores the key with the outcome and, on a retry, returns the stored outcome instead of doing the work again. Reads are safe. A put that sets a value is safe. A post that creates a charge is safe only when it carries that key.

If you do not have a key and the operation is not naturally idempotent, do not retry it. Surface the uncertainty to a path that can reconcile. At-least-once delivery plus an idempotent handler is the practical shape. Exactly-once across your database and a third party is not a checkbox on a client, and a retry loop does not create it. The Stripe idempotency pattern is the concrete version of the key: store the outcome, reject the same key with different parameters, and lock so two concurrent retries do not both run.

Bounded retries, then stop. A cap of two or three attempts is a policy, and you should say the number. An unbounded retry is a loop that waits for a dependency that may not return during this incident at all.

Exponential backoff. After a failure, wait before the next attempt. Double the wait each time, and cap it. A common shape, which you label as a policy rather than a law, is a base of 100 ms, then 200 ms, then 400 ms, with a cap at 1 s so a long outage does not schedule retries for tomorrow. The doubling is what keeps a dependent that is slightly late from being hit at a constant extra rate. The cap is what keeps a five-attempt policy from sleeping for half a minute inside a request the user has abandoned.

Full jitter. Sleep a random time up to the cap, not the cap itself. If the computed backoff is 400 ms, draw uniformly from 0 to 400 ms. The failure mode you are buying off is synchronization. A thousand clients that all see the error at the same moment, and all sleep exactly 400 ms, arrive again as a thousand-wide spike. They met the letter of “we backed off” and reproduced the outage. Spread across the window, those same thousand retries are a flat extra load of about a thousand per second for 0.4 s, which a dependency can absorb or shed on purpose. Full jitter is the random draw up to the cap. Do not “jitter” by adding a few milliseconds to a shared sleep. That still arrives as a spike.

A retry budget is the deadline. The user, or the caller above you, handed you a remaining time. Every attempt costs up to its timeout, and every sleep costs up to its cap if you are promising a bound rather than an average. If the sum of the worst case does not fit, you do not get that many attempts. A budget can also be a fleet rule: retries are at most some fraction of outbound calls, so that when the dependency is fully down you do not multiply its traffic by your attempt count. The fraction is a policy. The point is that retries are load, and load needs a cap the same way ordinary traffic does. A rate limit on the dependency is that cap seen from the other side.

Timeouts are part of the attempt, not a separate topic. A timeout longer than the remaining budget will outlive the user. A timeout shorter than the dependency’s normal tail fails healthy calls. Networking for request paths is where the handshake and the request sit in that budget. If you give up, say so downstream. A deadline that propagates, the way a gRPC deadline does, lets the dependency stop work the caller has already abandoned. A client-side timeout that does not cancel is how you occupy a worker on both sides for the same dead request, and then occupy another one with the retry.

Circuit breaker. Three states. Closed means calls go through, and you are counting failures. Open means calls fail immediately for a cool-down, and you do not touch the dependency at all. Half-open means the cool-down has ended and a few trial calls are allowed through. If the trials succeed, you close. If they fail, you open again and start another cool-down.

The breaker exists so a dead dependency does not hold all your threads. A timeout of two seconds with a stuck dependency holds each worker for two seconds. An open breaker holds it for the time it takes to notice the state and return. That is the difference between “this feature is down” and “the whole process is wedged.” The thresholds are policy. You might open after half of the last 20 calls fail, or after 10 consecutive failures, and you cool down for a few seconds. Say the numbers you picked. There is no universal setting hiding in the definition.

While the breaker is open you still owe the caller an answer: a fast error, or a degraded response that does not need the dependency. Load shedding is the matching idea on the inbound side. The breaker is outbound. Both are refusals to let a stall become a pile of waiting work.

In the Netflix open-source years, the client library people meant by this pattern was Hystrix. Hystrix is in maintenance. It is a historical example of a circuit breaker sitting in the calling process, not a statement about what that architecture looks like now. How Netflix streams is the published split between control traffic and the bytes of video, and it is not a circuit-breaker diagram.

flowchart TD
  call[Call arrives]
  closedState[Closed state]
  openState[Open state]
  halfState[Half open state]
  dep[Dependency]
  fast[Fail immediately]
  call --> closedState
  closedState -->|under threshold| dep
  closedState -->|too many failures| openState
  openState -->|during cool down| fast
  openState -->|cool down elapsed| halfState
  halfState -->|trials succeed| closedState
  halfState -->|a trial fails| openState

Half-open is the easy state to get wrong in a fleet. If every instance opens together and every instance ends its cool-down together, the trial calls are a thundering herd. Jitter the cool-down the same way you jitter the backoff, and keep the number of trials small.

A worked example

You are the checkout service. One dependency authorizes payment. These are assumptions, said out loud: arrivals hold at 100 requests per second even while the dependency is slow (an open system, not a benchmark that waits for each response before sending the next one), healthy latency is 50 ms, and during the incident the dependency takes 2 seconds and still returns success at the end. You have 40 workers. The user-facing budget for this hop is 800 ms.

Little’s law, healthy and stuck. Average concurrency equals arrival rate times average latency. If latency doubles and the arrival rate holds, concurrency doubles. Here latency did not double. It went from 50 ms to 2 s, which is a factor of 40, so concurrency does too.

concurrency = arrivals per second * latency in seconds

healthy
100 * 0.050 = 5 calls in flight

dependency at 2 s, arrivals still 100 per second
100 * 2 = 200 calls in flight

latency ratio = 2 / 0.050 = 40
concurrency ratio = 40

workers = 40
wanted in flight = 200
shortfall = 160 calls that have nowhere to run

Five in flight is a quiet pool. Two hundred in flight on a pool of 40 means the pool is saturated and the rest are queued or rejected. If that queue has no bound, the 160-and-growing live in memory until the process dies. That is the load-shedding problem, and it started as a latency problem. Little’s law is why a dependency getting slower is a capacity incident even when it is not returning errors.

Now add a naive retry. Assume the client times out at 1 second, does not cancel the server-side work, and immediately sends one retry. For that 1 second window the arrival rate the dependency sees is about 200 per second, and each call still occupies a slot for 2 seconds if the dependency keeps going after the client left.

client timeout = 1 s, no cancellation
visible arrivals during the retry = 100 original + 100 retries = 200 per second
occupancy if each still runs for 2 s = 200 * 2 = 400
workers available = 40

You multiplied the load, the first attempt is still running, and the user already left. Propagating the deadline is what stops the 2-second leftover. The breaker is what stops you from starting the next one.

What fits in 800 ms. Set the per-attempt timeout to 200 ms. Policy for the sleeps: full jitter with caps of 100 ms after the first failure and 200 ms after the second. Budget the worst case, because a deadline is a bound, not an average. The average sleep is half the cap, and you can say that, but you do not promise the average to the user.

three attempts, worst-case sleeps
attempt 1    200 ms
sleep        100 ms
attempt 2    200 ms
sleep        200 ms
attempt 3    200 ms
sum          900 ms
budget       800 ms
900 is over 800, so the third attempt does not fit

two attempts, worst case
200 + 100 + 200 = 500 ms
500 is under 800, so two attempts fit, with 300 ms to spare

The retry budget is two, not three, and it is two only while the dependency’s healthy tail fits in 200 ms. If the healthy p99 is already 180 ms, a 200 ms timeout will fail real calls and you will retry your own impatience. Latency numbers that matter is the reason you pick the timeout from the tail and the budget together.

Full jitter, same incident. A thousand checkouts fail in the same second. The backoff cap is 1 second. With no jitter, all thousand sleep for 1 second and return as 1,000 requests in the same instant. With full jitter, each sleeps a uniform draw from 0 to 1 second.

no jitter: 1,000 retries at t = 1.0 s
full jitter: 1,000 retries spread over 1 second
average retry rate = 1,000 / 1 s = 1,000 per second, flat

The integral is the same thousand retries. The shape is the difference between a spike the breaker should treat as a new incident and a load the pool can drain.

Opening the breaker. Policy assumption: open when at least 10 of the last 20 calls fail or time out, cool down for 5 seconds, allow 2 trial calls while half-open. Once open, the 100 arrivals per second fail in the process instead of occupying a worker for a second each. The 40 workers stay available for the part of checkout that can still succeed, or for returning a fast error so the client can back off instead of piling on. You have not fixed payment. You have stopped payment from taking the whole service with it. After 5 seconds, two trials go out. If payment is back, you close. If it is not, you open again, and the cool-down should be jittered so the other 19 instances do not trial on the same tick.

Tradeoffs

Choice What you gain What you spend
No retry No duplicate charges, no extra load Any lost response becomes a user-visible failure
Retry with an idempotency key A lost response can be repeated safely Storage for the key and the outcome, and a lock for concurrent retries
Retry a non-idempotent post A feeling that you tried Double charges, double emails, double writes
Exponential backoff, no jitter Clients wait longer each time The herd shares a clock and returns together
Full jitter up to the cap The same retries, spread out Any one client may retry almost immediately
Worst-case budget inside the deadline The user never waits past the promise You get fewer attempts than an average-case sum would suggest
Long timeout, no breaker A slow dependency can still answer Every worker sits in that slowness, and Little’s law fills the pool
Open breaker Fail fast, threads stay free You reject calls that a half-recovered dependency could have served
Half-open with a few trials You notice the recovery Trials too wide, or aligned across the fleet, recreate the stampede
Fleet retry budget A dead dependency sees little extra traffic Some callers give up while a retry would have worked

Pitfalls

  • Retrying a charge or an email because the client timed out. The symptom is duplicate side effects, and the first call had often succeeded. The response is what you lost.
  • Immediate retry. You turn one overloaded second into several, and the dependency never gets the quiet moment it needed.
  • Identical sleeps. Graphs show a clean wave at the backoff interval. Everyone was “well behaved” and still synchronized.
  • Three attempts whose worst case is longer than the deadline. The user is gone, your client is still waiting, and the dependency is still working if you did not cancel.
  • A timeout that is not propagated. Both sides hold a worker for the leftover request, then your retry takes another.
  • A breaker that opens and never trials. The dependency recovered five minutes ago. You are still failing fast, and the on-call cannot tell from the dependency’s graphs because you stopped sending traffic.
  • A cool-down with no jitter. Every instance half-opens together and the trial is a second incident.
  • Treating a deliberate rejection as a reason to open. A dependency that is shedding load with a fast refusal still has some capacity. A fleet-wide open breaker takes the rest of that capacity to zero. Back off, and send less, before you send nothing.
  • Retrying until the call succeeds, with no cap. This is an unbounded queue aimed at a sick host.

In the interview

Put the safety rule first. “I retry only if the operation is idempotent or the request carries an idempotency key. Two attempts, exponential backoff with full jitter, and the worst case has to fit in the remaining deadline. If failures continue, the breaker opens and I fail fast so the pool stays free.”

Then the number. “At 100 per second, a jump from 50 milliseconds to 2 seconds takes concurrency from 5 to 200. A pool of 40 does not survive that, so the breaker and a queue bound are the design, not an optional hardening pass.”

Skip library configuration. Skip a claim that the transport gives you exactly-once. The follow-up is almost always “what if it is not idempotent?” The answer is that you do not retry, or you introduce a key and store the outcome. The follow-up after that is the storm: jitter, a budget, and a breaker so one sick hop cannot multiply.

Early-career interviewers want that path, the Little’s law number, the bottleneck (the worker pool pinned by the slow hop), and one honest tradeoff. The tradeoff is that an open breaker fails some calls that would have succeeded during recovery. You accept that to keep the process alive.

Check yourself

A dependency serves 80 requests per second at 20 milliseconds. It slows to 2 seconds and arrivals hold. What is the concurrency before and after, and what law did you use?

Little’s law: concurrency equals arrival rate times latency. Before, 80 times 0.020 seconds is 1.6 in flight. After, 80 times 2 seconds is 160 in flight. Latency grew by 2 / 0.020 = 100, and concurrency grew by the same factor because arrivals were assumed to hold. A thread pool sized for a handful of in-flight calls is now two orders of magnitude short.

Which of these may be retried without an idempotency key: a read, a request that sets balance to 40, a request that adds 10 to the balance, and a card charge?

The read is safe. Setting the balance to 40 is safe because the second write leaves the same state as the first. Adding 10 is not safe, because the second call moves the balance again. The charge is not safe, because the first call may have captured money before the response was lost. Those two need a key, or they need a human-visible reconciliation, not a blind retry.

One thousand clients time out together and the backoff cap is 2 seconds. What do they do to the dependency with no jitter, and with full jitter?

With no jitter they all arrive again 2 seconds later, as a thousand-request spike. With full jitter each sleeps a random time from 0 up to 2 seconds, so the same thousand retries spread over the 2 seconds, about 500 per second. You did not reduce the number of retries. You removed the synchronization. The cap still has to fit in the caller’s deadline.

The per-attempt timeout is 250 milliseconds and the worst-case sleep between attempts is 100 milliseconds. The caller has 700 milliseconds left. How many attempts fit, and why is a circuit breaker still useful if you already time out?

Two attempts cost 250 plus 100 plus 250, which is 600 milliseconds and fits. A third attempt needs another sleep and another 250, which does not fit in 700. The timeout still occupies a worker for the whole 250 milliseconds on every attempt, and for the whole stall if you set the timeout to the dependency’s worst second. An open breaker returns in microseconds and leaves the pool free. The timeout bounds one call. The breaker stops you making the call.

Based on: Marc Brooker, AWS Builders' Library; Brandur Leach, Stripe idempotency; Google SRE book.