Emmanuel Akinfulubi

JavaScriptBasic

Retry a failing operation with backoff in JavaScript

Advanced · 4 min read

Networks fail. A payment server is busy for a second, a phone drops signal in a tunnel, an API says "try again later". Often the same request works if you simply try again a moment later. Doing that well is called retry with backoff: try, and if it fails, wait a little, try again, wait longer, try again, and after a few goes give up.

In this tutorial you will write retry(fn, options), which calls a function that sometimes fails, waits 100 ms, then 200 ms, then 400 ms between attempts, and gives up after four tries. You will also see how to test waiting without actually waiting. You should know what a function and try...catch are. Promises and await are explained below from the start.

Waiting in JavaScript: promises and await

JavaScript doesn't pause while it waits for a network reply. Instead, a slow operation hands back a promise: an object that says "I will have an answer later". Inside a function marked async, the keyword await waits for that answer before moving to the next line.

JavaScript

const later = () => new Promise((resolve) => setTimeout(() => resolve('done'), 10));
async function main() {
  const answer = await later();
  console.log(answer); // done
}
main();

setTimeout(fn, 10) runs fn after about 10 milliseconds, and calling resolve('done') is how the promise delivers its answer. If an awaited promise fails instead, await throws the error, so an ordinary try...catch can catch it.

Exponential backoff

"Exponential" means each wait multiplies the last one, here by 2: 100, 200, 400. Why grow the wait? If a server is overloaded, hammering it every 100 ms makes things worse. Backing off gives it room to recover.

The wait before retry number attempt is baseMs * 2 ** (attempt - 1). ** means "to the power of", so 2 ** 0 is 1, 2 ** 1 is 2 and 2 ** 2 is 4:

JavaScript

const baseMs = 100;
for (let attempt = 1; attempt <= 3; attempt++) console.log(baseMs * 2 ** (attempt - 1));
// prints 100, then 200, then 400

Here is the exercise. Try it yourself first if you like, or read on and we will build it together.

50 Retry a flaky operation with backoff

hard

Call something that sometimes fails, retrying a few times with a growing wait between attempts, then giving up. Adapted: uses an injected clock so the waits can be asserted rather than waited out.

Stuck? Three hints, smallest first
  1. 1. Each wait should be longer than the last, usually doubling. That is exponential backoff.
  2. 2. Give up after a set number of attempts and rethrow the last failure.
  3. 3. Real code adds a random jitter so a thousand clients do not all retry in the same instant.

Step 1: a function that fails twice

To practice, you need something unreliable on purpose. This one throws on its first two calls and succeeds on the third:

Step 1

let calls = 0;
const flaky = async () => {
  calls++;
  if (calls < 3) throw new Error('temporarily unavailable');
  return 'payload';
};
flaky().catch((err) => console.log(err.message)); // temporarily unavailable

Because flaky is async, a throw inside it becomes a failed promise, which .catch receives.

Step 2: try again in a loop

Loop up to attempts times. If a call works, return straight away. If it fails, remember the error and go round again. If the last attempt fails too, throw the last error so the caller knows:

Step 2

async function retry(fn, { attempts = 4 } = {}) {
  let lastError;
  for (let attempt = 1; attempt <= attempts; attempt++) {
    try {
      return { value: await fn(attempt), attempt };
    } catch (err) {
      lastError = err;
    }
  }
  throw lastError;
}
let calls = 0;
const flaky = async () => {
  calls++;
  if (calls < 3) throw new Error('temporarily unavailable');
  return 'payload';
};
retry(flaky).then((result) => console.log(result.value, result.attempt)); // payload 3

{ attempts = 4 } = {} reads an attempts option from an object and uses 4 if it is missing. The result says which attempt worked. This version retries instantly, which is exactly what a struggling server doesn't want.

Step 3: wait between attempts

Add the doubling wait after each failure, but not after the last one: there is no point waiting if you are about to give up. A sleep helper turns setTimeout into a promise you can await:

Step 3

const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function retry(fn, { attempts = 4, baseMs = 100 } = {}) {
  const waits = [];
  let lastError;
  for (let attempt = 1; attempt <= attempts; attempt++) {
    try {
      return { value: await fn(attempt), attempt, waits };
    } catch (err) {
      lastError = err;
      if (attempt === attempts) break;
      const wait = baseMs * 2 ** (attempt - 1);
      waits.push(wait);
      await sleep(wait);
    }
  }
  throw lastError;
}
let calls = 0;
const flaky = async () => {
  calls++;
  if (calls < 3) throw new Error('temporarily unavailable');
  return 'payload';
};
retry(flaky, { baseMs: 10 }).then((r) => console.log(r.attempt, r.waits)); // 3 [ 10, 20 ]

