FrontendInterviews.dev

Loading problem…

23. Promise Retry with Backoff

Medium•
Acceptance: 92.86%
•
🔓3/3 Pro unlocks today

Implement a utility promiseRetry that retries a promise-returning function when it fails.

Requirements

  • Accept a function fn that returns a promise
  • Retry up to maxRetries times
  • Wait between retries using exponential backoff
  • Resolve immediately when a retry succeeds
  • Reject with the last error when all retries fail

Signature

function promiseRetry(fn, options = {})

Where options supports:

  • maxRetries (default: 3)
  • initialDelay in ms (default: 100)
  • backoffMultiplier (default: 2)

Example Usage

// Example: Retries until success
let attempts = 0;
const fn = () => {
  attempts++;
  return attempts < 3 ? Promise.reject('fail') : Promise.resolve('ok');
};

promiseRetry(fn, { maxRetries: 3, initialDelay: 10 }).then(value => {
  console.log(value); // 'ok' (after 3 attempts)
});

// Example: Rejects after max retries
const failingFn = () => Promise.reject('error');

promiseRetry(failingFn, { maxRetries: 2, initialDelay: 50 }).catch(error => {
  console.log(error); // 'error' (last failure after 2 attempts)
});

Constraints

  • fn returns a Promise
  • maxRetries is >= 1
  • Use exponential backoff delay: initialDelay * backoffMultiplier^(attempt-1)
  • Reject with the last failure reason