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^attempt ms, 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)
  1. Use a for loop from 0 to retries.
  2. Wrap each attempt in try/catch.
  3. On failure, wait using setTimeout wrapped in a Promise.
  4. Multiply the delay by 2^attempt for exponential backoff.
  5. On the last attempt, re-throw the error.

Topics

  • Promises & Async

Asked at

Netflix · Uber · Stripe · Cloudflare

Join Us
blur