Jump to the editorJAVASCRIPT
JAVASCRIPT JAVASCRIPT JAVASCRIPT JAVASCRIPT
14.4. Retry with exponential backoff
Medium
Topics
This question is in
14. Timeouts, retries and concurrencyNetworks 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
function retry(fn, options) // returns a Promisefn(attempt): the work.attemptis 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 isfactortimes the one before.maxDelay(defaultInfinity): 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
fnis called at once, with0; each retry passes the next attempt number.- As soon as an attempt succeeds, the promise resolves with its result and no more attempts run.
- After failed attempt number
n,retrywaits exactlymin(baseDelay * factor ** n, maxDelay)ms, measured from the failure, then tries again. - There are at most
1 + retriesattempts; then the promise rejects with the last error, the same objectfnfailed with. 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.- An error
fnthrows (instead of rejecting) is handled the same way. - No timer is left once the promise settles, and separate calls to
retryare independent.
Examples
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 errorretry(task, { retries: 5, maxDelay: 300 });
// waits: 100, 200, 300, 300, 300retry(task, { shouldRetry: (error) => error.status >= 500 });
// a 503 is retried, a 404 fails at once: asking again will not find the pageretry(task, { retries: 0 }); // one attempt, no waitingEnvironment
- Plain JavaScript in a browser page; the tests call the global
retryfromretry.js. - The tests run on a virtual clock that replaces
setTimeout, so wait withsetTimeout. - Random jitter is left out so the waits can be checked exactly; the explanation shows how to add it.
Hints
- Is this easier as a loop with
await, or as a chain of callbacks? Which one makes "the last error" simple? - 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…