Retry fetch in TypeScript with exponential backoff and a timeout

Abstract

A tested, dependency-free fetchWithRetry: per-attempt timeout, retries only on 429 and 5xx, exponential backoff with jitter, and the traps to avoid.

Networks fail, servers have bad mornings, and a single fetch call has no opinion about either. This tutorial builds a small fetchWithRetry function in TypeScript with no dependencies. It gives every attempt a timeout, retries only when retrying makes sense, and waits longer between attempts so a struggling server is not hit harder.

The code below was type-checked with TypeScript 7.0.2 in strict mode and run on Node 24 against a local test server.

What the function should do

  1. Abort an attempt that takes too long.
  2. Retry on network errors, timeouts, HTTP 429 and HTTP 5xx.
  3. Not retry on other statuses such as 404, because asking again will not make the page exist.
  4. Wait between attempts, with the wait growing each time.
  5. After the last attempt, throw the last error.

The code

type RetryOptions = {
  retries: number;
  baseDelayMs: number;
  timeoutMs: number;
};

const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));

function isRetryable(status: number): boolean {
  return status === 429 || status >= 500;
}

export async function fetchWithRetry(
  url: string,
  opts: RetryOptions,
  init: RequestInit = {},
): Promise<Response> {
  let lastError: unknown;
  for (let attempt = 0; attempt <= opts.retries; attempt++) {
    try {
      const res = await fetch(url, { ...init, signal: AbortSignal.timeout(opts.timeoutMs) });
      if (!isRetryable(res.status)) return res;
      await res.body?.cancel();
      lastError = new Error(`HTTP ${res.status}`);
    } catch (err) {
      lastError = err;
    }
    if (attempt < opts.retries) {
      const ceiling = opts.baseDelayMs * 2 ** attempt;
      await sleep(Math.random() * ceiling);
    }
  }
  throw lastError;
}

How it works

The timeout. AbortSignal.timeout(ms) creates a signal that aborts after ms milliseconds. Passing it to fetch cancels the attempt, and the call rejects with a TimeoutError. A fresh signal is created for each attempt, so the budget is per attempt, not for the whole loop.

What counts as retryable. The function returns any response that is not a 429 or a 5xx, including 4xx errors, and lets the caller decide what to do. A 404 comes straight back.

Discarding the body. When a response is going to be retried, res.body?.cancel() releases it. Leaving unread bodies around can hold connections open.

Backoff with jitter. The ceiling doubles with each attempt (baseDelayMs * 2 ** attempt), and the actual wait is a random number between zero and the ceiling. The randomness is deliberate. If a thousand clients all fail together and all wait exactly 200 ms, they all return together. Spreading the waits stops them from arriving as a herd.

The last error. If every attempt fails, the loop ends and the last error is thrown, either the TimeoutError, a network error, or the HTTP 5xx error.

What the test showed

A local server was set to answer 503 twice and then 200 on one path, 404 on a second path, and never reply on a third. With retries: 3, baseDelayMs: 20 and timeoutMs: 300:

flaky: 200 ok hits 3
404 not retried: 404 hits 1
hang: TimeoutError after ms >=600: true

The flaky path succeeded on the third request. The 404 was requested once. The hanging path timed out on both attempts (with retries: 1) and took at least 600 ms in total.

Traps

  • Do not retry non-idempotent requests blindly. A retried POST that creates an order may create two. Retry GET and other safe requests by default, and use idempotency keys for writes.
  • Retries multiply load. If a service is overloaded, a client that retries three times sends up to four times the traffic. That is why the jitter and the retry cap exist. During the 2026 Google Cloud London outage, failover itself caused errors in healthy zones, and aggressive client retries make that kind of event worse.
  • Honour Retry-After if the server sends it. This version ignores it. Reading the header and using it as the minimum wait is a good exercise.
  • Set a total deadline. Four attempts with 10-second timeouts can keep a user waiting for 40 seconds. Choose the numbers on purpose.

Conclusion

Thirty lines give you timeouts, selective retries and jittered backoff. They will not make an unreliable service reliable, but they stop your client from being the part that makes it worse.[1] If your system depends on one region, retries are not a substitute for a plan; see the multi-region lessons.


  1. Reviewer 2 asks what happens if the retry logic itself fails. The authors recommend a second retry function, and then stopping. ↩︎