Building Resilient Data Fetching with Retry Strategies
A deep guide to resilient data fetching: exponential backoff, circuit breakers, jitter, and retry budgets for production services.
On this page
Introduction
Every production application talks to things it does not control. A database restarts, a third-party API rate-limits you, a DNS lookup times out, a colleague deploys a service that is briefly unavailable. The difference between a system that degrades gracefully and one that pages you at 3 a.m. is rarely the happy path — it is the retry strategy. Naive retries, written in five minutes, are responsible for a surprising amount of production pain: thundering herds, retry storms, requests that never terminate, and cascading failures that take down services far from the original fault.
This article is a deep, practical guide to building resilient data fetching. We will move from why a simple while (retries < 3) loop is dangerous, through exponential backoff and jitter, retry budgets and deadlines, and finally to circuit breakers and the composition of all of these into a single coherent policy. The code examples are in TypeScript, but the patterns transfer directly to Go, Python, Rust, and any language with an async runtime.
Why Naive Retries Are Dangerous
A retry is a bet: you are betting that the failure was transient. When you lose that bet — when the failure is permanent, or when every other caller is making the same bet simultaneously — retries amplify load instead of absorbing it. Consider the most common naive implementation:
async function fetchWithRetry<T>(url: string, retries = 3): Promise<T> {
for (let attempt = 0; attempt <= retries; attempt++) {
try {
const res = await fetch(url);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return (await res.json()) as T;
} catch (err) {
if (attempt === retries) throw err;
}
}
throw new Error("unreachable");
}
This looks harmless. It is not. Three problems dominate. First, there is no delay between attempts, so on a slow dependency you fire four requests back-to-back, multiplying your own load and the dependency’s. Second, it retries on every error including HTTP 400 and HTTP 401, which are permanent and will never succeed no matter how many times you ask. Third, every concurrent caller retries independently, so a ten-second downstream blip with fifty in-flight requests becomes two hundred requests the instant the dependency recovers — a retry storm that can knock it right back down.
The fix is not to stop retrying. The fix is to retry intelligently: with delays that grow, with randomness that spreads load, with a budget that caps total retry effort, and with a circuit breaker that stops you from retrying at all when things are clearly broken.
Exponential Backoff
Exponential backoff means each successive retry waits longer than the last. The wait grows geometrically rather than linearly, which gives a recovering service progressively more breathing room. The canonical formula is:
function backoff(attempt: number, baseMs: number, capMs: number): number {
return Math.min(capMs, baseMs * 2 ** attempt);
}
// backoff(0, 100, 30_000) = 100ms
// backoff(1, 100, 30_000) = 200ms
// backoff(2, 100, 30_000) = 400ms
// backoff(6, 100, 30_000) = 6400ms
The baseMs is the initial delay and capMs prevents the sequence from growing without bound — important because a retry scheduled for ten minutes in the future is almost never useful and ties up memory holding the pending promise. A cap of thirty seconds is a reasonable default for most API calls; for background jobs you might allow minutes.
Backoff alone solves the “fire four requests instantly” problem, but it introduces a new one: synchronization. If a service restarts and a hundred clients all fail at the same instant, they will all retry at exactly 100ms, then exactly 200ms, then exactly 400ms. The recovery traffic is bursty and phased, which can overwhelm the freshly-restarted service in a phenomenon called thundering herd.
Jitter: Breaking the Synchronization
Jitter is randomness added to the delay to spread retries across a window instead of concentrating them at a single point. There are two common strategies. Full jitter picks a uniform random value between zero and the full backoff, which maximizes spread. Equal jitter picks a value between half the backoff and the full backoff, which preserves a minimum delay while still spreading the upper half.
function withFullJitter(delay: number): number {
return Math.random() * delay;
}
function withEqualJitter(delay: number): number {
return delay / 2 + Math.random() * (delay / 2);
}
function retryDelay(attempt: number, baseMs = 100, capMs = 30_000): number {
const exp = Math.min(capMs, baseMs * 2 ** attempt);
return withFullJitter(exp);
}
Full jitter is the safer default because it can return zero, letting a genuinely transient failure (a single dropped packet) retry immediately while still spreading the bulk of retries. AWS documented this approach in their exponential backoff paper, and it is the strategy used by the AWS SDK, gRPC clients, and most mature retry libraries. Use equal jitter when you want to guarantee a minimum spacing between attempts, for example when you know the downstream service needs at least some time to recover.
Retrying Only What Is Retryable
Retrying a 400 Bad Request is a waste of a round trip and a slot in your connection pool. Retrying a 500 is usually reasonable. Retrying a 429 Too Many Requests is reasonable only if you respect the Retry-After header. Classify errors before you retry:
type RetryDecision = "retry" | "giveup";
function classify(status: number, err?: unknown): RetryDecision {
// Network errors and timeouts are transient.
if (err instanceof TypeError) return "retry"; // fetch() throws TypeError on network failure
if (status === 0) return "retry";
// 5xx: server error, likely transient.
if (status >= 500 && status < 600) return "retry";
// 429: rate limited — retry, but the caller should honor Retry-After.
if (status === 429) return "retry";
// 4xx (except 429): client error, permanent.
return "giveup";
}
For 429, parse the Retry-After header (it may be seconds or an HTTP date) and use it as the delay for that attempt, overriding your computed backoff. Honoring Retry-After is not just courtesy — it is the difference between recovering gracefully and being rate-limited harder on every retry.
Idempotency matters here too. A retry re-sends the request. If the request is a POST that charges a credit card, retrying it can double-charge the customer. Only retry idempotent methods (GET, HEAD, OPTIONS, PUT, DELETE) by default. For non-idempotent POST, retry only if you have an idempotency key and the server promises to deduplicate — Stripe, for example, supports an Idempotency-Key header for exactly this reason.
Retry Budgets and Deadlines
A retry budget caps the total number of retries across all in-flight operations, not just per request. If your service handles a thousand concurrent requests and each is allowed three retries, a downstream blip can produce three thousand extra requests. A budget of, say, ten percent of total requests means at most ten percent of operations may retry at any time; once the budget is exhausted, new failures fail fast instead of retrying. This protects the downstream service from your retry storm and protects your own service from the latency tail of queued retries.
class RetryBudget {
private tokens: number;
constructor(private readonly max: number, private readonly refillPerSec: number) {
this.tokens = max;
}
tryAcquire(): boolean {
this.refill();
if (this.tokens >= 1) { this.tokens -= 1; return true; }
return false;
}
private refill() {
const now = Date.now();
const elapsed = (now - this.lastRefill) / 1000;
this.tokens = Math.min(this.max, this.tokens + elapsed * this.refillPerSec);
this.lastRefill = now;
}
private lastRefill = Date.now();
}
Pair the budget with a deadline. A retry that would land after the overall deadline is pointless — the caller has already given up. Compute the remaining time before each attempt and stop when the next delay would exceed it. Deadlines propagate: if your handler has a five-second budget and the downstream call has already consumed three seconds, the retry should be capped at two seconds, not the call’s own thirty-second timeout.
The Circuit Breaker
A circuit breaker stops you from calling a service that is demonstrably broken. It has three states: closed (calls flow normally), open (calls fail immediately without hitting the network), and half-open (a limited probe to test whether the service has recovered). The breaker opens when failures exceed a threshold within a rolling window, stays open for a cooldown period, then transitions to half-open where a single trial call is allowed. If the trial succeeds, the breaker closes; if it fails, it reopens.
type CircuitState = "closed" | "open" | "half-open";
class CircuitBreaker {
private state: CircuitState = "closed";
private failures = 0;
private openedAt = 0;
constructor(
private readonly failureThreshold = 5,
private readonly cooldownMs = 10_000,
private readonly halfOpenMaxCalls = 1,
) {}
async exec<T>(fn: () => Promise<T>): Promise<T> {
if (!this.allowCall()) throw new Error("circuit open");
try {
const result = await fn();
this.onSuccess();
return result;
} catch (err) {
this.onFailure();
throw err;
}
}
private allowCall(): boolean {
if (this.state === "closed") return true;
if (this.state === "open") {
if (Date.now() - this.openedAt >= this.cooldownMs) { this.state = "half-open"; return true; }
return false;
}
return true; // half-open: allow limited probe
}
private onSuccess() { this.failures = 0; this.state = "closed"; }
private onFailure() {
this.failures++;
if (this.state === "half-open" || this.failures >= this.failureThreshold) {
this.state = "open"; this.openedAt = Date.now();
}
}
}
The circuit breaker is the complement of retries. Retries handle transient failures by trying again; the breaker handles sustained failures by not trying at all. When the breaker is open, you should return a fallback (cached data, a default, a degraded response) rather than an error, so the user sees something useful instead of a spinner.
Composing a Complete Policy
A production-grade fetch policy composes all of these: classify the error, check the budget, consult the breaker, compute a jittered backoff, honor Retry-After, and stop at the deadline. Here is a complete, composable implementation:
interface RetryOptions {
attempts?: number;
baseDelayMs?: number;
maxDelayMs?: number;
deadlineMs?: number;
retryOn?: (status: number, err?: unknown) => boolean;
}
async function resilientFetch(url: string, opts: RetryOptions = {}): Promise<Response> {
const {
attempts = 4,
baseDelayMs = 100,
maxDelayMs = 30_000,
deadlineMs = 10_000,
retryOn = (s, e) => s >= 500 || s === 429 || !!e,
} = opts;
const deadline = Date.now() + deadlineMs;
for (let attempt = 0; attempt < attempts; attempt++) {
if (Date.now() >= deadline) throw new Error("deadline exceeded");
try {
const res = await fetch(url, { signal: AbortSignal.timeout(deadline - Date.now()) });
if (res.ok) return res;
if (!retryOn(res.status)) throw new Error(`HTTP ${res.status}`);
const retryAfter = res.headers.get("retry-after");
let delay = retryAfter ? parseRetryAfter(retryAfter) : withFullJitter(Math.min(maxDelayMs, baseDelayMs * 2 ** attempt));
delay = Math.min(delay, deadline - Date.now());
if (delay <= 0) throw new Error("deadline exceeded");
await sleep(delay);
} catch (err) {
if (err instanceof Error && err.message === "deadline exceeded") throw err;
if (!retryOn(0, err) || attempt === attempts - 1) throw err;
await sleep(withFullJitter(Math.min(maxDelayMs, baseDelayMs * 2 ** attempt)));
}
}
throw new Error("max attempts exceeded");
}
function parseRetryAfter(value: string): number {
const asNum = Number(value);
if (!Number.isNaN(asNum)) return asNum * 1000;
return Math.max(0, Date.parse(value) - Date.now());
}
function sleep(ms: number) { return new Promise(r => setTimeout(r, ms)); }
This single function embodies every principle above. It is not the end of the road — you would still wrap it with a circuit breaker and a retry budget at the service boundary — but it is a vast improvement over the naive loop and is safe to run in production.
Observability and Testing
A retry strategy you cannot see is a retry strategy you cannot tune. Emit a structured log or metric on every attempt: the attempt number, the status, the delay chosen, whether the Retry-After header was honored, and the outcome. Aggregate these into a “retry rate” metric (retries per request) and alert when it climbs — a rising retry rate is an early signal of a degrading dependency, often before error rates move.
Test the strategy under failure. Use a mock server that returns 503 for the first three calls and 200 thereafter and assert that your client recovers on the fourth. Test the deadline by configuring a server that hangs and asserting the client gives up within the deadline. Test the breaker by driving failures past the threshold and asserting subsequent calls fail fast without hitting the network. These are not unit tests of the happy path — they are the tests that prove your resilience works, and they are the tests most teams never write.
Conclusion
Resilient data fetching is the product of several small, composable ideas: classify errors before retrying, wait with exponential backoff, add jitter to avoid synchronization, cap total retries with a budget, bound every call with a deadline, and stop calling broken services with a circuit breaker. None of these is clever on its own; their power is in composition. Start by replacing your naive retry loop with the resilientFetch above, add a circuit breaker at the boundary of each external dependency, and instrument everything. Your on-call rotation will thank you.
Report a problem with this articleOpens a pre-filled issue on GitHub.