By Gaurav · · 19 min read
- distributed-systems
- reliability
- backend
- resilience
- performance
At 14:02, one replica of the primary database starts pausing for 200 milliseconds every few seconds. It is not down. It is slow.
The API timeout is 500 milliseconds. A handful of requests exceed it, the client retries, and the retry policy — which nobody budgeted — quietly doubles the load on a database that is already struggling. p99 climbs from 400 milliseconds to 900, so more requests time out, so more clients retry. By 14:09 the replica is healthy again, but the service is not. The retry traffic is now the load. The trigger is gone; the feedback loop remains.
That sequence is not a story about a badly chosen timeout. It is a story about treating retries as a local reliability feature when they are a global load amplifier. Every retry is a new request. Every timeout is a decision to stop waiting, not a decision to stop work. Every queue is a promise to do something later that you may not have the capacity to do at all.
This article builds the model that connects those pieces: deadlines that compose across services, retries that spend a budget instead of multiplying, jitter that breaks synchronization, circuit breakers that shed load, and backpressure that makes the limit explicit. The code examples run in the browser and model the decision logic rather than the network, so you can watch the feedback loop happen.
Reliability features that add load
A retry adds a request. A short timeout creates more retries. A queue absorbs load until the moment it turns latency into an outage. A circuit breaker rejects work. None of these mechanisms creates capacity. They decide which work gets to consume the capacity that exists.
That is why the unit of design is not "the request." It is the logical operation and its total budget: how long the user is willing to wait, how many attempts that budget can fund, which of those attempts are safe to repeat, and what the system does when the budget runs out.
If you take one idea from this article, take this one: a retry is not free, and it is not local. The cost of a retry is paid by the dependency, by every hop between you and the dependency, and by every other request that is now waiting behind it.
A timeout is a deadline, not a guess
"Timeout" is an overloaded word. A production client usually has several, and they bound different things:
| Timeout | What it bounds | Common mistake |
|---|---|---|
| Connect | Establishing TCP and TLS | Setting it too short for cross-region calls, then retrying calls that never had a chance |
| Read | The gap between bytes, not total duration | Assuming it caps the whole response; a slow drip can run forever |
| Request | The whole call, from send to last byte | Configuring it independently at every hop |
| Idle | A kept-alive connection with no traffic | Confusing it with a request timeout |
| Deadline | An absolute point in time carried with the request | Not propagating it, so children cannot know the parent has given up |
The request timeout is the one people reach for, and it is also the one that composes worst. If the edge allows 2 seconds, the gateway allows 2 seconds, and the service allows 2 seconds, the end-to-end budget is not 2 seconds. It is up to 6 seconds of sequential waiting, plus retries, plus the time to serialize and stream the response. Each layer believes it is the only layer with a timeout.
A deadline fixes this because it is absolute. It does not matter when a child call starts; the child can compare the deadline to its own clock and know exactly how much time remains. The parent passes the deadline down, and every hop subtracts the time it has already spent before making the next call.
function budgetFor(deadline, hop) {
const remaining = deadline - Date.now();
const usable = remaining - hop.margin;
return usable <= 0 ? 0 : Math.min(hop.max, usable);
}
async function call(name, timeoutMs, latencyMs) {
if (timeoutMs <= 0) throw new Error(`${name}: no budget left`);
await new Promise((resolve) =>
setTimeout(resolve, Math.min(latencyMs, timeoutMs)),
);
if (latencyMs > timeoutMs) {
throw new Error(
`${name}: ${timeoutMs}ms budget is shorter than ${latencyMs}ms latency`,
);
}
return `${name}: ok in ${latencyMs}ms`;
}
const deadline = Date.now() + 120;
const hops = [
{ name: "auth", max: 50, margin: 10, latency: 30 },
{ name: "inventory", max: 60, margin: 10, latency: 40 },
{ name: "payment", max: 70, margin: 10, latency: 55 },
];
for (const hop of hops) {
const timeout = budgetFor(deadline, hop);
try {
console.log(await call(hop.name, timeout, hop.latency));
} catch (error) {
console.log(String(error.message));
}
}
The important line is the subtraction, not the timer. A child that receives a fresh two-second timeout after its parent has 80 milliseconds left is not being given a budget. It is being given a way to waste the parent's remaining time.
Two rules follow from this:
- Set the end-to-end deadline first, at the edge, from the user's tolerance. Then derive every downstream timeout from what remains.
- Leave a margin. The last hop before the deadline still needs time to encode the response, write a log line, and let the parent handle the error. A child timeout that exactly equals the remaining budget guarantees the parent will time out while formatting the child's timeout error.
Timeouts do not cancel work
A client-side timeout is a statement that the client stopped waiting. It is not a statement that the server stopped working. The request may already be inside a transaction, halfway through a file upload, or about to commit a write.
This is why a timeout is inseparable from idempotency. If the operation is safe to repeat, a retry after a timeout is a reasonable bet. If it is not, the retry is a way to perform the write twice. The server cannot generally tell the difference between "the client gave up" and "the network dropped the response," and both look identical to the client.
[!WARNING] A timeout does not prove the request failed. Retrying a non-idempotent operation after a timeout is how you get duplicate charges, double-sent emails, and inventory that decrements twice.
Retries multiply load
On paper, retries are modest. If each attempt fails independently with probability p, the expected number of attempts for a request with n allowed tries is:
1 + p + p² + ... + p^(n-1) = (1 - p^n) / (1 - p)
With a 10% failure rate and three attempts, that is 1.11 attempts per request. An 11% overhead. That is the math a retry library shows you in its README.
The real system does not behave like the README, because p is not independent of load. The dependency fails more often when it is busy, retries make it busier, and the failure rate rises. The formula is stable only while the retry load is small. Once retries become a meaningful fraction of traffic, the assumption that p is constant is exactly the assumption that stops being true.
The load also multiplies across layers. Each layer that retries three times does not add three requests. It multiplies the layer below it:
| Layer | Attempts | Requests reaching the dependency |
|---|---|---|
| Client or SDK | 3 | 3 |
| API gateway | 3 | 9 |
| Service | 3 | 27 |
| Database driver | 3 | 81 |
Nobody configured 81 requests. Each team configured a reasonable local policy: three tries, because three is what the library defaults to. The multiplication is emergent, and it is invisible in any single service's configuration.
There is a second, subtler multiplier: a retried request may still be running. When the client times out at 500 milliseconds and retries, the original request can continue inside the server for another two seconds. If the operation is expensive, the retry adds capacity pressure even though the first response was never delivered. The dependency sees two requests; the client sees one logical operation.
function expectedAttempts(failureRate, maxAttempts) {
let expected = 0;
let reach = 1;
for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
expected += reach;
reach *= failureRate;
}
return expected;
}
for (const p of [0.01, 0.05, 0.1, 0.3, 0.5]) {
const perRequest = expectedAttempts(p, 3);
const worstCase = 3 ** 4;
console.log(
`p=${p.toFixed(2)} attempts/request=${perRequest.toFixed(2)} ` +
`worst case across 4 layers=${worstCase}`,
);
}
The expected number is the friendly view. The worst case is the bound, and the worst case is what an overloaded dependency experiences: if every layer is failing, every layer retries, and the request tree fans out until something gives.
Backoff gives the dependency time; jitter gives it space
Exponential backoff is the standard first fix. Instead of retrying immediately, wait 100 milliseconds, then 200, then 400, up to a cap. The growing delay gives the dependency room to recover instead of hammering it at the exact moment it is least able to respond.
Backoff alone is not enough. If every client uses the same base delay and the same schedule, they all wake up at the same time. A thousand clients that failed at 14:02:00 retry at 14:02:00.100, then at 14:02:00.300, then at 14:02:00.700. The result is a series of synchronized spikes, which is indistinguishable from a traffic surge. This is the thundering herd, and it is a property of the schedule, not of the clients.
Jitter randomizes the delay. The common policies:
| Policy | Delay | Character |
|---|---|---|
| Fixed | base |
Synchronizes every client; avoid |
| Exponential | base * 2^attempt |
Better spacing, still synchronized without jitter |
| Full jitter | random(0, min(cap, base * 2^attempt)) |
Maximum spread; the usual default |
| Equal jitter | ceiling / 2 + random(0, ceiling / 2) |
Keeps a floor while still spreading |
| Decorrelated | min(cap, random(base, previous * 3)) |
Good for long-lived clients and repeated retries |
Full jitter can produce a delay close to zero. That is acceptable: the goal is to spread the retries, not to guarantee a minimum wait. If the dependency needs a floor before it can make progress, equal jitter gives you one.
function mulberry32(seed) {
return function random() {
seed |= 0;
seed = (seed + 0x6d2b79f5) | 0;
let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
function simulate(policy, seed = 7) {
const random = mulberry32(seed);
const clients = 500;
const attempts = 5;
const base = 50;
const cap = 800;
const buckets = new Map();
for (let client = 0; client < clients; client += 1) {
let elapsed = 0;
for (let attempt = 0; attempt < attempts; attempt += 1) {
const ceiling = Math.min(cap, base * 2 ** attempt);
elapsed += policy(ceiling, random);
const bucket = Math.floor(elapsed / 10) * 10;
buckets.set(bucket, (buckets.get(bucket) ?? 0) + 1);
}
}
const sorted = [...buckets.entries()].sort((a, b) => a[0] - b[0]);
return {
peak: Math.max(...sorted.map(([, count]) => count)),
sorted,
};
}
const fixed = (ceiling) => ceiling;
const fullJitter = (ceiling, random) => Math.floor(random() * ceiling);
for (const [name, policy] of [
["fixed", fixed],
["full jitter", fullJitter],
]) {
const { peak, sorted } = simulate(policy);
console.log(
`${name}: peak=${peak} retries in a 10ms bucket ` +
`buckets=${sorted.length}`,
);
console.log(
sorted
.slice(0, 8)
.map(([time, count]) => `${time}ms:${count}`)
.join(" "),
);
}
Five hundred clients, five retries each, same failure time. With fixed backoff, the retries arrive in five enormous bursts. With full jitter, the same 2,500 retries are spread across the same window and the peak is a fraction of the size. The dependency sees the same total work, but it sees it at a rate it can survive.
Jitter does not reduce the number of retries. It reduces the probability that they arrive together. That is often the difference between a slow dependency and a failed one.
Cap the retries, not just the delay
Backoff and jitter shape when retries happen. A retry budget limits whether they happen at all.
The idea, popularized by Google's SRE practice, is to treat retries as a small, bounded fraction of total request volume. If a service handles 10,000 requests per second and its retry budget is 10%, it may issue at most 1,000 retries per second. The budget is shared across all callers of that dependency. When the dependency starts failing, the budget is consumed quickly, and further retries are rejected. The clients fail fast instead of adding fuel to the fire.
A token bucket is a practical implementation: every request adds a fraction of a token, every retry removes one, and the bucket has a burst capacity so a short outage does not instantly exhaust it.
function createBudget({ ratio = 0.1, burst = 100 } = {}) {
let tokens = burst;
let retries = 0;
let denied = 0;
return {
onRequest() {
tokens = Math.min(burst, tokens + ratio);
},
onFailure() {
if (tokens < 1) {
denied += 1;
return false;
}
tokens -= 1;
retries += 1;
return true;
},
report() {
return { retries, denied, tokens: Math.round(tokens) };
},
};
}
function run(failEvery) {
const budget = createBudget();
const requests = 10_000;
for (let i = 0; i < requests; i += 1) {
budget.onRequest();
if (i % failEvery === 0) budget.onFailure();
}
return budget.report();
}
console.log("normal, 1% failures: ", run(100));
console.log("incident, 33% failures:", run(3));
At a 1% failure rate, the budget covers every retry. At a 33% failure rate, most retries are denied. That is the intended behavior: the retry budget converts an unbounded feedback loop into a bounded one. The clients that are denied a retry return an error sooner, which frees capacity for requests that still have a chance to succeed.
The budget belongs to the dependency, not to the individual caller. A per-caller budget isolates callers from each other, but it does not bound the aggregate retry load: every caller can spend its own allowance at the same time. A global budget per dependency lets the system make a single decision about how much extra load it is willing to spend on optimism, and a per-caller limit can sit inside it so one noisy caller cannot consume the whole allowance.
Retry only what can succeed on a retry
Not every error is a transient failure. Retrying a validation error just repeats the same mistake, and retrying a non-idempotent write can duplicate it.
| Retry | Do not retry |
|---|---|
| Connection reset before the request was sent | 400 Bad Request |
408 Request Timeout on an idempotent operation |
401 Unauthorized, 403 Forbidden |
429 Too Many Requests, honoring Retry-After |
404 Not Found |
502, 503, 504 from a gateway or upstream |
409 Conflict unless the conflict is known to be transient |
| Temporary DNS failure | 422 Unprocessable Entity |
| A leader election or failover error | TLS certificate or protocol mismatch |
500 is the ambiguous one. It can be a transient bug in a dependency or a deterministic failure in your own handler. Retry it only if the operation is idempotent, the retry is budgeted, and you have evidence that the error class is transient. "It is a 5xx" is not evidence.
The same table applies to the retry owner. Pick one layer to retry, ideally the layer that understands whether the operation is idempotent. If the gateway retries, the service retries, and the SDK retries, none of them knows how many attempts the operation has already survived.
Idempotency is the license to retry
Retries are at-least-once delivery by construction. The client sends the request, the server may have processed it, and the response may be lost. The only way to make a retry safe is to make the operation idempotent.
Some operations are naturally idempotent: PUT with a full representation, DELETE of a resource that may already be gone, setting a value to a known state. Others are not: POST /payments, POST /messages, incrementing a counter, appending to a log.
For the operations that are not naturally idempotent, the client generates an idempotency key and sends it with the request. The server stores the key and the response in a durable place, scoped to the caller and the operation, with a retention window longer than the maximum retry window. When the same key arrives again, the server returns the stored response instead of performing the work twice.
The subtle part is concurrency. Two retries can arrive at the same time, both miss the deduplication store, and both execute. The fix is a unique constraint or a lock on the key, not a read-then-write check. The first request to insert the key owns the work; the second waits or returns a conflict. A deduplication layer that is only checked after the work is done is a duplicate detector, not a duplicate preventer.
And the retention window matters. If the key expires after one hour and a client retries after two, the operation runs again. The window must cover the client's retry budget plus the time a request can spend in queues, retries, and failover.
Circuit breakers stop spending budget on a broken dependency
A retry budget limits the total volume of retries. A circuit breaker limits the rate at which clients discover that the dependency is broken. It is a local, per-dependency state machine:
stateDiagram-v2
[*] --> Closed
Closed --> Open: failure ratio above threshold
Open --> HalfOpen: cooldown elapsed
HalfOpen --> Closed: probe succeeds
HalfOpen --> Open: probe fails
In the closed state, calls pass through and the breaker records successes and failures over a rolling window. When the failure ratio exceeds a threshold — and the window has enough volume to be meaningful — it opens. In the open state, calls fail immediately without touching the dependency. That is the load shedding. After a cooldown, the breaker moves to half-open and allows a small number of probe requests. If they succeed, it closes; if one fails, it reopens.
Two details make the difference between a useful breaker and a flaky one:
- Require a minimum volume. One failure in a quiet period is not evidence of an outage. A breaker that opens on one failed request will flap all day.
- Scope it per dependency and operation. A breaker on reads should not open because writes are failing against the same database. A breaker on one payment processor should not disable the backup processor.
A circuit breaker does not fix the dependency and does not create capacity. It prevents your service from spending its own threads, connections, and deadlines on calls that are almost certain to fail. That is a worthwhile trade, but it is a trade: while the breaker is open, those requests are failing fast, and the product needs a plan for that state.
Backpressure is the part everyone skips
Retries and timeouts describe what a client does when a dependency is slow. Backpressure describes what a server does when it cannot keep up. Without it, the only backpressure is the queue growing until something crashes or a timeout fires.
The arithmetic is unforgiving. If requests arrive at rate λ and the service can complete work at rate μ, the utilization is ρ = λ / μ. Little's Law relates the number of requests in the system L, the arrival rate, and the time each request spends in the system W:
L = λW
If arrivals exceed the service rate, the queue grows without bound, and so does W. The queue does not create capacity. It converts a capacity problem into a latency problem, and the timeout then converts the latency problem back into a capacity problem when the abandoned requests are retried.
Even below saturation, latency rises sharply as utilization approaches 1. For a simple queue, the average time in the system grows roughly as 1 / (1 - ρ) times the service time. At 50% utilization, a request spends about twice the service time in the system. At 90%, it is about ten times. At 99%, it is about a hundred times. A service at 90% utilization is not "10% away from capacity" in any useful sense; it is already paying a large latency tax, and a small spike is enough to push it over.
The defenses are unglamorous:
- Bound every queue. A queue with no limit is a memory leak with extra steps.
- Size the queue by time, not by items. A queue of 10,000 items is meaningless without knowing the throughput. If the service handles 1,000 items per second, that queue is ten seconds of work. Is ten seconds acceptable for the caller's deadline?
- Reject when full, quickly and explicitly. Return
503 Service UnavailablewithRetry-Afterfor temporary overload, or429 Too Many Requestswhen a specific caller has exceeded a quota. Do not accept work you cannot finish before its deadline. - Limit concurrency, not just request rate. For latency-sensitive work, the number of in-flight requests is a better admission signal than requests per second. A hundred requests per second that each take two seconds is two hundred concurrent requests, not a hundred.
- Shed by priority. Drop background reindexing and analytics before you drop checkout. The system needs a way to say which work matters when capacity is short.
function simulate({ limit, ms = 10_000, arrivalsPerMs = 1.2, servicePerMs = 1 }) {
let queue = 0;
let accepted = 0;
let rejected = 0;
let maxQueue = 0;
let queuedForMs = 0;
let arrivalCredit = 0;
for (let t = 0; t < ms; t += 1) {
arrivalCredit += arrivalsPerMs;
while (arrivalCredit >= 1) {
arrivalCredit -= 1;
if (queue < limit) {
queue += 1;
accepted += 1;
} else {
rejected += 1;
}
}
const served = Math.min(queue, servicePerMs);
queue -= served;
queuedForMs += queue;
maxQueue = Math.max(maxQueue, queue);
}
return {
accepted,
rejected,
maxQueue,
avgQueue: Number((queuedForMs / ms).toFixed(1)),
avgWaitMs: Number((queuedForMs / accepted).toFixed(1)),
};
}
console.log("unbounded: ", simulate({ limit: Infinity }));
console.log("bounded 100:", simulate({ limit: 100 }));
Arrivals are 20% above capacity. The unbounded queue accepts every request and ends with a backlog near 2,000 items, which means the average accepted request waits about 800 milliseconds. That is latency the caller did not budget for, and it is exactly the condition that produces timeouts and retries. The bounded queue rejects roughly 1,900 requests, but the accepted requests wait under 100 milliseconds. The system fails a predictable fraction of work quickly instead of failing all of it slowly.
That trade is the whole point. Load shedding is not a failure to serve; it is a decision about which requests to serve and how long the rest should wait before they are told no.
[!NOTE] Backpressure is a protocol, not a single setting. The client has to respect
Retry-After, the gateway has to enforce concurrency limits, and the service has to bound its queues. A429that the client immediately retries is not backpressure; it is a suggestion.
Put the budget where the failure is
Timeouts, retries, and limits interact, so they need a single owner per stage. A defensible split:
| Layer | Owns | Retries | Timeout |
|---|---|---|---|
| Client or SDK | The user's end-to-end deadline | At most once, only for idempotent calls | The remaining deadline, not a fresh default |
| Edge or API gateway | Admission, quotas, request size | Rarely; prefer to fail fast | Slightly longer than the backend budget |
| Service | Business operation and idempotency | Yes, within a retry budget | Derived from the incoming deadline |
| Database driver | Connection and statement execution | Connection errors only | Shorter than the service's remaining budget |
| Queue consumer | Delivery and redelivery | Yes, with a dead-letter path | Visibility timeout, not a request timeout |
The row that matters most is the service row: the layer that understands idempotency should own the retries. A generic proxy cannot know whether repeating a POST will create a second order. It can know that the connection failed before the request was sent, which is a narrower and safer class of retry.
The edge should not retry by default. It sits in front of everything, so its retries multiply across every service behind it, and it has the least context about what the request does. Let the edge shed load; let the service decide whether a retry is safe.
What to measure
Error rate alone is a poor signal because retries hide degradation. A service with a 1% error rate and a 40% retry ratio is not healthy; it is doing 1.4 requests of work for every request of value, and the dependency is absorbing the difference.
Instrument the things that describe the feedback loop:
- Attempts per logical request. The distribution, not just the mean. A p99 of four attempts is a different system from a p99 of one.
- Retry ratio per dependency. Retries divided by initial requests. Alert when it rises, even if the user-facing error rate is flat.
- Timeout rate by cause. Connect, read, and deadline exceeded are different failures with different fixes.
- Queue depth and queue age. Depth in items is a proxy; age in milliseconds is the number the caller experiences.
- Saturation. In-flight requests divided by the concurrency limit, connection pool usage, and thread pool usage.
- Retry budget denials. A rising denial count means the budget is doing its job, but it also means the dependency is degrading.
- Circuit breaker state changes. An open breaker is a leading indicator, not a lagging one.
- Duplicate suppression counts. If the idempotency layer is rejecting duplicates, the retry volume is already high enough to matter.
Trace one logical request as a parent span with a child span per attempt. Record the attempt number, the deadline remaining when the attempt started, and the error class. Without that, a retry storm and a traffic spike look identical in aggregate charts: both show more requests and more latency.
A default policy you can ship
If you need a starting point rather than a theory:
- Set one end-to-end deadline at the edge from the product's tolerance. Propagate it as an absolute timestamp. Every hop subtracts its own elapsed time.
- Choose timeouts from the healthy p99.9, plus a margin for encoding and error handling. Never from the average.
- Pick one retry owner — usually the service that knows whether the operation is idempotent. Make the other layers fail fast.
- Allow at most two or three attempts, and only for retryable errors on idempotent operations.
- Use exponential backoff with full jitter. Base around 100 to 200 milliseconds, cap around two to five seconds.
- Add a per-dependency retry budget of roughly 10% of total request volume. Reject retries that exceed it.
- Honor
Retry-After. A server that tells you when to come back is giving you a budget; ignoring it is choosing to be part of the problem. - Add a circuit breaker with a minimum request volume and a half-open probe.
- Bound every queue and size it in milliseconds of work, not item count. Reject at the edge before consuming downstream resources.
- Make writes idempotent with a deduplication key whose retention exceeds the maximum retry window.
- Load test a slow dependency, not just a dead one. A dead dependency fails fast; a slow one consumes every thread, connection, and deadline before it fails. The slow failure is the one that produces retry storms.
The last item is the one teams skip. It is easy to simulate a dependency returning 500. It is much more revealing to make it take 1.5 seconds, watch the thread pool fill, and see whether the retry policy turns a latency incident into an availability incident.
The model to keep
Reliability is not the presence of retries. It is the ability to fail a bounded amount of work, quickly, without turning that failure into more load.
A timeout is a budget. A retry spends that budget, and a retry budget caps how much optimism the system can afford. Jitter prevents the retries from arriving as a synchronized wave. Circuit breakers stop spending budget on a dependency that is already broken. Backpressure makes the limit explicit before the queue makes it for you.
The next time a dependency gets slow, watch what your system does in the first thirty seconds. If the answer is "it retries," you have found the mechanism that will decide whether the incident stays small — or becomes the outage.
Distributed systems, databases, and the craft of shipping software.