← Whiteboard questions

Retry a function with exponential backoff and jitter

Retry a failing async call with growing, random waits

Coding, Medium

Small real code that works when called late, twice, or with bad input.

Write retry(fn, options) in JavaScript (or the same idea in another language). fn is an async function that may fail. retry calls fn and, if it throws, waits and calls it again, up to retries more times (at most 1 + retries calls). The wait before retry k (k = 1, 2, ...) is a random time between 0 and min(maxMs, baseMs * 2^(k-1)). On success, return the result. If every call fails, throw the last error. Options: retries (default 3), baseMs (100), maxMs (5000), shouldRetry(error) (default: retry all; if false, throw that error at once). For tests, also accept sleep(ms) (default: a real timer) and random() (default: Math.random).

Examples

Input fn fails twice, then returns "ok". baseMs = 100, random always returns its top value (just under 1)
Output returns "ok" after 3 calls; the two waits were just under 100 ms and just under 200 ms
Why Wait 1 is up to min(5000, 100 x 1) and wait 2 is up to min(5000, 100 x 2). A random value just under 1 gives the top of each range.
Input fn always fails with a different message each call, retries = 3
Output throws the 4th error; fn was called 4 times
Why The first call plus 3 retries. The caller sees the last error.
Input fn fails with status 400, shouldRetry = (e) => e.status >= 500
Output throws at once after 1 call, with no wait
Why Edge case: some errors will never succeed on a retry, so waiting only wastes time.

Constraints

Your answer must contain

Target A strong answer covers the wait formula with cap and jitter, the last error, the no-retry rule, and a test with a fake sleep and a fixed random value.

Hints

Try the problem first. Open one hint at a time.

Hint 1 a nudge

Write the loop first: call, and on failure decide whether to try again. How many calls are allowed in total?

Hint 2 the approach

The wait grows with each failure but has a ceiling. Pick a random wait from zero up to the capped delay, so many clients do not retry together.

Hint 3 the key step

Pass the sleep and random functions in as options. A test can then record the waits and fix the random value, with no real waiting.

Walkthrough

Full walkthrough brute force to best

Naive version

Call the function again at once, in a loop, up to the limit. It is simple and works for a rare glitch. If the server is overloaded, every client hits it again with no pause, and the retries keep it down.

Better version

Wait a fixed time, or a doubling time, between calls. The pause gives the server room. But if 1,000 clients fail together, they all wait the same 100, 200, 400 ms and come back at the same moment. A doubling wait with no ceiling also grows without end.

Best method

Loop over the attempt number. Call fn inside try. On success, return the result. On failure, rethrow if this was the last allowed call or if shouldRetry says no. Otherwise compute the cap as the smaller of maxMs and baseMs times 2 to the attempt, and wait a random time between 0 and the cap. This is full jitter: the random wait spreads the clients out, and the cap stops the wait from growing without end. Take sleep and random as options so a test can replace them. Await fn inside the try block, so a synchronous throw is caught too.

Worked example

Run the first example with baseMs 100 and random fixed just under 1. Call 1 fails, so the cap is the smaller of 5000 and 100 x 1, and the wait is just under 100 ms. Call 2 fails, so the cap is 200 and the wait is just under 200 ms. Call 3 returns ok, so retry returns ok after 3 calls.

Reference code

// Calls fn up to 1 + retries times. Waits a random time between 0 and the capped exponential delay
// ("full jitter") before each retry. sleep and random can be replaced, so tests need no real waiting.
async function retry(fn, {
  retries = 3, baseMs = 100, maxMs = 5000,
  shouldRetry = () => true,
  sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
  random = Math.random,
} = {}) {
  if (!Number.isInteger(retries) || retries < 0) throw new RangeError('retries must be a whole number >= 0');
  for (let attempt = 0; ; attempt++) {                 // attempt 0 is the first call
    try {
      return await fn(attempt);
    } catch (err) {
      if (attempt >= retries || !shouldRetry(err)) throw err;   // out of retries, or an error that will never succeed
      const cap = Math.min(maxMs, baseMs * 2 ** attempt);
      await sleep(random() * cap);
    }
  }
}

Time and memory

O(retries) time, apart from the waits. O(1) memory.

Common mistakes

  • Waiting after the last failed call. The wait only delays the error.
  • Retrying errors that can never succeed, such as a bad request.
  • Leaving out the cap. The waits then grow without end.
  • Using real timers in tests. The suite becomes slow and flaky.

Related problems

Retry a function with exponential backoff and jitter