Skip to content
jshacks.dev
Functions

Implement a Retry Helper From Scratch in JavaScript

Build a retry helper from scratch in JavaScript with attempt limits, exponential backoff, jitter, a retry predicate, abort support and tests. Node.js 24.

7 min read
Summarize in AI
Flat illustration of items passing through a chain of collection methods, with the JavaScript, Vite, npm and TypeScript logos.

Retrying a failed call is easy to write badly. The loop that catches an error and tries again immediately turns a brief outage into a flood of requests, retries things that can never succeed and swallows the real error after the last attempt. A good retry helper decides how many times to try, how long to wait between attempts, which errors deserve another try and how to stop when the caller gives up. This post builds one on Node.js 24, in the order an interviewer tends to ask, and ends with tests that need no real waiting. If you only need the backoff arithmetic, see retrying a function with exponential backoff.

The contract

retry(fn, options) calls fn until it resolves, and returns that result. If every attempt fails, it rejects with the last error. fn may be synchronous or return a promise. Options: retries for the number of extra attempts, a delay policy, a shouldRetry(error) predicate and an AbortSignal.

Count carefully, because off-by-one is the first bug. With retries: 3 the function runs at most four times: the first attempt plus three retries.

The first version

JavaScript
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

async function retry(fn, { retries = 3, delayMs = 100 } = {}) {
  let lastError;

  for (let attempt = 0; attempt <= retries; attempt += 1) {
    try {
      return await fn(attempt);
    } catch (error) {
      lastError = error;

      if (attempt < retries) {
        await sleep(delayMs);
      }
    }
  }

  throw lastError;
}

let calls = 0;

const value = await retry(
  async () => {
    calls += 1;
    if (calls < 3) throw new Error(`fail ${calls}`);
    return "ok";
  },
  { retries: 3, delayMs: 10 },
);

console.log(value, calls);
Text
ok 3

The function failed twice and succeeded on the third call, so the helper returned "ok" after three calls. Three details are worth stating. await fn(attempt) inside the try is needed, because without await a rejected promise would escape the try block and never be caught. The if (attempt < retries) check avoids sleeping after the final failure, where waiting accomplishes nothing. And the attempt number is passed to fn, which helps logging and lets a caller change behavior on a retry.

When everything fails, the caller gets the last error.

JavaScript
try {
  await retry(
    async () => {
      throw new Error("down");
    },
    { retries: 1, delayMs: 1 },
  );
} catch (error) {
  console.log(error.message);
}
Text
down

Exponential backoff

A fixed delay hammers a struggling service at a constant rate. Exponential backoff doubles the wait after each failure, so the load drops as the trouble continues.

JavaScript
function backoff(attempt, { baseMs = 100, factor = 2, maxMs = 10_000 } = {}) {
  return Math.min(maxMs, baseMs * factor ** attempt);
}

console.log([0, 1, 2, 3, 4].map((n) => backoff(n)));
console.log(backoff(20));
Text
[ 100, 200, 400, 800, 1600 ]
10000

The cap matters. Without maxMs, attempt twenty would wait over a day. Pick a ceiling that matches how long the caller is willing to be stuck, not the largest number that fits.

Jitter

Exponential backoff has a flaw when many clients fail at the same moment, for example after a brief outage of a shared service. They all wait exactly 100 ms, retry together, fail together, wait 200 ms and retry together again. The retries stay synchronized and arrive as spikes. Random jitter spreads them out. The "full jitter" approach picks a random delay between zero and the computed backoff, a pattern described in the AWS Architecture Blog post on exponential backoff and jitter.

JavaScript
function fullJitter(attempt, options, random = Math.random) {
  return Math.floor(random() * backoff(attempt, options));
}

console.log(fullJitter(3, {}, () => 0.5));
console.log(fullJitter(3, {}, () => 0.99));
Text
400
792

With the attempt-three ceiling of 800, a random value of 0.5 gives 400 and 0.99 gives 792. Passing the random source as a parameter keeps the function testable, the same way an injected clock does. Real runs differ, which is the point.

Which errors to retry

Not every failure is worth another attempt. A network timeout or a 503 response may succeed later. A 400 response, a validation error or a TypeError from a bug will fail the same way every time, and retrying only delays the error and adds load. A predicate lets the caller decide.

JavaScript
async function retry(fn, options = {}) {
  const {
    retries = 3,
    shouldRetry = () => true,
    delay = (attempt) => backoff(attempt),
    signal,
  } = options;

  let lastError;

  for (let attempt = 0; attempt <= retries; attempt += 1) {
    signal?.throwIfAborted();

    try {
      return await fn(attempt);
    } catch (error) {
      lastError = error;

      const isLast = attempt === retries;

      if (isLast || !shouldRetry(error, attempt)) {
        throw error;
      }

      await sleep(delay(attempt));
    }
  }

  throw lastError;
}

const transient = (error) => error.code === "ETIMEDOUT" || error.status >= 500;

let tries = 0;

try {
  await retry(
    async () => {
      tries += 1;
      const error = new Error("bad request");
      error.status = 400;
      throw error;
    },
    { retries: 5, shouldRetry: transient, delay: () => 1 },
  );
} catch (error) {
  console.log(error.message, tries);
}
Text
bad request 1

