← JavaScript Coding

Retry Promise with Exponential Backoff

mediumpromisesretrytimers
Asked at
Amazon
DoorDash
PayPal
Razorpay
Stripe
Uber
Amazon, DoorDash, PayPal, Razorpay, Stripe, Uber

Problem statement

Implement retry(fn, options). It calls an async function and retries it when it fails.

API

await retry(fetchUser, {
  retries: 3,
  delay: 100,
  factor: 2,
  shouldRetry: (error) => true,
});

Requirements

  • Call fn immediately for the first attempt.
  • Retry at most retries additional times.
  • Wait delay * factor ** attemptIndex before each retry.
  • Support synchronous throws and promise rejections.
  • If shouldRetry(error) returns false, reject immediately.
  • Reject with the final error if all attempts fail.

This mirrors real frontend work: transient 429/503 failures, flaky networks, and API calls that should retry only when the error is safe to retry.

Requirements & constraints

  • →Do not retry forever.
  • →Support both thrown errors and rejected promises.
  • →Do not wait after the final failed attempt.

How to approach Retry Promise with Exponential Backoff

The strategy an interviewer expects you to reach for.

Retry with exponential backoff is how flaky networks stop becoming flaky UX — wait longer between attempts instead of hammering. Naive move Immediate tight loop retries, or recurse without a budget. Where it breaks 4xx errors should often not retry. Sleep must happen between failures, multiplying delay by factor each time. Exhausted retries must throw the last error. The fix Loop with attempt counter. try/await fn; on success return. On failure, if attempts remain and shouldRetry(error), await sleep(delay), then delay *= factor. Otherwise throw. Remember: Budget + predicate + backoff. Not every error deserves another try. Say this in the interview: I'd retry in a loop with a remaining budget, sleep with exponential delay only when shouldRetry says so, and throw the last error when attempts are exhausted.

Premium

The full solution is part of HelloFrontend Pro

The question above is free to read in full. Upgrade to unlock the interactive workspace and the senior-level walkthrough that go with it.

  • Runnable editor with the hidden test suite
  • Progressive hints that unlock as you get stuck
  • Senior-level reference solution with a line-by-line walkthrough
Unlock the full solution →

Already a member? Log in to open the workspace.

More JS Coding questions

View all JS Coding →
JS CodingEasy

City Fetcher API

JS CodingHard

promise.all( )

JS CodingHard

promise.allSettled( )

JS CodingHard

promise.any( )

JS CodingHard

promise.race( )

JS CodingEasy

promise.reject()

Explore related prep hubs

  • All JavaScript coding
  • JavaScript interview questions
  • JS polyfill interview questions
  • Debounce & throttle questions
  • React interview hub
  • Amazon interview
  • DoorDash interview
  • PayPal interview
  • Razorpay interview
  • Stripe interview
  • Uber interview