JavaScriptMedium
Retry an API call on failure
Retry an HTTP request only for failures that can succeed on a second try (network errors, timeouts, 408, 429 and 5xx), using exponential backoff with jitter, respecting the server's Retry-After header, capping attempts, and never blindly retrying non-idempotent requests like payments.
What to retry
- Retry: network failures (
TypeErrorfromfetch), timeouts,408,429 Too Many Requests,500,502,503,504. - Do not retry:
400,401,403,404,422(the request itself is wrong), and user aborts. - Idempotency:
GET,PUTandDELETEare safe to repeat;POSTusually is not unless the API supports an idempotency key (Stripe-styleIdempotency-Keyheader), so the server can deduplicate.
Backoff strategy
- Exponential: 300 ms, 600 ms, 1.2 s, 2.4 s... capped at a maximum.
- Jitter: randomise each delay so thousands of clients do not retry in sync (the "thundering herd").
Retry-After: if the server sends it (seconds or an HTTP date), wait at least that long.
Other essentials
- A per-attempt timeout (
AbortSignal.timeout) so one hanging request does not stall everything. - Respect a caller's
AbortSignalto cancel the whole retry loop. - Log attempts for observability.
- Cap the total time as well as the number of attempts.
Related
The generic "retry any promise" utility is covered in "Implement Promise retry logic"; this answer focuses on HTTP semantics.
Code example
js
1const RETRYABLE_STATUS = new Set([408, 429, 500, 502, 503, 504]);2const sleep = (ms, signal) =>3 new Promise((resolve, reject) => {4 const t = setTimeout(resolve, ms);5 signal?.addEventListener("abort", () => (clearTimeout(t), reject(signal.reason)), { once: true });6 });78async function fetchWithRetry(url, { retries = 3, baseDelay = 50, maxDelay = 2000, timeout = 5000, signal, fetchImpl = fetch, ...init } = {}) {9 for (let attempt = 0; ; attempt++) {10 let response;11 try {12 response = await fetchImpl(url, { ...init, signal: AbortSignal.any([AbortSignal.timeout(timeout), ...(signal ? [signal] : [])]) });13 if (response.ok || !RETRYABLE_STATUS.has(response.status)) return response; // success or a non-retryable error14 } catch (err) {15 if (signal?.aborted) throw err; // the caller cancelled: stop16 if (attempt >= retries) throw err; // network error, out of attempts17 }18 if (response && attempt >= retries) return response; // give the last response back to the caller1920 const retryAfter = Number(response?.headers.get("retry-after")) * 1000 || 0;21 const backoff = Math.min(maxDelay, baseDelay * 2 ** attempt);22 const delay = Math.max(retryAfter, backoff / 2 + Math.random() * (backoff / 2)); // exponential + jitter23 console.log(`attempt ${attempt + 1} failed (${response?.status ?? "network error"}), retrying in ~${Math.round(delay)}ms`);24 await sleep(delay, signal);25 }26}2728// A fake server: two 503s, then success29let calls = 0;30const fakeFetch = async () => {31 calls++;32 if (calls === 1) throw new TypeError("Failed to fetch"); // network blip33 if (calls === 2) return new Response("busy", { status: 503, headers: { "Retry-After": "0" } });34 return new Response(JSON.stringify({ ok: true }), { status: 200 });35};3637const res = await fetchWithRetry("https://api.example.com/data", { fetchImpl: fakeFetch });38console.log(res.status, await res.json(), "after", calls, "calls"); // 200 { ok: true } after 3 calls3940// Non-retryable errors return immediately41const notFound = await fetchWithRetry("/missing", { fetchImpl: async () => new Response("", { status: 404 }) });42console.log(notFound.status); // 404 - no retries
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.