Skip to content
jshacks.dev
Async

How to Retry a Failed Promise With Exponential Backoff

Retry a failed promise with exponential backoff and jitter in modern JavaScript, with a reusable helper, printed output and the limits that keep it safe.

7 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, npm and TypeScript logos.

A network call that fails once will often succeed a moment later. A dropped connection, a 503 from an overloaded server or a rate limit that resets in a second are all cases where the right response is to wait and try again. The wrong response is to retry in a tight loop, because a hundred clients doing that turn a short outage into a long one. This post builds a small helper that retries a failed promise with exponential backoff and jitter, shows what it prints, and lists the places where retrying does harm. The code targets Node.js 24 and current browsers, and relies only on async functions, setTimeout and AbortSignal. If you want the underlying model first, the guide to how promises settle covers it.

The smallest useful retry

Start with a loop. The function takes a task, which is a function that returns a promise, and a number of attempts. It calls the task, returns the result on success, and waits before the next try on failure.

retry.jsJavaScript
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

export async function retry(task, { attempts = 4, baseMs = 100 } = {}) {
  let lastError;
  for (let attempt = 1; attempt <= attempts; attempt++) {
    try {
      return await task(attempt);
    } catch (error) {
      lastError = error;
      if (attempt === attempts) break;
      const delay = baseMs * 2 ** (attempt - 1);
      console.log(`attempt ${attempt} failed, waiting ${delay} ms`);
      await sleep(delay);
    }
  }
  throw lastError;
}

The task receives the attempt number, which is handy for logging. Passing a function instead of a promise matters: a promise is already running when you hold it, so retrying means creating a new one. The delay doubles each time, which is what "exponential" means here: 100, 200, 400 milliseconds.

Watching it work

A task that fails twice and then succeeds shows the shape of the output.

demo.jsJavaScript
import { retry } from "./retry.js";

let calls = 0;

async function flaky() {
  calls += 1;
  if (calls < 3) throw new Error(`failure ${calls}`);
  return "ok";
}

const result = await retry(flaky, { attempts: 4, baseMs: 100 });
console.log(`result: ${result} after ${calls} calls`);
Text
attempt 1 failed, waiting 100 ms
attempt 2 failed, waiting 200 ms
result: ok after 3 calls

The helper waited 300 milliseconds in total before the third call returned. If every attempt failed, the loop would exit after the fourth call and rethrow the last error, so the caller sees the real failure and not a generic wrapper.

Why jitter matters

Pure doubling has a flaw. Suppose a server drops 500 clients at the same instant. All 500 wait 100 ms and retry together, all 500 wait 200 ms and retry together, and the server sees the same spike at every step. Adding randomness spreads them out. The common variant is "full jitter": pick a random delay between zero and the exponential ceiling.

retry-jitter.jsJavaScript
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

export function backoffDelay(attempt, { baseMs = 100, capMs = 5000 } = {}) {
  const ceiling = Math.min(capMs, baseMs * 2 ** (attempt - 1));
  return Math.random() * ceiling;
}

export async function retry(task, options = {}) {
  const { attempts = 4 } = options;
  let lastError;
  for (let attempt = 1; attempt <= attempts; attempt++) {
    try {
      return await task(attempt);
    } catch (error) {
      lastError = error;
      if (attempt === attempts) break;
      await sleep(backoffDelay(attempt, options));
    }
  }
  throw lastError;
}

Two details are worth noticing. The capMs value stops the ceiling from growing past a limit you can live with, so attempt 10 does not wait for minutes. And Math.random() * ceiling means the wait can be close to zero, which sounds wrong but is the point: across many clients, the average load flattens. The exact delays differ on every run, so any output you log will differ too.

Retry only what can succeed

Retrying a request that failed because the input is invalid wastes time, since the answer will not change. Retry transient failures and fail fast on the rest. For fetch, that usually means network errors and a short list of status codes.

retry-fetch.jsJavaScript
import { retry } from "./retry-jitter.js";

class HttpError extends Error {
  constructor(status) {
    super(`HTTP ${status}`);
    this.status = status;
  }
}

const RETRYABLE = new Set([408, 429, 500, 502, 503, 504]);

export function fetchWithRetry(url, init) {
  return retry(async () => {
    const response = await fetch(url, init);
    if (response.ok) return response;
    if (RETRYABLE.has(response.status)) throw new HttpError(response.status);
    // A 404 or 422 will not improve on retry, so escape the loop.
    const fatal = new HttpError(response.status);
    fatal.fatal = true;
    throw fatal;
  });
}

As written, the fatal flag does nothing yet, because retry does not read it. The next step is to let the helper ask a predicate whether an error deserves another try.

retry-when.jsJavaScript
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

