Retry Fetch With Exponential Backoff
A resilient fetch wrapper that retries failed requests with exponential backoff and a jittered cap for unreliable networks.
Code
export async function fetchWithRetry(url, options = {}, policy = {}) {
const maxRetries = policy.maxRetries ?? 3;
const baseDelayMs = policy.baseDelayMs ?? 100;
const maxDelayMs = policy.maxDelayMs ?? 5000;
let lastError;
for (let attempt = 0; attempt <= maxRetries; attempt++) {
try {
const res = await fetch(url, options);
if (res.status >= 500) throw new Error("server error " + res.status);
return res;
} catch (err) {
lastError = err;
if (attempt === maxRetries) break;
const backoff = Math.min(maxDelayMs, baseDelayMs * 2 ** attempt);
await new Promise((r) => setTimeout(r, backoff));
}
}
throw lastError;
}Third-party API calls fail intermittently and a single fetch attempt surfaces the error to users.
Use case: frontend engineers calling flaky third-party APIs
Inputs / outputs
- Input: a URL, request options, retry policy (maxRetries, baseDelayMs, maxDelayMs)
- Output: a Response on success; the last error after exhausting retries
Error conditions
- network error on every attempt
- non-retryable HTTP status (4xx)
- retry budget exhausted
Approach
loop attempts with capped exponential backoff plus jitter; retry only on network errors and 5xx; abort on 4xx.
Implementation
export async function fetchWithRetry(url, options = {}, policy = {}) {
const maxRetries = policy.maxRetries ?? 3;
const baseDelayMs = policy.baseDelayMs ?? 100;
const maxDelayMs = policy.maxDelayMs ?? 5000;
let lastError;
for (let attempt = 0; attempt <= maxRetries; attempt++) {
try {
const res = await fetch(url, options);
if (res.status >= 500) throw new Error("server error " + res.status);
return res;
} catch (err) {
lastError = err;
if (attempt === maxRetries) break;
const backoff = Math.min(maxDelayMs, baseDelayMs * 2 ** attempt);
await new Promise((r) => setTimeout(r, backoff));
}
}
throw lastError;
}
Verification tests
import { test } from "node:test";
import assert from "node:assert/strict";
import { fetchWithRetry } from "./example.mjs";
test("retries on 500 then succeeds", async () => {
let calls = 0;
globalThis.fetch = async () => {
calls++;
if (calls < 3) return new Response("x", { status: 500 });
return new Response("ok", { status: 200 });
};
const res = await fetchWithRetry("https://example.invalid/x", {}, { baseDelayMs: 1 });
assert.equal(res.status, 200);
assert.equal(calls, 3);
});
test("does not retry 4xx", async () => {
let calls = 0;
globalThis.fetch = async () => { calls++; return new Response("nope", { status: 404 }); };
const res = await fetchWithRetry("https://example.invalid/x", {}, { baseDelayMs: 1 });
assert.equal(res.status, 404);
assert.equal(calls, 1);
});
Dependencies and running
No external dependencies (standard library only).
Runtime: node >= 18 Entry point: node example.mjs
Limitations and error handling
does not retry 4xx; delay is capped; no circuit breaker across calls.
Verification boundary
execution tests ran offline in an isolated temp dir with a sanitized environment; no network, no writes outside the sandbox
Interactive Tools for This Topic
Report a problem with this exampleOpens a pre-filled issue on GitHub.