againly
v1.2.0
Published
Retry async functions with exponential backoff, jitter, per-attempt timeouts that abort, a total time budget and AbortSignal. Typed errors, ESM + CommonJS, zero dependencies.
Maintainers
Readme
againly
Retry async functions with backoff, jitter, timeouts and AbortSignal support.
Network calls and other async work sometimes fail for a short time. againly calls your function again until it works, and waits a little longer after each failure. This is called backoff. It also adds jitter: a random change to each wait, so many clients do not all retry at the same moment. Use it in place of p-retry or async-retry, especially when you need timeouts that really cancel a slow attempt.
Features
- Exponential backoff with jitter: waits 200ms, 400ms, 800ms... with
'full','equal'or no jitter. - Time limit per attempt (
timeout) that aborts the attempt'sAbortSignal. - Time limit for everything (
maxTime) that also stops a running attempt. - Cancel everything with your own
AbortSignal. - Choose what to retry with
shouldRetry(error), stop early withbail(), or set the wait yourself (for example from aRetry-Afterheader). - Typed errors:
RetryErrorkeeps the last error ascause, plus the number ofattempts. wrap(fn)turns any function into a function that retries.- Works with fake timers, because it only uses
setTimeoutandDate.now. - Zero dependencies, about 2 KB gzipped, ESM and CommonJS, TypeScript types included.
Installation
npm install againlypnpm add againly
yarn add againly
bun add againlyQuick start
import againly from 'againly'
// A function that fails two times, then works
let calls = 0
async function getData() {
calls++
if (calls < 3) throw new Error('Server busy')
return { ok: true }
}
const data = await againly(getData, { retries: 5 })
data // => { ok: true }
calls // => 3
// When every attempt fails, againly rejects with a RetryError
await againly(() => { throw new Error('Down') }, { retries: 2 })
// => throws RetryError: againly: gave up after 3 attempts (out of retries): DownWith CommonJS, use const againly = require('againly') and const { wrap, RetryError } = require('againly').
Table of contents
Usage
Retry a fetch request
import againly from 'againly'
const user = await againly(
async ({ signal }) => {
const res = await fetch('https://api.example.com/user', { signal })
if (!res.ok) throw new Error(`HTTP ${res.status}`)
return res.json()
},
{ retries: 5, timeout: 2000 },
)fetchdoes not reject on HTTP errors such as 500. Throw an error yourself, soagainlyknows the attempt failed.- Pass
signaltofetch. When an attempt takes longer thantimeout(2 seconds here), the signal is aborted and the request is really cancelled.
Your function gets a context object on every attempt: { attempt, retriesLeft, elapsed, signal, bail }. See the API for details.
Choose how long to wait between attempts
After each failure, againly waits before it tries again. Without jitter, the wait is minDelay * factor ** (attempt - 1), capped at maxDelay. With the defaults, that is:
| After attempt | 1 | 2 | 3 | 4 | 5 | ... | |---|---|---|---|---|---|---| | Wait (no jitter) | 200ms | 400ms | 800ms | 1600ms | 3200ms | up to 30s |
Jitter then changes each wait at random:
| jitter | Wait after attempt 1 (default options) |
|---|---|
| 'full' (default) or true | Random between 0 and 200ms |
| 'equal' | Random between 100ms and 200ms |
| 'none' or false | Exactly 200ms |
await againly(task, {
retries: 4, // up to 5 calls in total
minDelay: 500, // first wait: 500ms
factor: 3, // then 1500ms, 4500ms, ...
maxDelay: 10_000, // never wait more than 10 seconds
jitter: 'equal', // each wait is random, between half and all of it
})You can see the real waits with onRetry:
const waits = []
await againly(alwaysFails, {
jitter: 'none',
onRetry: (error, { delay }) => waits.push(delay),
}).catch(() => {})
waits // => [200, 400, 800]Set time limits
// Each attempt gets 2 seconds. Everything together gets at most 10 seconds.
await againly(({ signal }) => fetch(url, { signal }), { timeout: 2000, maxTime: 10_000 })timeout: when an attempt takes too long, itssignalis aborted and the attempt fails with aTimeoutError. This error is retried like any other error.maxTime: when the total time runs out, the running attempt is aborted.againlyalso does not start a retry if its wait would end after the limit. It then rejects with aRetryErrorwithreason: 'maxTime'.
import againly, { RetryError, TimeoutError } from 'againly'
try {
// This attempt never finishes
await againly(() => new Promise(() => {}), { retries: 1, timeout: 100 })
} catch (error) {
error instanceof RetryError // => true
error.cause instanceof TimeoutError // => true
error.attempts // => 2
}If your function ignores its signal, it keeps running in the background after a timeout. againly stops waiting for it and ignores its result.
Retry only some errors
Return false from shouldRetry to give up on an error. Use onRetry to log each retry.
await againly(callApi, {
retries: 5,
shouldRetry: (error) => !(error instanceof ValidationError),
onRetry: (error, { attempt, delay }) => {
console.warn(`attempt ${attempt} failed, retrying in ${delay}ms`, error)
},
})shouldRetrycan be async. It is not called after the last attempt.- When it returns
false,againlyrejects with aRetryErrorwithreason: 'shouldRetry'. The error is incause. onRetryruns before each wait, andagainlywaits for it if it returns a promise.- If
shouldRetry,onRetryordelaythrows,againlyrejects with that error.
Stop retrying early
Call bail() inside your function, or throw a StopError from anywhere in its call stack. No more attempts are made, and shouldRetry and onRetry are not called.
await againly(async ({ bail }) => {
const res = await fetch(url)
if (res.status === 404) bail(new NotFoundError(url)) // rejects with this error, no retry
if (!res.ok) throw new Error(`HTTP ${res.status}`) // retried
return res.json()
})bail(error)andthrow new StopError(error)reject witherroritself, not wrapped.bail('message')andbail()reject with aStopErrorthat has this message.bailthrows, so code after it does not run.
import againly, { StopError } from 'againly'
await againly(() => { throw new StopError('Not allowed') })
// => throws StopError: Not allowedUse the wait from a Retry-After header
delay(error, ctx) lets you choose the wait yourself. Return a number of milliseconds, or undefined to use the normal backoff.
await againly(
async () => {
const res = await fetch(url)
if (res.status === 429) {
const error = new Error('Too many requests')
error.retryAfter = Number(res.headers.get('retry-after')) // in seconds
throw error
}
if (!res.ok) throw new Error(`HTTP ${res.status}`)
return res.json()
},
{
delay: (error) => (error.retryAfter ? error.retryAfter * 1000 : undefined),
},
)The value you return is used as it is: no jitter, and no maxDelay cap. maxTime still applies.
Cancel with an AbortSignal
Pass your own signal to cancel everything: the running attempt and all retries. againly then rejects right away with signal.reason.
const controller = new AbortController()
const promise = againly(({ signal }) => fetch(url, { signal }), { signal: controller.signal })
controller.abort()
await promise
// => throws an AbortError (a DOMException)When your signal aborts, the signal of the running attempt is aborted too.
Handle the final error
When againly gives up, it rejects with a RetryError, not with your original error. This is different from p-retry and async-retry. Your original error is in error.cause.
import againly, { RetryError } from 'againly'
try {
await againly(callApi)
} catch (error) {
if (error instanceof RetryError) {
console.log(`gave up after ${error.attempts} attempts`, error.cause)
}
}| Property | Description |
|---|---|
| cause | The error from the last attempt, exactly as it was thrown (it may not be an Error). |
| attempts | How many attempts were made. |
| reason | Why it stopped: 'retries', 'shouldRetry' or 'maxTime'. |
See What it rejects with for every case.
Make a function that retries
wrap(fn, options?) returns a new function with the same parameters. Each call retries on its own.
import { wrap } from 'againly'
const getUser = wrap((id) => api.get(`/users/${id}`), { retries: 2 })
await getUser('42')The new function passes this through. It does not give fn the attempt context, so use againly() directly when you need signal or bail.
Test code that retries
againly uses setTimeout and Date.now(). So vi.useFakeTimers() in Vitest or jest.useFakeTimers() in Jest control every wait, timeout and maxTime. You can also pass minDelay: 0 in tests.
vi.useFakeTimers()
const promise = againly(flakyTask)
await vi.runAllTimersAsync()
await promiseUse TypeScript types
The result type comes from fn. wrap keeps the parameter list:
import againly, { wrap } from 'againly'
const user = await againly(async () => ({ id: 1 })) // { id: number }
const get = wrap(async (id: string) => load(id)) // (id: string) => Promise<...>API
againly(fn, options?)
function againly<T>(
fn: (ctx: AttemptContext) => T | PromiseLike<T>,
options?: AgainlyOptions,
): Promise<T>Calls fn until it succeeds and returns a promise for its result. fn can be sync or async. This is also the default export. The default export also has every named export as a property, for example againly.wrap.
fn gets a context object (AttemptContext):
| Property | Type | Description |
|---|---|---|
| attempt | number | Attempt number, starting at 1. |
| retriesLeft | number | Retries still available after this attempt. Infinity with retries: Infinity. |
| elapsed | number | Milliseconds since againly() was called. |
| signal | AbortSignal | Signal for this attempt. Aborted on timeout, when maxTime runs out, or when your signal aborts. |
| bail(reason?) | (reason?: unknown) => never | Stop retrying now. See Stop retrying early. |
Options
| Option | Type | Default | Description |
|---|---|---|---|
| retries | number | 3 | Retries after the first attempt, so 3 means up to 4 calls. 0 means try once. An integer >= 0, or Infinity. |
| minDelay | number | 200 | Wait before the first retry, in ms (before jitter). |
| factor | number | 2 | Each wait is factor times the one before. Must be >= 1. |
| maxDelay | number | 30000 | Largest backoff wait, in ms (before jitter). Infinity is allowed. |
| jitter | 'full' \| 'equal' \| 'none' \| boolean | 'full' | 'full': random between 0 and the wait. 'equal': random between half and all of it. 'none': exact. true means 'full', false means 'none'. |
| delay | (error, ctx) => number \| undefined | none | Choose the wait yourself. Return ms, or undefined to use the normal backoff. Used as it is (no jitter, no maxDelay). |
| timeout | number | none | Time limit for each attempt, in ms. The attempt's signal is aborted and the attempt fails with a TimeoutError, which is retried. |
| maxTime | number | none | Time limit for everything, in ms. A running attempt is aborted when it runs out, and a retry is not started if its wait would end after the limit. |
| signal | AbortSignal | none | Cancels everything. againly then rejects with signal.reason. |
| shouldRetry | (error, ctx) => boolean \| Promise<boolean> | none | Return false to give up on this error. Not called after the last attempt. |
| onRetry | (error, ctx) => void \| Promise<void> | none | Called before each wait. A returned promise is awaited. |
shouldRetry and delay get ctx with { attempt, retriesLeft, elapsed } (type FailureContext). onRetry gets the same plus delay, the wait in ms (type RetryContext).
Every wait goes through setTimeout, even a wait of 0ms. So a function that keeps failing never blocks the event loop. Waits longer than about 24.8 days are cut down to the largest value setTimeout supports.
What it rejects with
| Situation | Rejects with |
|---|---|
| All retries used | RetryError with reason: 'retries' |
| shouldRetry returned false | RetryError with reason: 'shouldRetry' |
| maxTime ran out | RetryError with reason: 'maxTime' |
| bail(error) or throw new StopError(error) | error itself |
| bail('message') or bail() | StopError |
| Your signal aborted | signal.reason (an AbortError DOMException by default) |
| A hook threw | That error |
| Invalid options | TypeError or RangeError |
wrap(fn, options?)
function wrap<A extends unknown[], R, This = unknown>(
fn: (this: This, ...args: A) => R,
options?: AgainlyOptions,
): (this: This, ...args: A) => Promise<Awaited<R>>Returns a function with the same parameters that retries fn on every call, with the same options as againly(). this is passed through. fn does not get the attempt context.
RetryError
class RetryError extends Error {
readonly cause: unknown
readonly attempts: number
readonly reason: 'retries' | 'shouldRetry' | 'maxTime'
}The error againly rejects with when it gives up. cause is the last error, exactly as thrown, even if it is not an Error. See Handle the final error.
TimeoutError
class TimeoutError extends Error {
readonly timeout: number
}An attempt took longer than timeout (or longer than the time left in maxTime). timeout is the limit in ms. It is retried like any other error, so you usually find it in RetryError.cause.
StopError
class StopError extends Error {
constructor(reason?: unknown)
}Throw it from your function to stop retrying, the same as calling bail(). new StopError(error) makes againly reject with error. new StopError('message') makes it reject with the StopError itself. It is recognized even when it comes from another copy of againly in your node_modules.
Types
These types are exported: AgainlyOptions, AttemptContext, FailureContext, RetryContext, Jitter, RetryErrorReason.
Comparison
| | p-retry | async-retry | againly |
|---|---|---|---|
| Exponential backoff, retries, factor, max delay | Yes | Yes | Yes |
| Jitter | Random x1-2 multiplier | Random x1-2 multiplier | Full, equal or none (full by default) |
| Per-attempt timeout | No (combine with p-timeout) | No | Yes, aborts the attempt's AbortSignal |
| Total time limit | Yes, maxRetryTime, checked between attempts | Yes, maxRetryTime (through retry) | Yes, maxTime, also stops a running attempt |
| Cancel with AbortSignal | Yes (the running attempt is not interrupted) | No | Yes, rejects right away and aborts the attempt's signal |
| Stop early | Yes, AbortError | Yes, bail() | Yes, bail() or StopError |
| shouldRetry / hook before each retry | Yes / Yes | No / Yes, onRetry | Yes / Yes |
| Custom delay per error (for example Retry-After) | No | No | Yes, delay(error) |
| Failures that do not use up a retry | Yes, shouldConsumeRetry | No | No |
| unref timers | Yes | Yes | No |
| Skips non-network TypeErrors automatically | Yes | No | No (use shouldRetry) |
| Wrap a function | Yes, makeRetriable | No | Yes, wrap |
| Final error | The last error, as thrown | The last error, as thrown | RetryError with cause, attempts, reason |
| CommonJS require() | No (ESM only) | Yes | Yes |
| Runtime dependencies | 1 (is-network-error) | 1 (retry) | 0 |
| Default retries / first delay | 10 / 1000ms | 10 / 1000ms | 3 / 200ms |
p-retry is well maintained. Choose againly if you need the per-attempt timeout, the jitter options or CommonJS from the table above.
Notes and limitations
- The final error is wrapped. Unlike
p-retry,againlyrejects with aRetryErrorwhen it gives up. Readerror.causefor your original error. - A slow attempt is only really cancelled if it uses
signal. Otherwise it keeps running in the background after a timeout, and its result is ignored. - Timers are not
unref'd. A pending wait keeps Node.js running until it ends. - Every failure uses up a retry. There is no option like
p-retry'sshouldConsumeRetry. TypeErrors are retried like other errors. UseshouldRetryto skip them.- Waits from
delay()skip jitter andmaxDelay. The value is used as it is. - Very long waits are cut down to about 24.8 days, the largest value
setTimeoutsupports.
Requirements
- Node.js 20 or newer. Also works in Bun, Deno and browsers.
- ESM and CommonJS.
- TypeScript types included.
- Zero dependencies.
License
MIT
