Retries, Backoff, Circuit Breakers and Idempotency
Overview
In a distributed system a request can fail without telling you whether the work happened. A timeout might mean "the server never got it", or "the server did it and the reply was lost". Retrying fixes the first case and can cause damage in the second, such as charging a customer twice.
This lesson covers the four tools that make retrying safe: exponential backoff with jitter (spread retries out), circuit breakers (stop retrying a dead service), timeouts (do not wait forever) and idempotency keys (make repeats harmless).
Detailed Notes
What is it?
A retry is sending a failed request again. Failures that are worth retrying are transient: a brief network glitch, a server restart, a 503 (service unavailable) or 429 (too many requests). Failures that are not worth retrying are permanent: 400 (bad request), 401, 404. Retrying a permanent failure only wastes capacity.
An operation is idempotent if doing it several times has the same effect as doing it once. "Set the user's email to a@b.com" is idempotent. "Add 10 dollars to the balance" is not. In the clients-and-servers lesson you saw that GET, PUT and DELETE are meant to be idempotent while POST usually is not.
Why do we need it?
Failures are normal at scale. If each call has a 0.1% chance of failing and one user action makes 20 internal calls, about 2% of actions hit at least one failure. Retries turn those into successes and hide glitches from users.
But naive retries are dangerous in two ways:
Retry storms. A database slows down. Every client times out and retries immediately, tripling the load on a system that was already struggling, so it fails completely. This is called metastable failure: the retries themselves keep the system down even after the original cause is gone.
Duplicate side effects. The payment succeeded, the response was lost, the client retried, and the customer was charged twice.
How does it work?
Timeouts first
Every network call needs a timeout, a maximum time to wait. Without one, a hung dependency holds your threads forever and your service dies too. Set it from measured latency: if a dependency's p99 is 200 ms, a 500 ms to 1 s timeout is reasonable; 60 s is not. Timeouts combine across layers: the client's overall deadline must be longer than the sum of the retries below it, or the client gives up while the inner retries are still running.
Exponential backoff
Instead of retrying immediately, wait, and double the wait after every failure: exponential backoff. A typical schedule uses a base of 100 ms, a multiplier of 2 and a cap of 5 s.
text
attempt 1 fails -> wait 100 ms
attempt 2 fails -> wait 200 ms
attempt 3 fails -> wait 400 ms
attempt 4 fails -> wait 800 ms
attempt 5 fails -> wait 1,600 ms
attempt 6 fails -> wait 3,200 ms
attempt 7 fails -> wait 5,000 ms (6,400 would be next, capped at 5,000)
Give up after attempt 8 fails: total waiting = 11,300 ms
Jitter
Backoff alone is not enough. If 10,000 clients all fail at the same moment, they all wait exactly 100 ms and retry together, then all wait 200 ms and retry together: the spikes are synchronized. Jitter adds randomness. With full jitter the client sleeps for a random time between 0 and the computed delay, for instance random(0, 400 ms) on the third attempt. The 10,000 retries then spread evenly across the interval instead of arriving as one wall.
Backoff Schedule and Why Jitter MattersEstimation
Request load
100 msafter attempt 1
base
200 msafter attempt 2
x 2
400 msafter attempt 3
x 2
1.6 safter attempt 5
100 x 2^4
5 safter attempt 7
6.4 s capped
No backoff
10,000 at once
all clients retry together, again and again
A retry storm that keeps the server down.
Backoff only
Spikes at 100, 200, 400 ms
same waits, so clients stay synchronized
Better, but still waves of load.
Backoff + full jitter
About 25 per ms
10,000 retries spread over 0 to 400 ms
Smooth, recoverable load.
Key point. Backoff spaces retries out in time. Jitter spreads clients out so they stop retrying in lockstep.
Base 100 ms, multiplier 2, cap 5 s. With jitter each client sleeps a random time up to the delay.
Also set a retry budget: retry at most 2 to 3 times, and cap retries to a share (say 10%) of total traffic. And retry at one layer only. If three stacked services each retry 3 times, the bottom one sees 3 x 3 x 3 = 27 attempts for one user action.
Circuit breaker
Even with backoff, hammering a dead service is wasteful. A circuit breaker wraps calls to a dependency and tracks failures, like an electrical fuse. It has three states:
Closed: normal. Calls pass through. If the failure rate exceeds a threshold (say 50% of the last 20 calls), trip to open.
Open: calls fail immediately without touching the dependency, for a cool-down such as 30 s. This protects the dependency from load and protects you from slow timeouts. Often a fallback is returned: cached data, a default, or a friendly error.
Half-open: after the cool-down, let a few trial calls through. If they succeed, close the circuit; if not, open it again.
Circuit Breaker StatesComparison
Closed
normal operation
1
Calls go through
2
Count recent failures
3
Trip if failures > 50%
of the last 20 calls
No overhead for healthy services
Healthy
Open
fail fast for 30 s
1
Reject calls immediately
2
Return fallback or error
cache, default, 503
3
Wait for the cool-down
Dependency gets time to recover
Callers do not wait on timeouts
Some good requests are rejected
Protecting
Half-open
probe with a few calls
1
Allow 3 trial calls
2
All succeed: close
back to normal
3
Any fails: open again
restart the cool-down
Recovers automatically
Testing
Key point. Fail fast while a dependency is down, then probe carefully before trusting it again.
The breaker protects the failing service and your own threads.
Idempotency keys
For operations that are not naturally idempotent, such as creating a payment, the client generates a unique idempotency key (a random UUID) per logical operation and sends it with every attempt:
The server stores the key together with the result:
First request with this key: do the work, store (key -> response), return it.
Repeat request with the same key: return the stored response and do nothing else.
Same key but a different body: reject with 422, since this is a client bug.
Request still running: return 409 so the client waits rather than starting a second copy.
The check and the insert must be atomic: use a unique constraint on the key column in the database, inside the same transaction as the work. Keep keys for 24 hours or more. For message consumers, the same idea uses the message ID as the key (see the queues lesson), which is how at-least-once delivery becomes effectively exactly-once.
Idempotency Key: The Lost ResponseRequest flow
The charge happens once even though the client sent the request twice.
Interview tip. Never say "just retry on failure" for a write. Ask: is it idempotent? If not, where does the idempotency key live, and what happens if the first attempt is still running? Mention backoff and jitter, and a circuit breaker for dependencies.
Real-world example
A payments API receives a card charge. The mobile app times out after 5 s and retries with the same Idempotency-Key. The server had in fact completed the first charge; it looks up the key, finds the stored result, and returns the original 201 Created with the same payment ID. The customer is charged once. Meanwhile, the app's calls to a flaky currency service pass through a circuit breaker that returns cached rates when open.
System design example
Order service calls Inventory (which sometimes slows to 3 s). Design:
Timeout 800 ms per call to Inventory (its normal p99 is 250 ms).
Up to 2 retries with exponential backoff (100 ms, 200 ms) and full jitter, only on timeouts and 503s.
A circuit breaker opens at a 50% failure rate over 20 calls; while open, the Order service answers "temporarily unavailable" immediately or uses a fallback (accept the order, reserve stock later through a queue).
POST /orders requires an Idempotency-Key; a unique index on the key in the orders table prevents double orders.
Worst-case wait for the user is about 800 + 100 + 800 + 200 + 800 = 2.7 s, within a 3-second deadline; when the breaker opens it drops to a few milliseconds.
Interview discussion. "Retries must be safe and bounded. I'd use timeouts, up to three attempts with exponential backoff and full jitter, a circuit breaker per dependency, and idempotency keys on writes so a repeat returns the stored result instead of repeating the side effect."
Trade-off thinking. More retries raise success rates for transient faults but amplify load during real outages. Longer backoff protects the server but makes users wait. A circuit breaker protects everyone but can reject requests that would have succeeded. Idempotency keys cost storage and a lookup on every write but remove an entire class of bugs.
Key interview takeaway
Retry only transient errors, with timeouts, exponential backoff, jitter and a small budget at a single layer. Add circuit breakers to protect dependencies. Make writes idempotent with a client-generated key stored atomically with the result.
Real World Example
A mobile app times out calling the payments API and retries with the same Idempotency-Key. The server finds the stored result and returns the original 201 with the same payment ID, so the customer is charged once. Calls to a flaky currency service pass through a circuit breaker that serves cached rates while open.