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)— callasyncFn(). If it throws, retry up tomaxRetriestimes.- 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
attemptcounter 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)
- Loop from 0 to maxRetries (inclusive), trying asyncFn each time.
- On failure, calculate delay as baseDelay * 2^attempt + random jitter.
- Jitter should be a random value between 0 and baseDelay.
- Store the last error and throw it after all retries are exhausted.
- On success, return immediately.
Topics
- Promises & Async
Asked at
Netflix · Cloudflare · Stripe · Uber
