Skip to content
Onsite

Retry with Exponential Backoff

MediumP2Coding

Implement retry(fn, retries, baseDelay) for an async function fn that may fail.

It calls fn() and returns a promise that:

  • resolves with the result of the first call that succeeds,
  • after a failed call, waits and calls fn again, up to retries extra times (so fn runs at most retries + 1 times),
  • waits baseDelay * 2^k milliseconds before retry number k + 1 (exponential backoff: baseDelay, then 2 * baseDelay, then 4 * baseDelay, ...),
  • if every attempt fails, rejects with the error from the last attempt.

There is no delay before the first call and none after the last failure. retries may be 0.

Example 1

Input
retry(flaky, 3, 100)
Output
calls flaky, waits 100 ms, 200 ms, 400 ms between failures, resolves on the first success

Constraints

  • 0 <= retries <= 10
  • 0 <= baseDelay <= 1000

Hints

Run checks the 3 visible tests, Submit all 8.