export async function retry(task, { attempts = 4, baseMs = 100, shouldRetry = () => true } = {}) {
  let lastError;
  for (let attempt = 1; attempt <= attempts; attempt++) {
    try {
      return await task(attempt);
    } catch (error) {
      lastError = error;
      if (attempt === attempts || !shouldRetry(error)) break;
      await sleep(Math.random() * baseMs * 2 ** (attempt - 1));
    }
  }
  throw lastError;
}

let calls = 0;
const task = async () => {
  calls += 1;
  const error = new Error("bad input");
  error.fatal = true;
  throw error;
};

try {
  await retry(task, { shouldRetry: (e) => !e.fatal });
} catch (error) {
  console.log(`${error.message} after ${calls} call(s)`);
}
Text
bad input after 1 call(s)

The task ran once and the error came straight back. With the default predicate it would have run four times. A separate post covers retrying only on specific errors in more depth.

Stop retrying when the caller gives up

A retry loop that sleeps for seconds is hard to interrupt unless you build that in. Accept an AbortSignal and make the sleep listen to it, so a navigation or a timeout ends the whole sequence immediately.

retry-abort.jsJavaScript
function sleep(ms, signal) {
  return new Promise((resolve, reject) => {
    if (signal?.aborted) return reject(signal.reason);
    const timer = setTimeout(() => {
      signal?.removeEventListener("abort", onAbort);
      resolve();
    }, ms);
    function onAbort() {
      clearTimeout(timer);
      reject(signal.reason);
    }
    signal?.addEventListener("abort", onAbort, { once: true });
  });
}

export async function retry(task, { attempts = 4, baseMs = 100, signal } = {}) {
  let lastError;
  for (let attempt = 1; attempt <= attempts; attempt++) {
    signal?.throwIfAborted();
    try {
      return await task(attempt);
    } catch (error) {
      lastError = error;
      if (attempt === attempts) break;
      await sleep(Math.random() * baseMs * 2 ** (attempt - 1), signal);
    }
  }
  throw lastError;
}

const controller = new AbortController();
setTimeout(() => controller.abort(new Error("user left the page")), 50);

try {
  await retry(() => Promise.reject(new Error("down")), {
    baseMs: 1000,
    signal: controller.signal,
  });
} catch (error) {
  console.log(error.message);
}
Text
user left the page

The abort reason, not the last task error, is what surfaces, because the caller asked to stop. signal.throwIfAborted() is available in Node.js 17.3 and later and in current browsers. The AbortSignal reference on MDN lists the methods used here.

Reading the failure after the last attempt

When every attempt fails, the helper rethrows only the last error. That is usually what you want for control flow, but it hides the earlier ones, and the first failure is sometimes the informative one: a timeout on attempt one followed by a refused connection on attempt four points at a server that went down, not at a bad request. Collect the errors and attach them to the final one so the log tells the whole story. In Node.js 24 and current browsers the built-in AggregateError takes an array of errors and a message, and the cause option on Error links one error to another.

retry-errors.jsJavaScript
const errors = [];
for (let attempt = 1; attempt <= 3; attempt++) {
  try {
    throw new Error(`attempt ${attempt} failed`);
  } catch (error) {
    errors.push(error);
  }
}
const failure = new AggregateError(errors, "all 3 attempts failed");
console.log(failure.message);
console.log(failure.errors.map((e) => e.message));
Text
all 3 attempts failed
[ 'attempt 1 failed', 'attempt 2 failed', 'attempt 3 failed' ]

Callers that only care about success can ignore the extra detail, and callers that log failures get a complete record without a second code path. Keep the list short, since one entry per attempt is bounded by the attempt count you already capped. If you wrap the final error instead, pass the last failure as cause so a debugger can walk back to the original stack trace without any extra bookkeeping in your retry loop.

Where retrying hurts

Retrying is safe only when repeating the call is safe. A GET is normally idempotent. A POST that charges a card is not, and if the first request succeeded but the response was lost, a retry charges twice. For writes, send an idempotency key that the server uses to recognize a repeat, or do not retry at all. A second cost is amplification. If service A retries four times against service B, and B retries four times against C, one user action can become sixteen calls to C. Put retries at one layer, usually the outermost caller, and keep attempt counts small. Finally, a retry budget protects the system when a dependency is truly down: after a number of failures across all requests, stop retrying for a while, which is what a circuit breaker does.

Choosing the numbers

Defaults that work for most HTTP clients are three or four attempts, a base of 100 to 500 milliseconds and a cap of a few seconds. User-facing requests deserve shorter totals than background jobs, because a person will not wait twenty seconds for a spinner. Whatever you pick, log each retry with the attempt number and the error, so an incident review can see how often retries rescued a call and how often they only delayed the failure.

Taggedpromises
Share

Keep reading

Flat illustration of an editor window full of code, with the Google Chrome, JavaScript and npm logos.
Browser

script Tags: async, defer and type=module

Compare classic, async, defer and module script tags: when each downloads, when each runs, how order is kept and which one to pick for each kind of script.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.