JavaScript Fetch Retry Logic with Exponential Backoff
Retry failed fetch() calls in JavaScript with exponential backoff, jitter, AbortSignal timeouts, a circuit breaker, and idempotency-safe POSTs.
Overview
fetch() throws on network errors and resolves on HTTP errors, so retry logic has to handle both paths, and plain fetch() has no timeout at all. This recipe is the fetch-specific take on retrying: exponential backoff with full jitter, AbortSignal.timeout() and AbortSignal.any() for deadlines that compose with your caller’s signal, Retry-After handling for 429s, a circuit breaker that only counts availability failures, and Idempotency-Key for the POST case. For the language-agnostic version covering Python, Java, and Node patterns, see retry logic with exponential backoff.
When to Use
- Calls to external APIs that occasionally return 5xx, 429, or time out
- Resilient HTTP requests in browser or Node.js 18+ code without a heavy dependency
- Fan-in code where one flaky dependency shouldn’t fail the whole request
- Any retry that must compose with cancellation the caller already owns
Don’t retry blindly, though. Choosing what to retry is the decision that matters most:
| Failure | Retry? | Why |
|---|---|---|
| 5xx (500, 502, 503, 504) | Yes | Transient server-side failure |
429 + Retry-After | Yes | Rate limit — wait exactly what the server asks |
| Network error / timeout | Yes | Never reached the server (usually) |
| 4xx (400, 401, 403, 404, 422) | No | Client error — same request, same result |
| 408 Request Timeout | Maybe | Server closed it early; one retry is reasonable |
| POST without idempotency | No | May have succeeded server-side before the failure |
Prerequisites
- Node.js 18+ or a modern browser (both ship
fetch,AbortSignal.timeout,AbortSignal.any) - A server that returns sane status codes and, ideally,
Retry-Afteron 429
Solution
1. Basic retry with exponential backoff
async function fetchWithRetry(url, options = {}, retries = 3, baseDelay = 1000) {
for (let attempt = 0; attempt <= retries; attempt++) {
try {
const response = await fetch(url, options);
if (response.ok) return response;
if (response.status >= 500 && attempt < retries) {
await sleep(baseDelay * 2 ** attempt);
continue;
}
return response;
} catch (err) {
if (attempt < retries) {
await sleep(baseDelay * 2 ** attempt);
continue;
}
throw err;
}
}
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
const res = await fetchWithRetry("https://api.example.com/data");
const data = await res.json();
2. Timeout, full jitter, and Retry-After
async function fetchWithRetry(url, options = {}, config = {}) {
const {
retries = 3,
baseDelay = 1000,
maxDelay = 30000,
timeoutMs = 10000
} = config;
for (let attempt = 0; attempt <= retries; attempt++) {
// AbortSignal.timeout for the deadline, combined with the caller's
// signal so an outer cancel still aborts in-flight retries
const signal = options.signal
? AbortSignal.any([options.signal, AbortSignal.timeout(timeoutMs)])
: AbortSignal.timeout(timeoutMs);
try {
const response = await fetch(url, { ...options, signal });
if (response.ok) return response;
if (response.status === 429 && attempt < retries) {
const retryAfter = parseInt(response.headers.get("Retry-After") || "0", 10);
const wait = retryAfter > 0
? retryAfter * 1000
: jitterDelay(attempt, baseDelay, maxDelay);
await sleep(wait);
continue;
}
if (response.status >= 500 && attempt < retries) {
await sleep(jitterDelay(attempt, baseDelay, maxDelay));
continue;
}
return response; // 4xx and friends — no retry
} catch (err) {
// AbortError from our timeout IS retryable; from the caller's
// signal it means "cancel", so rethrow immediately
if (options.signal?.aborted) throw err;
if (attempt < retries) {
await sleep(jitterDelay(attempt, baseDelay, maxDelay));
continue;
}
throw err;
}
}
}
// Full jitter — AWS's recommendation: pick randomly inside the window,
// don't just add noise on top of the exponential
function jitterDelay(attempt, baseDelay, maxDelay) {
const ceiling = Math.min(baseDelay * 2 ** attempt, maxDelay);
return Math.floor(Math.random() * ceiling);
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
3. Retry wrapper with a circuit breaker
class CircuitBreaker {
constructor(threshold = 5, resetTimeout = 60000) {
this.threshold = threshold;
this.resetTimeout = resetTimeout;
this.failures = 0;
this.lastFailureTime = null;
this.state = "closed";
}
recordFailure() {
this.failures++;
this.lastFailureTime = Date.now();
if (this.failures >= this.threshold) this.state = "open";
}
recordSuccess() {
this.failures = 0;
this.state = "closed";
}
canExecute() {
if (this.state === "open") {
if (Date.now() - this.lastFailureTime > this.resetTimeout) {
this.state = "half-open";
return true;
}
return false;
}
return true;
}
}
class FetchWithRetry {
constructor(config = {}) {
this.retries = config.retries ?? 3;
this.baseDelay = config.baseDelay ?? 1000;
this.maxDelay = config.maxDelay ?? 30000;
this.timeoutMs = config.timeoutMs ?? 10000;
this.breaker = new CircuitBreaker(
config.breakerThreshold ?? 5,
config.breakerResetTimeout ?? 60000
);
}
// Only availability failures should trip the breaker.
// A definitive 4xx is the client's problem, not the service's.
isAvailabilityFailure(status) {
return status >= 500 || status === 429;
}
async request(url, options = {}) {
if (!this.breaker.canExecute()) {
throw new Error("Circuit breaker is open — requests temporarily blocked");
}
for (let attempt = 0; attempt <= this.retries; attempt++) {
const signal = options.signal
? AbortSignal.any([options.signal, AbortSignal.timeout(this.timeoutMs)])
: AbortSignal.timeout(this.timeoutMs);
try {
const response = await fetch(url, { ...options, signal });
if (response.ok) {
this.breaker.recordSuccess();
return response;
}
if (this.isAvailabilityFailure(response.status)) {
this.breaker.recordFailure();
if (attempt < this.retries) {
await this.waitFor(response, attempt);
continue;
}
}
return response; // definitive status — not a breaker event
} catch (err) {
if (options.signal?.aborted) throw err;
this.breaker.recordFailure();
if (attempt < this.retries) {
await this.sleep(this.jitter(attempt));
continue;
}
throw err;
}
}
}
waitFor(response, attempt) {
if (response.status === 429) {
const retryAfter = parseInt(response.headers.get("Retry-After") || "0", 10);
if (retryAfter > 0) return this.sleep(retryAfter * 1000);
}
return this.sleep(this.jitter(attempt));
}
jitter(attempt) {
const ceiling = Math.min(this.baseDelay * 2 ** attempt, this.maxDelay);
return Math.floor(Math.random() * ceiling);
}
sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
}
const client = new FetchWithRetry({
retries: 4,
baseDelay: 500,
timeoutMs: 8000,
breakerThreshold: 5,
breakerResetTimeout: 30000
});
const res = await client.request("https://api.example.com/users");
const data = await res.json();
4. Retrying a POST safely with Idempotency-Key
POST retries are dangerous because the first attempt may have succeeded before the connection died; retry blindly and you get two orders. The standard fix is an idempotency key: a unique client-generated ID the server deduplicates on.
async function postWithRetry(url, body, config = {}) {
const { retries = 3, baseDelay = 500 } = config;
// One key for the WHOLE logical operation — retries share it,
// a genuinely new operation gets a new key
const idempotencyKey = crypto.randomUUID();
for (let attempt = 0; attempt <= retries; attempt++) {
try {
const response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Idempotency-Key": idempotencyKey
},
body: JSON.stringify(body),
signal: AbortSignal.timeout(10000)
});
if (response.ok) return response;
if (response.status >= 500 && attempt < retries) {
await sleep(baseDelay * 2 ** attempt);
continue;
}
return response;
} catch (err) {
if (attempt < retries) {
await sleep(baseDelay * 2 ** attempt);
continue;
}
throw err;
}
}
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
The catch: the server has to honor Idempotency-Key (Stripe does; check your API’s docs). If it doesn’t, retrying a POST is a coin flip: prefer a dedicated “check then create” endpoint, or make the operation naturally idempotent (PUT with a client-chosen ID).
5. Testing the retry path with MSW
Retry code only really runs when things are already on fire, so test it explicitly. MSW intercepts fetch in both browser tests and Node:
import { http, HttpResponse } from "msw";
import { setupServer } from "msw/node";
import { test, expect, beforeAll, afterAll } from "vitest";
const server = setupServer();
beforeAll(() => server.listen());
afterAll(() => server.close());
test("retries twice on 503 then succeeds", async () => {
let calls = 0;
server.use(
http.get("https://api.example.com/data", () => {
calls++;
return calls < 3
? new HttpResponse(null, { status: 503 })
: HttpResponse.json({ ok: true });
})
);
const res = await fetchWithRetry("https://api.example.com/data",
{}, { retries: 3, baseDelay: 1 }); // baseDelay 1ms keeps the test fast
expect(res.ok).toBe(true);
expect(calls).toBe(3);
});
Setting baseDelay: 1 keeps tests instant while still exercising the full retry path, including the breaker’s failure counting if you point it at the class version.
How It Works
Two failure channels, two answers. fetch() only rejects on network errors (DNS, TCP, TLS, CORS, abort); every HTTP status, including 500 and 404, resolves normally. So the retry wrapper needs both a try/catch for the network path and an if (response.ok) for the HTTP path. That’s the same decision table from “When to Use”, written out.
Backoff math, briefly: attempt n waits baseDelay * 2^n milliseconds, capped at maxDelay. Full jitter (Math.random() * ceiling) beats “exponential plus a little noise” because it spreads retries across the whole window, and AWS’s architecture blog measured it as meaningfully better at preventing synchronized retry storms. When the server tells you exactly how long to wait (Retry-After), that wins over any computed delay; the server knows its own recovery schedule.
Timeouts deserve their own paragraph because fetch() doesn’t have one: a hung request hangs forever. AbortSignal.timeout(ms) is the modern one-liner; the older pattern is new AbortController() plus a setTimeout(() => controller.abort(), ms) you must remember to clear. AbortSignal.any([a, b]) merges signals, which matters when the caller gave you a signal and you still want your own deadline: combining them means either one aborts the attempt. Watch for the subtlety in the examples: a timeout AbortError is retryable (our deadline fired, the server may just be slow), but an abort from the caller’s signal means “stop everything”, so the code checks options.signal?.aborted and rethrows.
The circuit breaker sits above retries, not inside them. Retries handle a service that’s sometimes slow; the breaker handles a service that’s down, stopping calls entirely so it can recover. Key design point in the class version: only availability failures (5xx, 429, network/timeout) count toward the threshold. A stream of legitimate 404s or 400s is the caller’s bug, not an outage; counting those would pop the breaker on healthy traffic.
Finally, the environment story: this is all standard fetch, so it runs identically in the browser and in Node 18+. In Node specifically, fetch is powered by undici, and you can push timeouts and retries into the dispatcher layer instead — new Agent({ connectTimeout, headersTimeout }) plus undici’s built-in RetryHandler — when you’d rather not wrap every call.
Variants
| Approach | Complexity | What you get | Use when |
|---|---|---|---|
| Basic retry | Low | Exponential backoff | Simple scripts, a few endpoints |
| Jitter + timeout | Medium | Full jitter, AbortSignal.timeout, Retry-After | Production browser/Node apps |
| Circuit breaker class | High | Failure accounting, fail-fast recovery | Critical downstream dependencies |
| Idempotency-Key POST | Medium | Safe mutation retries | Payments, orders, registrations |
undici RetryHandler | Medium | Retries at the HTTP-agent layer | Node-only services, central policy |
Best Practices
- Retry only what can fail transiently: 5xx, 429, network errors, timeouts. Anything else is a bug to fix, not something to repeat.
- Cap retries and cap delay.
retries: 3withmaxDelay: 30sis a sane default; an unbounded retry loop is an outage amplifier. - Honor
Retry-Afterover computed backoff whenever it shows up on a 429. - Use full jitter, not “exponential + sprinkle”:
Math.random() * ceilingspreads the herd better. - Give every attempt a deadline:
AbortSignal.timeout(), and merge it with the caller’s signal viaAbortSignal.any()when both exist. - Only retry POSTs with an idempotency story:
Idempotency-Keysupport, a check-then-create endpoint, or PUT semantics. - Log each attempt with its number and the status/error — intermittent failures are impossible to debug blind.
Common Mistakes
- Retrying POSTs bare. The first attempt may have committed server-side; the retry creates a duplicate. Without an idempotency key, don’t retry it.
- No timeout.
fetch()has no built-in deadline, and a hung request blocks every retry. It’s the most common way retry code fails in production. - Retrying 4xx. A 401 or 422 returns the same answer every time; you’re just adding latency to a guaranteed failure.
- Fixed-delay retries. Every 1s is a constant load on a struggling server and a thundering herd when many clients do it together.
- Counting definitive errors in the breaker. A bunch of 404s isn’t an outage; if the breaker counts them, it opens on healthy traffic and blocks good requests.
- Ignoring the caller’s signal. Combining
options.signalwith your timeout viaAbortSignal.any()keeps an outer cancel working;options.signal || controller.signalsilently disables your timeout instead.
See Also
Frequently Asked Questions
Should I retry 4xx errors?
No. 400s, 401s, 403s, 404s, and 422s are client errors, so retrying the same request returns the same result. The only partial exception is 408 Request Timeout, which some servers emit transiently; one cautious retry is defensible. Everything else 4xx: fix the request, don't repeat it.
How is this different from axios retry plugins?
Same idea, different wiring. Axios throws on non-2xx, so retry checks live in the catch reading error.response.status instead of response.ok. Libraries like axios-retry handle backoff for you; with fetch there's no built-in equivalent, which is exactly why you wrap it yourself, or reach for ky, which ships retry/timeout built in.
Does AbortSignal.timeout leak if the request finishes early?
No — AbortSignal.timeout(ms) schedules a timer that the platform clears when the signal is garbage-collected, and it only fires if the timeout actually elapses. The manual AbortController + setTimeout pattern is the one where forgetting clearTimeout causes a real leak (and a spurious abort if the controller outlives the request).
How do I test retry logic without waiting real seconds?
Two levers: inject the delay (pass baseDelay: 1 or a sleep function in config), and mock the server. MSW intercepts fetch in Node tests and browsers; for a pure unit test, a fake fetch that returns 503, 503, 200 in sequence works too. Check the number of calls rather than the elapsed time.
Should the circuit breaker count HTTP 4xx failures?
Generally no — the breaker exists to protect a service that's failing, and a 4xx is the caller's problem. Counting them means a buggy client can open the breaker and block healthy requests. Count 5xx, 429, timeouts, and network errors; treat definitive statuses as neutral.
Related Resources
Retry Logic with Exponential Backoff
How to implement resilient retry logic with exponential backoff and jitter for transient failures in network and API calls.
RecipeHandle API Errors with RFC 7807 and HTTP Status Codes
Patterns for consistent, predictable API error handling across multiple languages and frameworks.
GuideREST API Design Guide
A thorough guide to designing clean, scalable, and maintainable REST APIs.
PatternCircuit Breaker Pattern in Python, JavaScript, and Java
Prevent cascading failures by stopping requests to failing services. An architectural pattern for resilient distributed systems.
RecipeMake Concurrent HTTP Requests with Python and aiohttp
Fetch multiple APIs concurrently using asyncio and aiohttp. Covers connection pooling, rate limiting, retries, and batch processing.
RecipeNode.js WebSocket Real-Time Communication with Socket.io
Build real-time WebSocket applications in Node.js with Socket.io