← Back to Node.js, page 3

nodejs-0055 · Hard senior

How do you implement retries with exponential backoff and jitter for a flaky call?

Retry only temporary failures, wait longer after each attempt (base delay times factor to the attempt number, capped at a maximum), add random jitter so many clients do not retry together, limit the number of attempts, and stop when an AbortSignal fires. Make operations idempotent before retrying them.

Full answer

Networks and services fail briefly: a connection reset, a 503, a rate limit. A short pause and another try often works. A bad retry loop, however, can turn a small outage into a big one.

Design rules:

  1. Retry only errors that can heal: network errors, timeouts, 429, 502, 503, 504. Never retry 400, 401, 403 or 404.
  2. Exponential backoff: wait base * factor^attempt, for example 100 ms, 200 ms, 400 ms, 800 ms. This gives the other side time to recover.
  3. Maximum delay and maximum attempts. Without them a loop can last for hours.
  4. Jitter: add randomness. If 1,000 clients fail together and all wait exactly 200 ms, they all return together and fail again (a thundering herd). "Full jitter" picks a random delay between 0 and the backoff value. It spreads the load best.
  5. Respect Retry-After headers when the server sends one.
  6. Idempotency: a retry may repeat a request that already succeeded on the server. POST requests that create things need an idempotency key, or must not be retried.
  7. Cancellation: pass an AbortSignal so shutdown or a user cancel stops the waiting.
  8. A total deadline matters as much as an attempt count. Also consider a circuit breaker, which stops calling a service that keeps failing.

For tests, inject the sleep function and the random function. Then the code runs without real waiting and gives the same delays every time.

javascript
async function retry(task, options = {}) {
  const {
    retries = 3,
    baseMs = 100,
    factor = 2,
    maxMs = 2000,
    jitter = 'full',                 // 'none' or 'full'
    isRetryable = () => true,
    random = Math.random,            // injected for tests
    sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
    signal,
  } = options;

  for (let attempt = 0; ; attempt++) {
    signal?.throwIfAborted();
    try {
      return await task(attempt);
    } catch (err) {
      if (attempt >= retries || !isRetryable(err)) throw err;
      const backoff = Math.min(maxMs, baseMs * factor ** attempt);
      const delay = jitter === 'full' ? Math.floor(random() * backoff) : backoff;
      await sleep(delay);
    }
  }
}

// A seeded random generator so the output is the same on every run.
function seeded(seed) {
  return () => {
    seed = (seed * 1664525 + 1013904223) % 4294967296;
    return seed / 4294967296;
  };
}

async function main() {
  // The task fails twice with a temporary error, then works.
  const makeTask = () => async (attempt) => {
    if (attempt < 2) throw Object.assign(new Error('503 service busy'), { retryable: true });
    return 'ok on attempt ' + (attempt + 1);
  };

  const delays = [];
  const fakeSleep = async (ms) => { delays.push(ms); };

  console.log(await retry(makeTask(), { jitter: 'none', sleep: fakeSleep }));
  console.log('delays without jitter:', delays.join(', '));

  delays.length = 0;
  await retry(makeTask(), { jitter: 'full', sleep: fakeSleep, random: seeded(42) });
  console.log('delays with full jitter (below the caps 100 and 200):', delays.join(', '));

  // A permanent error is not retried.
  const calls = [];
  await retry(async () => { calls.push(1); throw Object.assign(new Error('404 not found'), { retryable: false }); },
    { sleep: fakeSleep, isRetryable: (e) => e.retryable })
    .catch((err) => console.log('gave up at once:', err.message, '| calls:', calls.length));

  // Too many failures: the last error is thrown after retries + 1 calls.
  let count = 0;
  await retry(async () => { count++; throw new Error('still down'); }, { retries: 2, sleep: fakeSleep })
    .catch((err) => console.log('exhausted:', err.message, '| calls:', count));
}

main();

The sleep and random functions are injected, so the example prints the exact delays without waiting. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): ok on attempt 3 delays without jitter: 100, 200 delays with full jitter (below the caps 100 and 200): 25, 17 gave up at once: 404 not found | calls: 1 exhausted: still down | calls: 3

Key points

  • Retry only temporary errors.
  • Exponential backoff with a cap, a maximum attempt count and a total deadline.
  • Jitter prevents synchronized retries.
  • Idempotency decides whether a retry is safe.
  • Inject sleep and random to make tests fast and stable.

Common mistakes

  • Retrying every error, including validation failures.
  • Retrying without jitter and without a limit.
  • Retrying non-idempotent writes and creating duplicates.
  • Hiding the final error after the last attempt.

Follow-ups

  • What is a circuit breaker and how does it differ from a retry?
  • How would you honour a Retry-After header?
  • How do idempotency keys work?

Tips

  • Name the thundering herd problem when you explain jitter.
  • State the retryable list (429, 502, 503, 504, network errors).
  • Say that injected sleep and random keep tests fast and exact.