backoff-retry-lite
v0.1.0
Published
Async retry utility with exponential backoff and jitter for flaky calls (network requests, LLM APIs, etc).
Maintainers
Readme
backoff-retry-lite
Async retry with exponential backoff and jitter, for flaky network calls, LLM API requests, or anything that fails transiently. Zero dependencies.
Install
npm install backoff-retry-liteQuick start
import { retry } from 'backoff-retry-lite';
const data = await retry(() => fetch(url).then(r => r.json()), {
retries: 4,
baseDelayMs: 250,
onRetry: (err, attempt, delayMs) => console.warn(`attempt ${attempt} failed, retrying in ${delayMs}ms`),
});Stop retrying on errors that will never succeed:
await retry(callApi, {
shouldRetry: (err) => (err as any).status >= 500, // only retry server errors
});Why jitter is on by default
Naive exponential backoff without jitter causes many clients that failed at the same moment (e.g. after a shared dependency blips) to retry in lockstep, creating a thundering-herd spike against the service that's already struggling. Jitter (randomizing the delay within the exponential bound) is the standard fix and costs nothing, so it's the default here rather than an opt-in.
API
retry(fn, options?)— callsfn(attempt), retrying on throw up tooptions.retriestimescomputeDelay(attempt, baseDelayMs, maxDelayMs, jitter)— the delay calculation, exported for testing/inspection
Options: retries (default 3), baseDelayMs (200), maxDelayMs (5000), jitter (true), shouldRetry(err, attempt), onRetry(err, attempt, delayMs), sleep (injectable for tests).
License
MIT
