AniUI Academy

Retry a request with backoff

hardAsync & Promises+350 XPPractice Available

A request that fails once will often succeed on the next try. Exponential backoff — doubling the wait after each failure — gives the dependency room to recover without hammering it.

Implement retry(task, { attempts, baseDelay }). Call task() and resolve as soon as it does; on rejection, wait baseDelay and try again, doubling the delay between each subsequent attempt until attempts is exhausted.

Arguments

task() => Promise<T>
An async function to invoke. Called afresh on each attempt.
options.attemptsnumber
Maximum number of calls to task before giving up. Defaults to 3.
options.baseDelaynumber
Milliseconds to wait after the first failure. Doubles after each subsequent failure. Defaults to 100.

Returns

Promise<T> — Resolves with the first successful value from task. Rejects with the last error if every attempt fails.

Examples

let calls = 0;
const value = await retry(async () => {
  calls++;
  if (calls < 3) throw new Error("flaky");
  return "ok";
}, { attempts: 5, baseDelay: 10 });
// value === "ok", calls === 3

Succeeds on the third attempt; earlier failures are swallowed.

try {
  await retry(async () => { throw new Error("down"); }, { attempts: 2, baseDelay: 10 });
} catch (err) {
  // err.message === "down" — the last error surfaces
}

What it has to do

  • Resolve as soon as any attempt succeeds.
  • Reject with the last error once attempts are exhausted.
  • Double the delay after each failure, starting at baseDelay.

Notes

  • Don't sleep after the final failed attempt — rejecting immediately feels snappier and matches what callers expect.
  • In production you'd typically add jitter to the delay so retrying clients don't all pile back on at the same instant.
Asked atAmazonStripeUber

Stuck? The javascript course covers everything this challenge needs.

Try it yourself
Loading playground...
3 tests · +350 XP

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.