mediumcodingjavascript~12 min
Retry with Exponential Backoff
Objective: Build resilient async calls with bounded, injectable delays.
Write `retry(fn, { retries, baseMs, sleep })`. Call `fn()` until it resolves; on failure wait `baseMs * 2 ** attempt` (via the injected `sleep`) and try again, up to `retries` retries.
- Total attempts are `retries + 1`.
- Delay before retry n (0-based) is `baseMs * 2 ** n`, awaited through `sleep(ms)`.
- Resolve with the first successful value.
- After the last failure reject with that final error and do not sleep after it.
JavaScript
⌘/Ctrl + Enter to run tests · Esc then Tab leaves the editor
Output
> Nothing has run yet.
Interview follow-up questions
- Why add jitter to the delay?
- Which errors should never be retried?
- How do you combine retries with an overall timeout or AbortSignal?