FrontendInterviews.dev

Loading problem…

23. Promise Retry with Backoff

Medium•

The promiseRetry function retries an asynchronous operation until it succeeds or the attempt limit is reached.

Implement promiseRetry(fn, options) where fn is a function that returns a Promise. If the promise rejects, retry it up to maxRetries total attempts.

The delay should follow exponential backoff:

delay = initialDelay * (backoffMultiplier ^ attempt)

If all attempts fail, reject with the last error. If any attempt succeeds, resolve with its result.

Options

{
  maxRetries: 3, // total number of attempts (including the first)
  initialDelay: 100,
  backoffMultiplier: 2
}

Example

let attempts = 0;

const fn = () => {
  attempts++;
  return attempts < 2
    ? Promise.reject('fail-' + attempts)
    : Promise.resolve('ok');
};

promiseRetry(fn, { maxRetries: 2, initialDelay: 10 })
  .catch(console.log); // 'fail-2'

Constraints

  • fn returns a Promise
  • maxRetries is >= 1
  • Use exponential backoff delay: initialDelay * backoffMultiplier^(attempt-1)
  • Reject with the last failure reason
Accepted19/22|Acceptance Rate86.4%