← Back to JavaScript, page 3

javascript-0048 · Hard senior

How would you implement a retry helper with exponential backoff for an unreliable async operation?

Call the operation in a loop, and when it fails with a retryable error, wait before the next attempt and double the delay each time, up to a maximum number of attempts. Add random jitter so many clients do not retry together, retry only errors that can succeed later, and stop when the caller aborts. Operations that are retried should be safe to repeat.

Full answer

Networks and services fail briefly. A retry with a growing delay gives a service time to recover, whereas immediate retries in a tight loop add load exactly when it is struggling.

Exponential backoff means the delay grows by a factor each attempt: for example 100 ms, 200 ms, 400 ms. A cap such as maxDelay stops it from growing without limit. Jitter adds randomness, for example choosing a random value between 0 and the computed delay (called full jitter). Without it, thousands of clients that failed together retry at the same moment and cause a second wave of failures.

A sound helper has these properties:

  • It takes a maximum attempt count and throws the last error when it runs out.
  • It uses a shouldRetry(error) check. A network timeout or a 503 response is worth retrying. A 400 response or a validation error will fail the same way every time.
  • It accepts an AbortSignal so a user can cancel while it waits.
  • It makes the sleep and random functions injectable, so tests are fast and deterministic.
  • It is only used for idempotent operations, or the caller adds an idempotency key. Repeating a payment request without protection can charge twice.

In production, also respect a Retry-After header when the server sends one, and consider a circuit breaker if failures are long-lasting.

javascript
async function retry(operation, options = {}) {
  const {
    attempts = 4,
    baseDelay = 100,
    factor = 2,
    maxDelay = 2000,
    shouldRetry = () => true,
    random = Math.random,
    sleep = (ms, signal) =>
      new Promise((resolve, reject) => {
        const timer = setTimeout(resolve, ms);
        signal?.addEventListener('abort', () => { clearTimeout(timer); reject(signal.reason); }, { once: true });
      }),
    signal,
    onRetry = () => {},
  } = options;

  for (let attempt = 1; ; attempt++) {
    signal?.throwIfAborted();
    try {
      return await operation(attempt);
    } catch (error) {
      if (attempt >= attempts || !shouldRetry(error)) throw error;
      const ceiling = Math.min(maxDelay, baseDelay * factor ** (attempt - 1));
      const delay = Math.floor(random() * ceiling); // full jitter
      onRetry({ attempt, delay, ceiling, message: error.message });
      await sleep(delay, signal);
    }
  }
}

(async () => {
  const waits = [];
  const fakeSleep = async (ms) => waits.push(ms); // no real waiting in the demo
  let calls = 0;

  const flaky = async () => {
    calls += 1;
    if (calls < 3) throw Object.assign(new Error('503 service unavailable'), { retryable: true });
    return 'ok on call ' + calls;
  };

  const result = await retry(flaky, {
    sleep: fakeSleep,
    random: () => 1, // no randomness, so the full ceiling is used
    shouldRetry: (error) => error.retryable,
    onRetry: ({ attempt, ceiling }) => console.log(`attempt ${attempt} failed, waiting up to ${ceiling} ms`),
  });
  console.log(result, 'waits:', waits);

  try {
    await retry(async () => { throw new Error('400 bad request'); }, { sleep: fakeSleep, shouldRetry: () => false });
  } catch (error) {
    console.log('not retried:', error.message);
  }

  try {
    await retry(async () => { throw new Error('always down'); }, { attempts: 3, sleep: fakeSleep });
  } catch (error) {
    console.log('gave up:', error.message);
  }

  const controller = new AbortController();
  const waiting = retry(async () => { throw new Error('down'); }, { baseDelay: 500, random: () => 1, signal: controller.signal });
  setTimeout(() => controller.abort(new Error('cancelled by user')), 20);
  try {
    await waiting;
  } catch (error) {
    console.log('aborted while waiting:', error.message);
  }
})();

Run with Node.js v24.22.1 as js-48.js; two runs gave identical output. Output: attempt 1 failed, waiting up to 100 ms attempt 2 failed, waiting up to 200 ms ok on call 3 waits: [ 100, 200 ] not retried: 400 bad request gave up: always down aborted while waiting: cancelled by user

Key points

  • Delay grows by a factor each attempt, capped at a maximum.
  • Jitter prevents many clients from retrying in sync.
  • Retry only errors that can succeed later; rethrow the last error at the end.
  • Support cancellation with an AbortSignal.
  • Retried operations must be idempotent or protected by an idempotency key.

Common mistakes

  • Retrying immediately in a tight loop.
  • Retrying errors that will never succeed, such as validation failures.
  • Leaving out jitter, so all clients retry together.
  • Retrying non-idempotent operations without an idempotency key.

Follow-ups

  • How does a circuit breaker complement retries?
  • How would you honour a Retry-After header?
  • How would you add a total time budget across all attempts?

Tips

  • Mention jitter and idempotency without being prompted; they are what an experienced engineer adds.
  • Show injectable sleep and random for testing. It signals production habits.
  • Explain which errors you would retry and which you would not.