JavaScriptFundamental (ES6), part 1
Exponential backoff retry for async functions in JavaScript
112 retry with exponential backoff, asserted as a list of delays
hardWrite retry(operation, options) that reattempts a failing async operation, waiting base * factor ** (attempt - 1) between tries and capping at maxDelay. Take the clock as an argument so nothing waits on wall time, report the delays it asked for, and show that there is no wait after the final attempt.
Stuck? Three hints, smallest first
- 1. The loop is
for (let attempt = 1; attempt <= attempts; attempt++)with the operation in atryand the wait in thecatch. - 2. Check for the last attempt before waiting. Waiting after the attempt you will not retry is a delay nobody ever benefits from.
- 3. Do not measure the delays with a real clock. Report them through a callback and assert the list —
[100, 200, 400]is a much better test than a stopwatch.
const makeClock = () => {
let now = 0;
let seq = 0;
const timers = [];
const drainMicrotasks = async () => {
for (let i = 0; i < 50; i++) await Promise.resolve();
};
return {
now: () => now,
wait: (ms) => new Promise((resolve) => timers.push({ at: now + ms, seq: seq++, resolve })),
async runAll() {
await drainMicrotasks(); // drain BEFORE the clock moves
while (timers.length) {
timers.sort((a, b) => a.at - b.at || a.seq - b.seq);
const next = timers.shift();
now = next.at;
next.resolve();
await drainMicrotasks();
}
return now;
},
};
};
const retry = async (operation, options) => {
const { attempts, base, factor = 2, maxDelay = Infinity, clock, onWait } = options;
let lastError;
for (let attempt = 1; attempt <= attempts; attempt++) {
try {
return await operation(attempt);
} catch (error) {
lastError = error;
if (attempt === attempts) break; // no wait after the try you will not repeat
const delay = Math.min(base * factor ** (attempt - 1), maxDelay);
if (onWait) onWait(delay);
await clock.wait(delay);
}
}
throw lastError;
};
const flaky = (failures) => {
let calls = 0;
return async (attempt) => {
calls++;
if (calls <= failures) throw new Error(`attempt ${attempt} failed`);
return `ok on attempt ${attempt}`;
};
};
const attempt = async (options, failures) => {
const clock = makeClock();
const delays = [];
let value = 'no value';
let failure = 'no error';
const settled = retry(flaky(failures), { ...options, clock, onWait: (d) => delays.push(d) })
.then((v) => { value = v; }, (e) => { failure = e.message; });
await clock.runAll();
await settled;
return { value, failure, delays, at: clock.now() };
};
const doubling = await attempt({ attempts: 5, base: 100 }, 3);
const capped = await attempt({ attempts: 5, base: 100, maxDelay: 250 }, 3);
const flat = await attempt({ attempts: 4, base: 100, factor: 1 }, 3);
const hopeless = await attempt({ attempts: 3, base: 100 }, 99);
const firstTime = await attempt({ attempts: 5, base: 100 }, 0);
console.log('doubling :', doubling.delays, '->', doubling.value, '| clock:', doubling.at);
console.log('capped :', capped.delays, '| clock:', capped.at);
console.log('flat :', flat.delays);
console.log('hopeless :', hopeless.delays, '->', hopeless.failure);
Output
8 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 8 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('three failures then a success on the fourth attempt', doubling.value, 'ok on attempt 4');
test('the waits doubled each time', doubling.delays, [100, 200, 400]);
test('and the whole thing cost 700 on the injected clock, with nothing really waited for', doubling.at, 700);
test('maxDelay stops the growth without stopping the retries', [capped.delays, capped.at], [[100, 200, 250], 550]);
test('a factor of 1 is a fixed delay, which is the version that stampedes a server', flat.delays, [100, 100, 100]);
test('when every attempt fails, the last error is what comes out', hopeless.failure, 'attempt 3 failed');
test('and three attempts mean two waits: nothing sleeps after the final failure', [hopeless.delays, hopeless.at], [[100, 200], 300]);
test('an operation that works first time waits for nothing at all', [firstTime.value, firstTime.delays, firstTime.at], ['ok on attempt 1', [], 0]);
The reason backoff exists is that the usual cause of a failure is load, and retrying immediately adds load. Doubling gives the far end room to recover, and maxDelay stops the doubling from turning a transient blip into a nine-minute wait. A factor of 1 is the version to recognise and avoid: every client retries on the same fixed rhythm, so they all come back together and knock the server over again.
Injecting the clock is what makes this testable. With setTimeout the honest test of a doubling backoff takes seven hundred milliseconds and asserts almost nothing; with an injected clock the delays are a list of numbers, and [100, 200, 400] is a stronger statement than any elapsed-time check. The rule that makes a fake clock work is unglamorous: drain the pending microtasks before moving the time forward, so code that is mid-attempt has already registered its next wait and registers it against the right now.
Two details the assertions pin down. Three attempts mean two waits, because sleeping after the attempt you have already decided not to repeat is pure latency at the worst possible moment. And a real implementation needs one thing left out here for determinism: jitter. Multiply each delay by a random factor so that a thousand clients that failed together do not come back in lockstep. It is also worth deciding what to retry — a 500 or a dropped connection, yes; a 400 or a validation failure, never, because the answer will not change.