Retry with Backoff
MediumPromises & Async20 min4 tests
Implement a retry function that retries a failing async function up to n times with exponential backoff.
Requirements
- Call the function. If it succeeds, return the result.
- If it fails and retries remain, wait
delay * 2^attemptms, then try again. - If all retries are exhausted, throw the last error.
Example
let attempt = 0;
const flaky = () => ++attempt < 3 ? Promise.reject('fail') : Promise.resolve('ok');
await retry(flaky, 3, 10); // 'ok' (succeeds on 3rd try)Hints (5)
- Use a for loop from 0 to retries.
- Wrap each attempt in try/catch.
- On failure, wait using
setTimeoutwrapped in a Promise. - Multiply the delay by
2^attemptfor exponential backoff. - On the last attempt, re-throw the error.
Topics
- Promises & Async
Asked at
Netflix · Uber · Stripe · Cloudflare
