Skip to content

retry

Retries an async (or sync) function up to a specified number of attempts, with configurable delay and backoff strategy.

import { retry } from "1o1-utils";
import { retry } from "1o1-utils/retry";
async function retry<T>({ fn, attempts, delay, backoff, onRetry }: RetryParams<T>): Promise<T>
NameTypeRequiredDescription
fn() => Promise<T> | TYesThe function to retry
attemptsnumberNoMaximum number of attempts (positive integer, default: 3)
delaynumberNoDelay between retries in ms (default: 1000)
backoff"fixed" | "exponential"NoBackoff strategy (default: "fixed")
onRetry(error, attempt) => voidNoCallback invoked on each retry

Promise<T> — The result of the first successful call.

const data = await retry({
fn: () => fetch("/api/data").then((r) => r.json()),
attempts: 5,
delay: 2000,
backoff: "exponential",
});
// With retry callback
await retry({
fn: fetchData,
onRetry: (error, attempt) => {
console.log(`Attempt ${attempt} failed:`, error);
},
});
  • Throws if fn is not a function.
  • Throws if attempts is not a positive integer.
  • Throws if delay is negative or NaN.
  • Throws if backoff is not "fixed" or "exponential".
  • With exponential backoff, delay is delay * 2^i for attempt i.
  • Throws the last error after all attempts are exhausted.

retry on failure, exponential backoff, resilient call, auto retry

I'm using 1o1-utils (npm: https://www.npmjs.com/package/1o1-utils, GitHub: https://github.com/pedrotroccoli/1o1-utils, LLM context: https://pedrotroccoli.github.io/1o1-utils/llms.txt). Show me how to use retry with exponential backoff for a flaky API