Auto-Retry Fetcher

MediumPromises & Async20 min5 tests

Implement createFetcher(maxRetries, baseDelay) that returns an object with a fetch method that auto-retries on failure with exponential backoff and jitter.

Requirements

  • fetch(asyncFn) — call asyncFn(). If it throws, retry up to maxRetries times.
  • Delay between retries: baseDelay * 2^attempt + random jitter (0 to baseDelay).
  • On success, return the result.
  • If all retries are exhausted, throw the last error.
  • The attempt counter starts at 0 for the first retry.

Example

const fetcher = createFetcher(3, 100);
const data = await fetcher.fetch(async () => {
  // might fail, will be retried up to 3 times
  return 'data';
});
Hints (5)
  1. Loop from 0 to maxRetries (inclusive), trying asyncFn each time.
  2. On failure, calculate delay as baseDelay * 2^attempt + random jitter.
  3. Jitter should be a random value between 0 and baseDelay.
  4. Store the last error and throw it after all retries are exhausted.
  5. On success, return immediately.

Topics

  • Promises & Async

Asked at

Netflix · Cloudflare · Stripe · Uber

Join Us
blur