@jobrain/retry-x
v1.0.2
Published
A tiny, framework-agnostic retry library with smart backoff and jitter.
Downloads
33
Maintainers
Readme
retry-x
A tiny, framework-agnostic retry library that wraps any async function with smart backoff, jitter, and full control — done right.
Features
- Exponential backoff: Wait grows after each failure.
- Jitter: Adds randomness to backoff to prevent thundering herd.
- Max attempts: Stop after N retries and throw the last error.
- Max timeout: Stop retrying after a total elapsed time.
retryIfcondition: Only retry when a custom function returnstrue.onRetrycallback: Hook into each retry attempt for logging / metrics.- TypeScript types: Full type safety out of the box.
- Zero dependencies: Extremely lightweight.
Installation
npm install retry-xUsage
Minimal — works out of the box
import { retry } from "retry-x";
const data = await retry(() => fetch("https://api.example.com/data"));Full control
import { retry } from "retry-x";
const data = await retry(
() => fetch("https://api.example.com/data"),
{
attempts: 5,
backoff: "exponential", // or "linear" or "fixed"
jitter: true,
timeout: 10_000, // give up after 10 seconds total
retryIf: (err, attempt) => err.status === 503,
onRetry: (err, attempt) => {
console.log(`Retry #${attempt}:`, err.message);
},
}
);If all attempts fail, the last error is thrown — so your existing try/catch just works.
API
retry(fn, options?)
Wraps an async function and retries it based on the provided options. Returns the result of fn on success, or throws the last error after all attempts are exhausted.
Options
| Option | Type | Default | Description |
|---|---|---|---|
| attempts | number | 3 | Maximum number of attempts |
| backoff | 'exponential' \| 'linear' \| 'fixed' | 'exponential' | Backoff strategy between retries |
| initialDelay | number | 1000 | Initial delay in milliseconds |
| maxDelay | number | 30000 | Maximum delay in milliseconds |
| jitter | boolean | true | Adds randomness to delay to avoid thundering herd |
| timeout | number | — | Total timeout across all attempts in milliseconds |
| retryIf | (error, attempt) => boolean | — | Return false to stop retrying early |
| onRetry | (error, attempt) => void | — | Called before each retry attempt |
License
MIT
