Retry With Exponential Backoff and Jitter (JavaScript)

Retry a flaky async operation a bounded number of times, doubling the delay between attempts, adding jitter, and only retrying errors that are safe to repeat.

JavascriptResilience

Code

javascriptsnippet
24 lines
export async function retry(fn, options = {}) {
  const maxAttempts = options.maxAttempts ?? 5;
  const baseDelayMs = options.baseDelayMs ?? 100;
  for (let attempt = 1; ; attempt++) {
    try {
      return await fn(attempt);
    } catch (error) {
      if (attempt >= maxAttempts || !isRetryable(error)) throw error;
      const jitter = Math.random() * baseDelayMs;
      const delay = baseDelayMs * 2 ** (attempt - 1) + jitter;
      await sleep(delay);
    }
  }
}

function isRetryable(error) {
  if (!error || typeof error !== "object") return false;
  const status = error.status ?? error.statusCode;
  return status === undefined || status >= 500 || status === 429;
}

function sleep(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

Inside the snippet

Retry With Exponential Backoff and Jitter (JavaScript) is built around the functions retry, isRetryable and sleep.

Repetition is confined to for (let attempt = 1; ; attempt++) — the rest of the file is straight-line. Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.

What comes back is a new object, not a reference to anything passed in.

Caveats

  • The guard !error || typeof error !== "object" short-circuits the flow with an early return when its condition holds.

Putting it to use

The primary signature is export async function retry(fn, options = {})

Treat retry as the API: import it, and ignore the supporting code.

Core lines

return new Promise((resolve) => setTimeout(resolve, ms));
return await fn(attempt);
if (attempt >= maxAttempts || !isRetryable(error)) throw error;

Interactive Tools for This Topic

FAQ

Does `retry` modify its input?
The input survives unchanged; what you get back is a newly constructed value.
Anything to download besides the language toolchain?
Nothing beyond the toolchain you already have for this language. The file defines `retry`, `isRetryable`, `sleep` at load time.