Skip to curriculum
Jump to the editor

14.4. Retry with exponential backoff

Medium
Topics
20–30 min

Networks fail for a moment all the time: a server restarts, a phone switches towers, a load balancer drops one connection. Trying again usually works, but trying again at once often fails the same way, and a thousand clients retrying in a tight loop can keep a struggling server down. Exponential backoff waits longer after each failure: 100 ms, then 200, then 400.

Write retry(fn, options) in retry.js. It calls fn; when fn fails, it waits and calls it again, doubling the wait each time, until fn succeeds or the retries run out.

Signature

JAVASCRIPT
function retry(fn, options) // returns a Promise
  • fn(attempt): the work. attempt is 0 for the first call, 1 for the first retry, and so on. It may return a promise or a value, or throw.
  • options (all optional):
    • retries (default 3): how many times to try again after the first attempt.
    • baseDelay (default 100): the wait after the first failure, in ms.
    • factor (default 2): each wait is factor times the one before.
    • maxDelay (default Infinity): no wait is longer than this.
    • shouldRetry(error, attempt) (default: always true): return false to stop at once for this error.
  • Returns a promise of fn's first successful result, or a rejection with the last error.

Requirements

  1. fn is called at once, with 0; each retry passes the next attempt number.
  2. As soon as an attempt succeeds, the promise resolves with its result and no more attempts run.
  3. After failed attempt number n, retry waits exactly min(baseDelay * factor ** n, maxDelay) ms, measured from the failure, then tries again.
  4. There are at most 1 + retries attempts; then the promise rejects with the last error, the same object fn failed with.
  5. shouldRetry(error, attempt) is asked after each failure that still has retries left; when it returns false, the promise rejects at once with that error, without waiting.
  6. An error fn throws (instead of rejecting) is handled the same way.
  7. No timer is left once the promise settles, and separate calls to retry are independent.

Examples

JAVASCRIPT
await retry(() => fetch("/api/data").then((r) => {
  if (!r.ok) throw new Error(`HTTP ${r.status}`);
  return r.json();
}));
// attempts at 0, 100, 300 and 700 ms at most; the data, or the 4th error
JAVASCRIPT
retry(task, { retries: 5, maxDelay: 300 });
// waits: 100, 200, 300, 300, 300
JAVASCRIPT
retry(task, { shouldRetry: (error) => error.status >= 500 });
// a 503 is retried, a 404 fails at once: asking again will not find the page
JAVASCRIPT
retry(task, { retries: 0 }); // one attempt, no waiting

Environment

  • Plain JavaScript in a browser page; the tests call the global retry from retry.js.
  • The tests run on a virtual clock that replaces setTimeout, so wait with setTimeout.
  • Random jitter is left out so the waits can be checked exactly; the explanation shows how to add it.

Hints

  1. Is this easier as a loop with await, or as a chain of callbacks? Which one makes "the last error" simple?
  2. Which failure should never ask shouldRetry, because there is no retry left to allow?

The explanation comes with the course

A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.

  • Every line explained
  • The mistakes each test catches
  • Links to the lessons behind it
Back to the question
Loading the editor…