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 (TypeError from fetch), 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, PUT and DELETE are safe to repeat; POST usually is not unless the API supports an idempotency key (Stripe-style Idempotency-Key header), 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 AbortSignal to 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 });
7
8async 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 error
14 } catch (err) {
15 if (signal?.aborted) throw err; // the caller cancelled: stop
16 if (attempt >= retries) throw err; // network error, out of attempts
17 }
18 if (response && attempt >= retries) return response; // give the last response back to the caller
19
20 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 + jitter
23 console.log(`attempt ${attempt + 1} failed (${response?.status ?? "network error"}), retrying in ~${Math.round(delay)}ms`);
24 await sleep(delay, signal);
25 }
26}
27
28// A fake server: two 503s, then success
29let calls = 0;
30const fakeFetch = async () => {
31 calls++;
32 if (calls === 1) throw new TypeError("Failed to fetch"); // network blip
33 if (calls === 2) return new Response("busy", { status: 503, headers: { "Retry-After": "0" } });
34 return new Response(JSON.stringify({ ok: true }), { status: 200 });
35};
36
37const 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 calls
39
40// Non-retryable errors return immediately
41const 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.

Open in study app