Retry with Backoff & Jitter

Naseebullah Ahmadi  Senior Software Engineer, London

A generic `retry(task, options)` that re-runs a failing async task with exponential backoff and full jitter, an optional `shouldRetry` predicate, and a cap on any single delay.

3 min read
#tooling

Retrying on a fixed interval turns one flaky dependency into a synchronised stampede - every client retries at the same instant. Exponential backoff spaces the attempts out; jitter, a random delay inside the backoff window, is what stops all the clients lining up on the same schedule again.

@itsnas usage.ts
codeusage.ts
// @src/code/retry
const report = await retry(() => fetchJSON('/api/report'), {
  retries: 5,
  shouldRetry: error =>
    error instanceof HttpError && error.status >= 500,
})
main
Nas (@itsnas)