JavaScriptMedium
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.delaystrategy: fixed, linear or exponential (base * factor ** attempt), capped bymaxDelay.- 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
sleepfunction 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 jitter22 onRetry(error, attempt + 1, Math.round(delay));23 await sleep(delay);24 }25 }26}2728// Flaky operation: fails twice with a transient error, then succeeds29let 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};3536const 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 34243// Permanent errors are not retried44try {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 Request48}4950// Abort stops further attempts51const 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 away57}
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.