Exponential Backoff Retry Utility

3.1.3 · active · verified Sun Apr 19

The `exponential-backoff` package provides a robust utility for retrying asynchronous (Promise-returning) functions with an exponential delay between attempts. Currently stable at version 3.1.3, the library maintains an active development status with regular chore and security updates, although it does not adhere to a strict release cadence. Its key differentiators include extensive configurability through the `BackOffOptions` object, allowing control over aspects like initial delay, maximum delay, number of attempts, jitter application (`full` or `none`), and a custom `retry` function for conditional reattempts. The package ships with TypeScript types, enhancing developer experience in TypeScript projects. It is designed to be a flexible solution for handling transient errors in network requests, database operations, or other unreliable processes.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to use `backOff` to retry an unreliable asynchronous function with custom exponential backoff options, including delay, attempts, jitter, and a custom retry condition.

import { backOff } from 'exponential-backoff';

interface WeatherResponse {
  temperature: number;
  unit: string;
}

// Simulate an unreliable API call
let attemptCount = 0;
function getUnreliableWeather(): Promise<WeatherResponse> {
  attemptCount++;
  console.log(`Attempting to fetch weather... (Attempt ${attemptCount})`);
  return new Promise((resolve, reject) => {
    if (Math.random() > 0.7 || attemptCount >= 3) { // Succeeds on ~30% chance or after 3 attempts
      resolve({ temperature: 25, unit: 'C' });
    } else {
      reject(new Error('Failed to fetch weather data.'));
    }
  });
}

async function main() {
  try {
    console.log('Starting weather fetch with exponential backoff...');
    const response = await backOff(
      () => getUnreliableWeather(),
      {
        numOfAttempts: 5, // Try up to 5 times
        startingDelay: 200, // Start with 200ms delay
        timeMultiple: 2, // Double delay each time
        maxDelay: 5000, // Max 5 seconds delay
        jitter: 'full',
        retry: (e, attemptNumber) => {
          console.warn(`Retry attempt ${attemptNumber}: ${e.message}`);
          return true; // Always retry for now
        }
      }
    );
    console.log('Successfully fetched weather:', response);
  } catch (e: any) {
    console.error('Failed to fetch weather after multiple retries:', e.message);
  } finally {
    console.log(`Total attempts: ${attemptCount}`);
  }
}

main();

view raw JSON →