async-retry vs backoff vs promise-retry vs retry vs retry-axios vs retry-request
Strategic Retry Logic and Resilience Patterns in JavaScript
async-retrybackoffpromise-retryretryretry-axiosretry-requestSimilar Packages:

Strategic Retry Logic and Resilience Patterns in JavaScript

This comparison evaluates six prominent npm packages designed to handle transient failures in JavaScript applications through retry mechanisms. While they share the common goal of improving system resilience against network flakiness or temporary service unavailability, they differ significantly in their execution models (callbacks vs. promises), integration scope (generic utilities vs. HTTP client wrappers), and maintenance status. Some packages like retry and backoff represent older, callback-era patterns, while others like async-retry and promise-retry modernize these concepts for async/await workflows. Specialized wrappers like retry-axios and retry-request offer drop-in solutions for specific HTTP libraries but introduce tighter coupling. Understanding these distinctions is critical for architects deciding between building custom resilience logic versus adopting specialized, potentially fragile, third-party wrappers.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
async-retry01,918-305 years agoMIT
backoff0335-1111 years agoMIT
promise-retry0319-116 years agoMIT
retry01,258-235 years agoMIT
retry-axios051164.9 kB15 months agoApache-2.0
retry-request03,19616.3 kB605a month agoMIT

Strategic Retry Logic and Resilience Patterns in JavaScript

Building resilient frontend and Node.js applications means accepting that networks fail, APIs timeout, and services glitch. The difference between a crashing app and a seamless user experience often comes down to how you handle these transient errors. The JavaScript ecosystem offers several tools for this, ranging from low-level primitives to high-level HTTP wrappers. Let's dive into six specific packagesโ€”async-retry, backoff, promise-retry, retry, retry-axios, and retry-requestโ€”to understand when each belongs in your architecture.

๐Ÿ”„ Core Execution Models: Callbacks vs. Promises

The most fundamental split in this group is between older callback-based designs and modern promise-driven workflows. This dictates how the code reads and how it fits into your existing async/await structures.

retry is the grandfather of this list. It uses a callback pattern where you pass a function to attempt, and a separate callback to handle the result or error. It forces you into a nested structure that feels out of place in modern codebases.

// retry: Callback-based
const operation = new RetryOperation(retries);

operation.attempt(function(currentAttempt) {
  fetchData(function(err, result) {
    if (operation.retry(err)) {
      return;
    }
    console.log(result);
  });
});

backoff follows a similar legacy approach, focusing specifically on the timing strategy rather than the whole operation flow. You create a backoff instance and wire up events for when to try again.

// backoff: Event-driven callback
const backoff = require('backoff');
const fibBackoff = backoff.fibonacci();

fibBackoff.on('ready', function() {
  fetchData(function(err, result) {
    if (err) {
      fibBackoff.backoff(); // Trigger next attempt after delay
    } else {
      fibBackoff.reset();
      console.log(result);
    }
  });
});

fibBackoff.start();

promise-retry bridges the gap. It takes the logic of retry but wraps it so you can return promises. It still expects a function that returns a promise, but it handles the chaining internally.

// promise-retry: Promise wrapper
const promiseRetry = require('promise-retry');

promiseRetry(function(retry, number) {
  return fetchData()
    .catch(function(err) {
      if (number <= 3) {
        return retry(err); // Pass error to retry logic
      }
      throw err;
    });
}, { retries: 3 });

async-retry is the modern standard. It is built entirely around async/await. You pass an async function, and it handles the looping internally. The code looks synchronous and clean, which reduces cognitive load.

// async-retry: Native async/await
const retry = require('async-retry');

try {
  const result = await retry(
    async (bail) => {
      const res = await fetchData();
      if (res.status === 404) {
        bail(new Error('Not found')); // Stop retrying immediately
        return;
      }
      return res;
    },
    { retries: 3 }
  );
  console.log(result);
} catch (err) {
  console.error('Failed after all retries', err);
}

๐ŸŒ HTTP Specific Wrappers vs. Generic Utilities

