Implement Promise retry logic

A generic retry(fn, options) utility calls an async function, and on failure waits and calls it again, up to a limit, with configurable backoff, jitter, a shouldRetry predicate, an onRetry hook and AbortSignal support; it rethrows the last error (with context) when attempts run out.

Options worth supporting

  • retries: maximum extra attempts.
  • delay strategy: fixed, linear or exponential (base * factor ** attempt), capped by maxDelay.
  • Jitter: "full jitter" picks a random delay between 0 and the backoff, which spreads retries from many clients.
  • shouldRetry(error, attempt): retry only transient errors (network, timeout, 5xx), not validation or auth failures.
  • onRetry(error, attempt, delay): logging and metrics.
  • signal: stop waiting and give up when the caller aborts.
  • Pass the attempt number to fn, so it can adjust (e.g. a longer timeout on later attempts).

Error reporting

When giving up, throw an error that says how many attempts were made, with the original error as cause (or collect all errors into an AggregateError).

Pitfalls

  • Retrying non-idempotent operations (charging a card) can duplicate side effects; use idempotency keys.
  • Retry storms: retries multiply load on a struggling service; combine backoff with circuit breakers on servers.
  • Do not retry inside nested layers that also retry (the multiplication effect).
  • Tests: inject the sleep function or use fake timers so tests run instantly.

Related

"Retry an API call on failure" applies this to HTTP specifics (status codes, Retry-After).

Code example

js
1async function retry(fn, {
2 retries = 3,
3 baseDelay = 100,
4 factor = 2,
5 maxDelay = 5_000,
6 jitter = true,
7 shouldRetry = () => true,
8 onRetry = () => {},
9 signal,
10 sleep = (ms) => new Promise((r) => setTimeout(r, ms)),
11} = {}) {
12 for (let attempt = 0; ; attempt++) {
13 signal?.throwIfAborted();
14 try {
15 return await fn(attempt);
16 } catch (error) {
17 if (attempt >= retries || !shouldRetry(error, attempt)) {
18 throw new Error(`Failed after ${attempt + 1} attempt(s): ${error.message}`, { cause: error });
19 }
20 const backoff = Math.min(maxDelay, baseDelay * factor ** attempt);
21 const delay = jitter ? Math.random() * backoff : backoff; // full jitter
22 onRetry(error, attempt + 1, Math.round(delay));
23 await sleep(delay);
24 }
25 }
26}
27
28// Flaky operation: fails twice with a transient error, then succeeds
29let calls = 0;
30const flaky = async (attempt) => {
31 calls++;
32 if (calls < 3) throw Object.assign(new Error("ECONNRESET"), { transient: true });
33 return `succeeded on attempt ${attempt + 1}`;
34};
35
36const result = await retry(flaky, {
37 baseDelay: 10,
38 shouldRetry: (err) => err.transient === true,
39 onRetry: (err, n, ms) => console.log(`retry #${n} after ${err.message} (waiting ${ms}ms)`),
40});
41console.log(result); // succeeded on attempt 3
42
43// Permanent errors are not retried
44try {
45 await retry(async () => { throw new Error("400 Bad Request"); }, { shouldRetry: (e) => !e.message.startsWith("4") });
46} catch (e) {
47 console.log(e.message, "| cause:", e.cause.message); // Failed after 1 attempt(s): 400 Bad Request | cause: 400 Bad Request
48}
49
50// Abort stops further attempts
51const controller = new AbortController();
52controller.abort(new Error("user navigated away"));
53try {
54 await retry(flaky, { signal: controller.signal });
55} catch (e) {
56 console.log(e.message); // user navigated away
57}

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app