The function ran once, because a 400 is not transient, so the helper rethrew at once instead of trying five more times. Rethrowing the original error, not a wrapper, keeps the stack trace and the properties the caller may check. The predicate also receives the attempt number, in case the policy depends on it.

Respecting a cancellation signal

A retry loop can run for a long time, and the caller may no longer care. An AbortSignal is the standard way to say so. The check at the top of the loop handles aborting between attempts, but the helper also needs to stop a sleep in progress.

JavaScript
function sleep(ms, signal) {
  return new Promise((resolve, reject) => {
    if (signal?.aborted) {
      reject(signal.reason);
      return;
    }

    const timer = setTimeout(() => {
      signal?.removeEventListener("abort", onAbort);
      resolve();
    }, ms);

    function onAbort() {
      clearTimeout(timer);
      reject(signal.reason);
    }

    signal?.addEventListener("abort", onAbort, { once: true });
  });
}

const controller = new AbortController();
const pending = sleep(10_000, controller.signal);

controller.abort(new Error("stopped"));

try {
  await pending;
} catch (error) {
  console.log(error.message);
}
Text
stopped

Without the abort handling, cancelling during a ten-second wait would leave the program waiting for the timer. Clearing the timer on abort and removing the listener on completion keeps both from leaking. In the retry loop, replace sleep(delay(attempt)) with sleep(delay(attempt), signal).

Putting it together

JavaScript
async function retry(fn, options = {}) {
  const {
    retries = 3,
    shouldRetry = () => true,
    delay = (attempt) => fullJitter(attempt, {}),
    signal,
  } = options;

  for (let attempt = 0; ; attempt += 1) {
    signal?.throwIfAborted();

    try {
      return await fn(attempt);
    } catch (error) {
      if (attempt >= retries || !shouldRetry(error, attempt)) {
        throw error;
      }

      await sleep(delay(attempt), signal);
    }
  }
}

This is the version to leave on the whiteboard. The loop has no lastError variable because the throw happens at the moment the decision is made. Every path ends in a return or a throw, so there is nothing after the loop.

Retrying safely

Retrying an operation that is not idempotent can do damage. A request that charged a card and then timed out on the way back has succeeded, and a retry charges the card again. Retry reads freely. Retry writes only when the operation is idempotent, for example when the request carries an idempotency key that the server uses to ignore repeats. State that limit in an interview, because it shows you think about what the helper is wrapped around.

Also mind the total time. Four attempts with the default backoff can add several seconds to a request that a user is waiting on. A retry budget, a maximum total elapsed time across all attempts, is often a better limit than an attempt count alone.

Making retries visible

A retry helper that works silently is a liability. When a call succeeds on the third attempt, nobody learns that the service is flaky until the fourth attempt starts failing too. Give the helper an onRetry hook that receives the error, the attempt number and the delay it is about to wait, and let the caller log it or count it in a metric.

The hook belongs in the catch branch, after the decision to retry and before the sleep, so it fires only for retries that will actually happen. Keep it from breaking the helper: if the hook itself throws, you have turned a logging bug into a failed request, so wrap it in its own try and ignore its errors. A counter of retries per dependency is one of the cheapest early warnings a service can have, because a rising retry rate shows up long before the error rate does.

Also decide what the final error says. The original error is the right thing to rethrow, but the number of attempts is useful context. One clean way is to attach it as a property, such as error.attempts = attempt + 1, before rethrowing, so the code that finally handles the failure can report that the helper already tried several times.

Testing it

Tests should not wait for real delays. Pass delay: () => 0 so that no time passes.

JavaScript
import test from "node:test";
import assert from "node:assert/strict";

test("returns after a later success", async () => {
  let calls = 0;
  const result = await retry(
    async () => {
      calls += 1;
      if (calls < 3) throw new Error("no");
      return "yes";
    },
    { retries: 5, delay: () => 0 },
  );

  assert.equal(result, "yes");
  assert.equal(calls, 3);
});

test("stops after retries and throws the last error", async () => {
  let calls = 0;

  await assert.rejects(
    retry(
      async () => {
        calls += 1;
        throw new Error(`fail ${calls}`);
      },
      { retries: 2, delay: () => 0 },
    ),
    { message: "fail 3" },
  );

  assert.equal(calls, 3);
});

test("does not retry when shouldRetry says no", async () => {
  let calls = 0;

  await assert.rejects(
    retry(async () => { calls += 1; throw new Error("fatal"); }, {
      retries: 5,
      shouldRetry: () => false,
      delay: () => 0,
    }),
  );

  assert.equal(calls, 1);
});
Text
ℹ tests 3
ℹ pass 3
ℹ fail 0
Taggedinterview
Share

Keep reading

Flat illustration of two options weighed side by side, with the JavaScript, Vite and Node.js logos.
Functions

Classes vs Factory Functions

Classes vs factory functions in JavaScript compared on private state, this, instanceof, inheritance, memory, JSON and testing, with exact output.

7 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.