A critical architectural decision is whether to use a generic tool that works for databases, file systems, and APIs, or a specialized tool tied to a specific HTTP library.

retry-axios is a specialized interceptor for Axios. It attaches directly to the Axios instance. This is convenient but creates a hard dependency on Axios. If you ever switch to fetch or ky, this logic becomes useless.

// retry-axios: Axios Interceptor
const axios = require('axios');
const setupRetry = require('retry-axios');

const client = axios.create();
setupRetry({ axios: client });

// Automatically retries failed requests on this instance
client.get('/api/data').then(res => console.log(res.data));

retry-request is similarly tied to the request library (and by extension, many Google Cloud Node.js clients). Since the request library itself is deprecated and unmaintained, relying on this wrapper introduces significant technical debt.

// retry-request: Tied to 'request' library
const request = require('retry-request');

request({ uri: 'https://api.example.com/data' }, function(err, res, body) {
  if (err) return console.error(err);
  console.log(body);
});

async-retry, promise-retry, retry, and backoff are generic. They don't care if you are fetching data, reading a file, or querying a database. This makes them more future-proof.

// async-retry: Generic usage (Database example)
await retry(async () => {
  return await db.query('SELECT * FROM users');
});

// async-retry: Generic usage (File system example)
await retry(async () => {
  return await fs.promises.readFile('config.json');
});

โš ๏ธ Maintenance Status and Deprecation Risks

In architectural decisions, the lifespan of a library is as important as its features. Several packages in this list carry heavy warnings.

retry-request depends on request, which has been officially deprecated since 2020. Using this in a new project is strongly discouraged. The ecosystem has moved to node-fetch, axios, or native fetch. If you see this in a codebase, plan to migrate away from it.

backoff and retry show signs of stagnation. While they still work, they lack the ergonomic improvements of modern JavaScript. They are "safe" in legacy apps but poor choices for greenfield development because they force callback hell.

async-retry is actively maintained and widely adopted in the modern Node.js ecosystem (including by Vercel and other major platforms). It receives updates to match current JavaScript standards.

retry-axios is useful but risky. Its life cycle is tied to Axios's internal interceptor API. If Axios makes a breaking change to how interceptors handle errors, this package could break unexpectedly.

๐ŸŽฏ Controlling the Retry Flow

How do you decide when to stop retrying? Different packages offer different levels of control.

async-retry gives you a bail function. This is powerful because it lets you distinguish between "try again" errors (like a 503 Service Unavailable) and "stop now" errors (like a 404 Not Found or a validation error).

// async-retry: Precise control with bail
await retry(async (bail) => {
  const response = await fetch('/api/resource');
  
  if (response.status === 404) {
    // Don't retry for 404s
    bail(new Error('Resource missing'));
    return;
  }
  
  if (!response.ok) {
    // Throw to trigger a retry
    throw new Error('Server error, retrying...');
  }
  
  return response.json();
});

promise-retry relies on you calling the retry function passed into your callback. It is slightly more verbose to implement conditional logic compared to bail.

// promise-retry: Manual retry trigger
await promiseRetry((retry, number) => {
  return fetchData().catch(err => {
    if (err.status === 404) {
      throw err; // Stops retrying
    }
    if (number < 3) {
      return retry(err); // Continues retrying
    }
    throw err;
  });
});

retry-axios handles this via configuration objects where you define which status codes should trigger a retry. It is less flexible for complex logic but sufficient for standard HTTP patterns.

// retry-axios: Config-based control
setupRetry({
  axios: client,
  retryDelay: 1000,
  retryAttempts: 3,
  shouldRetry: (error) => {
    // Custom logic to decide retry
    return error.response && error.response.status === 503;
  }
});

๐Ÿ“Š Summary of Trade-offs

Featureasync-retrypromise-retryretry / backoffretry-axiosretry-request
StyleAsync/AwaitPromisesCallbacksInterceptorCallback/Stream
ScopeGenericGenericGenericAxios OnlyRequest Only
MaintenanceActiveStableLegacy/StaleModerateDeprecated Risk
Controlbail() functionretry() callEvent/CallbackConfig ObjectConfig Object
Best ForModern AppsLegacy PromisesVery Old CodeAxios ProjectsGoogle Cloud Legacy

