How-To Guide

How to Implement Backoff with Jitter

Retry with exponential backoff and jitter: reach a good delay, spread the retries, and stop sensibly so retries do not become the outage.

On this page

  1. Introduction
  2. Grow the delay exponentially, capped
  3. Add jitter to spread the retries
  4. Retry only what is retryable
  5. Cap attempts and surface the failure
  6. Test the backoff, jitter, and cap
  7. Common pitfalls
  8. Conclusion

Introduction

A retry is a second chance for an operation that failed transiently. Done naively, retries make an outage worse: a downstream slows, every client retries immediately, and the extra load keeps it slow. Backoff spaces the retries out, growing the delay as the failure continues; jitter spreads them across clients so they do not arrive together. Together they let a system recover instead of stampeding a struggling dependency.

This tutorial implements retry with exponential backoff and jitter: grow the delay, spread it, retry only the retryable, and cap the attempts with a clear failure. The examples use a fetch retry wrapper, and the math applies to any retry loop.

Grow the delay exponentially, capped

Each failed attempt increases the next delay by a factor, typically two, so the retries space out as the failure persists. The first retry waits tens of milliseconds, the next hundreds, then a second, and so on. Cap the delay so it does not grow to minutes, which would make a recovered dependency sit unused because clients are still waiting. A cap of a few seconds is common for an interactive path.

Start from a base delay that fits the operation. A base too small makes the early retries effectively immediate, adding load without giving the dependency time to recover. A base too large makes even a transient blip cost a long wait. Choose the base from the expected recovery time of the dependency, and the cap from how long the caller can wait.

function backoff(attempt, { base = 50, cap = 5000, factor = 2 } = {}) {
  const exp = Math.min(cap, base * factor ** attempt);
  return exp;
}
// attempt 0 -> 50ms, 1 -> 100, 2 -> 200, ... capped at 5000

Add jitter to spread the retries

If every client uses the same deterministic delay, they all retry at the same time and recreate the spike. Jitter randomizes the delay so the retries spread over a window. Full jitter picks a uniform random value between zero and the exponential maximum, which is simple and effective. Equal jitter uses half the maximum plus a random half, guaranteeing a minimum wait.

The choice matters less than using some jitter. Without it, a fleet of clients that fail together retries together, and the dependency sees a synchronized burst each interval instead of a trickle. With it, the load rises gradually as the dependency recovers, which is exactly the behavior that lets the recovery succeed.

function fullJitter(attempt, { base = 50, cap = 5000, factor = 2 } = {}) {
  const max = Math.min(cap, base * factor ** attempt);
  return Math.random() * max;   // full jitter: uniform in [0, max]
}

Retry only what is retryable

Retrying a failure that will always fail wastes attempts and delays the inevitable. Classify the error before deciding: a network error, a timeout, and a 5xx are usually retryable; a 4xx such as a validation error or an unauthorized response is not, because the request is wrong and will fail again. Retry the transient classes and surface the rest immediately.

Also respect the server’s signal. A 429 or a 503 with a Retry-After header tells you how long to wait; honor it rather than applying your own backoff. A Retry-After shorter than your backoff means the server expects you back sooner; a longer one means it is telling you to wait more. Following the server’s guidance keeps your retries aligned with its capacity.

function isRetryable(err, res) {
  if (err) return true;                          // network/timeout: retryable
  if (res && res.status >= 500) return true;     // server error: retryable
  if (res && res.status === 429) return true;    // rate limited: retry after
  return false;                                  // 4xx: not retryable
}

function retryAfterMs(res) {
  const h = res?.headers?.get?.('retry-after');
  if (!h) return null;
  const s = Number(h);
  return Number.isFinite(s) ? s * 1000 : null;   // prefer the server's delay
}

Cap attempts and surface the failure

Bound the number of attempts, because an unbounded retry loop on a persistent failure never stops and hides the failure from the caller. After the cap, surface an error so the caller can decide what to do: show a message, try a fallback, or fail the request. The cap should account for the worst-case total wait, since attempts times backoff can be long.

Consider a total deadline as well as a count. If the caller has a time budget, retries should fit inside it, so a retry that would exceed the budget is not attempted. This prevents a retry loop from making a slow request much slower. The count and the deadline together bound the worst case, and the caller sees the failure before its own timeout.

async function withRetry(fn, { maxAttempts = 4, deadlineMs = 10000 } = {}) {
  const start = Date.now();
  for (let attempt = 0; ; attempt++) {
    try { return await fn(); }
    catch (err) {
      if (!isRetryable(err) || attempt >= maxAttempts - 1) throw err;
      const delay = fullJitter(attempt);
      if (Date.now() + delay > start + deadlineMs) throw err;   // no time left
      await new Promise((r) => setTimeout(r, delay));
    }
  }
}

Test the backoff, jitter, and cap

Test that the delay grows with the attempt and stays under the cap. Test that the jitter produces different delays across runs, by sampling many and asserting the values are spread rather than constant. Test that a non-retryable error is surfaced on the first attempt, not retried. Test that the attempts are capped and the final error is thrown after the cap, within the deadline.

node -e '
const { fullJitter } = require("./backoff");
const samples = Array.from({ length: 1000 }, () => fullJitter(3));
const min = Math.min(...samples), max = Math.max(...samples);
console.log("spread from", min.toFixed(0), "to", max.toFixed(0));  // not constant, under cap
'

Common pitfalls

A fixed delay so retries stay synchronized, no jitter so a fleet retries together, retrying a 4xx that will always fail, ignoring a Retry-After header, and an unbounded retry loop that hides a persistent failure are the recurring mistakes. Exponential growth with a cap, jitter, a retryable-only policy that respects Retry-After, and a bounded attempt count with a deadline address them.

Conclusion

Backoff and jitter turn retries from a stampede into a recovery. Grow the delay exponentially with a cap, add jitter so clients spread out, retry only transient failures and honor Retry-After, and bound the attempts with a deadline so the caller learns the failure. Self-check by asserting the delay grows but stays capped, the jitter spreads, and a non-retryable error is not retried. Then a struggling dependency is given room to recover instead of being retried to death.

Sources: AWS: Exponential backoff and jitter, MDN: Retrying fetch requests, Google Cloud: Retry with exponential backoff.

FAQ

Why is jitter necessary?
Without jitter, many clients that fail at the same moment all retry after the same delay, producing a synchronized spike that can be as bad as the original failure. Jitter spreads the retries over a window so the load recovers smoothly rather than in a thundering herd.
Which jitter variant?
Full jitter, a uniform random delay between zero and the exponential maximum, is simple and effective. Equal jitter, half the delay plus a random half, keeps a minimum wait. Decorrelated jitter uses the previous delay, which can be smoother but is more complex. Full jitter is a strong default.

Related Examples