break leaves the loop, and the function throws the last error. The waits list records each wait, so you can see the doubling. Here baseMs is 10 to keep the example quick.

Step 4: why the answer uses a fake clock

With real timers, testing the 100 and 200 ms waits takes 300 ms of real time, and a test can only say "it took roughly that long". The answer passes in a clock object instead. Its wait(ms) returns a promise, just like sleep, but that promise only finishes when the test calls clock.advance(ms) to move pretend time forward.

So the only change to retry is one line: await clock.wait(wait) instead of await sleep(wait). Passing a dependency in, instead of reaching for it inside, is called injecting it. The test can then check the waits exactly: [100, 200], three calls, and 300 ms of pretend time with none of real time.

The clock's advance lets pending promise steps finish before moving time on. Without that, retry might register its next wait after the clock had already moved, and that wait would never come due.

The full solution

The answer panel has makeClock, the finished retry, and the flaky function. It starts the retry, advances the clock by 100 ms and then 200 ms, and prints the attempt, the waits and the pretend time. Press Run to see the output.

The answer

function makeClock() {
  let now = 0;
  const jobs = [];
  return {
    wait(ms) {
      // A promise that resolves when the clock is advanced far enough.
      return new Promise((resolve) => jobs.push({ at: now + ms, resolve }));
    },
    async advance(ms) {
      // Drain first, THEN move the clock. Code that is mid-attempt has not
      // registered its wait yet, and a wait registered after the clock moved
      // would be timed from the wrong "now" and never come due. Letting it
      // settle first is what keeps each wait on the schedule it asked for.
      for (let turn = 0; turn < 20; turn++) await Promise.resolve();
      now += ms;
      for (const j of jobs.filter((j) => j.at <= now)) {
        jobs.splice(jobs.indexOf(j), 1);
        j.resolve();
      }
      for (let turn = 0; turn < 20; turn++) await Promise.resolve();
    },
    get time() { return now; },
  };
}

async function retry(fn, { attempts = 4, baseMs = 100, clock }) {
  const waits = [];
  let lastError;
  for (let attempt = 1; attempt <= attempts; attempt++) {
    try {
      return { value: await fn(attempt), attempt, waits };
    } catch (err) {
      lastError = err;
      if (attempt === attempts) break;
      const wait = baseMs * 2 ** (attempt - 1);   // 100, 200, 400, ...
      waits.push(wait);
      await clock.wait(wait);
    }
  }
  throw lastError;
}

const clock = makeClock();

// Fails twice, then works.
let calls = 0;
const flaky = async () => {
  calls++;
  if (calls < 3) throw new Error('temporarily unavailable');
  return 'payload';
};

const running = retry(flaky, { baseMs: 100, clock });
await clock.advance(100);   // let the first backoff elapse
await clock.advance(200);   // and the second
const result = await running;

console.log('succeeded on attempt', result.attempt);
console.log('waits used:', result.waits);
console.log('total simulated time:', clock.time, 'ms');

Output


      
6 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 6 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

6 checks

test('it eventually succeeded', result.value, 'payload');
test('on the third attempt', result.attempt, 3);
test('after two waits', result.waits.length, 2);
test('and they doubled', result.waits, [100, 200]);
test('the function was called three times', calls, 3);
test('no real time was spent', clock.time, 300);

Adapted: the usual version would use real timers and therefore take a real second to test. Injecting the clock means the doubling is asserted exactly: [100, 200], three calls, 300ms of simulated time and none of real. In production add a random jitter to each wait — without it, every client that failed at the same moment retries at the same moment, which is how a brief outage becomes a stampede.

Common mistakes

  • Retrying with no wait. Instant retries pile more load on a server that is already struggling.
  • Waiting after the final attempt. It delays the error for nothing. Break out first, then throw.
  • Swallowing the error. If every attempt fails, throw the last error so the caller can show a message or log it.

Try it yourself

  1. Add a maxMs option so no wait grows past, say, 1,000 ms. (Hint: Math.min.)
  2. Add random jitter: multiply each wait by a random number between 0.5 and 1. Without jitter, every client that failed at the same moment retries at the same moment.
  3. Only retry errors whose message includes 'temporarily', and throw any other error straight away.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.