๐Ÿ’ก The Architect's Recommendation

For nearly all modern frontend and Node.js projects, async-retry is the superior choice. It is framework-agnostic, meaning you can use it with fetch, axios, graphql, or database clients without locking yourself into a specific HTTP library. Its support for the bail pattern provides the clarity needed to handle complex error scenarios without nesting callbacks.

Reserve retry-axios only for quick prototypes where you are 100% certain Axios will remain your HTTP client forever. In large-scale enterprise applications, the coupling it introduces is often not worth the minor convenience.

Finally, treat retry-request, retry, and backoff as legacy artifacts. If you encounter them during maintenance, schedule time to refactor them into async-retry or native async/await loops. Building new features on top of deprecated or callback-heavy foundations slows down development and increases the risk of future breakage.

Resilience is essential, but it shouldn't come at the cost of code clarity or future flexibility. Choose tools that grow with your stack, not ones that anchor you to the past.

How to Choose: async-retry vs backoff vs promise-retry vs retry vs retry-axios vs retry-request

  • async-retry:

    Choose async-retry for modern, promise-based applications where you need a lightweight, generic utility to wrap any async operation (not just HTTP). It is the most robust choice for new projects requiring custom retry logic with clean async/await syntax and active maintenance.

  • backoff:

    Avoid choosing backoff for new projects as it relies on legacy callback patterns and appears largely unmaintained. Only consider it if you are refactoring a very old codebase that already depends on its specific exponential backoff strategy and cannot be easily migrated to promise-based alternatives.

  • promise-retry:

    Select promise-retry if your project already uses the retry package logic but requires a Promise interface, or if you need specific compatibility with npm-style retry behaviors. It is a solid middle-ground for generic promise retries but lacks the modern DX of async-retry.

  • retry:

    Do not use retry in new frontend or modern Node.js architectures. It is a foundational but outdated callback-based library. Use it only if you are maintaining legacy systems where changing the control flow from callbacks to promises is too risky or costly.

  • retry-axios:

    Use retry-axios only if you are strictly bound to the Axios ecosystem and need a quick, zero-config way to add retries to existing interceptors. Be aware that this adds a dependency on Axios internals, which may break if Axios updates its interceptor API significantly.

  • retry-request:

    Choose retry-request exclusively if your infrastructure relies heavily on the request library (which is itself deprecated) or Google Cloud libraries that depend on it. For any other HTTP client, this package is obsolete and should be avoided.

README for async-retry

async-retry

Retrying made simple, easy, and async.

Usage

// Packages
const retry = require('async-retry');
const fetch = require('node-fetch');

await retry(
  async (bail) => {
    // if anything throws, we retry
    const res = await fetch('https://google.com');

    if (403 === res.status) {
      // don't retry upon 403
      bail(new Error('Unauthorized'));
      return;
    }

    const data = await res.text();
    return data.substr(0, 500);
  },
  {
    retries: 5,
  }
);

API

retry(retrier : Function, opts : Object) => Promise
  • The supplied function can be async or not. In other words, it can be a function that returns a Promise or a value.
  • The supplied function receives two parameters
    1. A Function you can invoke to abort the retrying (bail)
    2. A Number identifying the attempt. The absolute first attempt (before any retries) is 1.
  • The opts are passed to node-retry. Read its docs
    • retries: The maximum amount of times to retry the operation. Default is 10.
    • factor: The exponential factor to use. Default is 2.
    • minTimeout: The number of milliseconds before starting the first retry. Default is 1000.
    • maxTimeout: The maximum number of milliseconds between two retries. Default is Infinity.
    • randomize: Randomizes the timeouts by multiplying with a factor between 1 to 2. Default is true.
    • onRetry: an optional Function that is invoked after a new retry is performed. It's passed the Error that triggered it as a parameter.

Authors