JavaScriptFundamental (ES6), part 2
Retry with backoff, max delay and time budget in JavaScript
22 Retry with backoff, a cap and a time budget
hardRetry a flaky call with exponentially growing waits, a maximum single wait, and a total time budget it refuses to exceed. When it gives up, the error it throws must carry the last failure as its cause. Also Basic 50, which is the plain backoff; this one adds the cap, the budget and the cause.
Stuck? Three hints, smallest first
- 1. Take the clock as an argument. The fake one records each wait and jumps forward instantly, so the schedule is assertable.
- 2.
Math.min(capMs, baseMs * 2 ** (attempt - 1))is the capped wait. - 3. Before waiting, check whether the wait would take you past the budget. If it would, stop now rather than after.
// Simulated time. wait() records the delay and moves the clock instantly, so
// nothing here sleeps and the schedule can be asserted exactly.
function fakeClock() {
let now = 0;
const waits = [];
return {
get time() { return now; },
get waits() { return waits.slice(); },
wait(ms) { waits.push(ms); now += ms; return Promise.resolve(); },
};
}
async function retry(task, { attempts = 4, baseMs = 200, capMs = Infinity, budgetMs = Infinity, clock }) {
let last;
for (let attempt = 1; attempt <= attempts; attempt++) {
try { return { value: await task(attempt), attempt }; }
catch (err) {
last = err;
if (attempt === attempts) break;
const wait = Math.min(capMs, baseMs * 2 ** (attempt - 1));
if (clock.time + wait > budgetMs) break; // no point waiting past the budget
await clock.wait(wait);
}
}
throw new Error(`gave up after ${attempts} attempt(s)`, { cause: last });
}
const clock = fakeClock();
let calls = 0;
const flaky = async () => {
calls++;
if (calls < 3) throw new Error('502 from the gateway');
return 'receipt LAG-0007';
};
const good = await retry(flaky, { baseMs: 200, clock });
const capped = fakeClock();
await retry(async () => { throw new Error('down'); }, { attempts: 5, baseMs: 100, capMs: 300, clock: capped }).catch(() => {});
const tight = fakeClock();
const gaveUp = await retry(async () => { throw new Error('down'); }, { attempts: 9, baseMs: 100, budgetMs: 350, clock: tight }).catch((e) => e);
const clean = fakeClock();
await retry(async () => 'first time', { clock: clean });
console.log('succeeded :', good, 'after', clock.waits, 'ms of waiting');
console.log('capped :', capped.waits);
console.log('budgeted :', tight.waits, 'stopped at', tight.time, 'ms');
console.log('cause :', gaveUp.cause.message);
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('it succeeded on the third attempt', good, { value: 'receipt LAG-0007', attempt: 3 });
test('after two waits, which doubled', clock.waits, [200, 400]);
test('600ms of simulated time, none of it real', clock.time, 600);
test('capMs stops the doubling running away', capped.waits, [100, 200, 300, 300]);
test('the budget stops it before the wait that would exceed it', tight.waits, [100, 200]);
test('the final error keeps the last failure as its cause', gaveUp.cause.message, 'down');
test('and says how many attempts were configured', gaveUp.message, 'gave up after 9 attempt(s)');
test('a task that works first time never waits at all', [clean.waits, clean.time], [[], 0]);
Basic 50 covers the doubling; the additions here are the ones that matter in production. Uncapped exponential backoff reaches an hour by attempt 15, so capMs turns the curve into a plateau. And a caller waiting on a request does not care how many attempts you configured, only how long it takes — so the budget is checked before the wait, which is why the third wait of 400ms is never taken rather than being cut short.
cause is the part most retry helpers get wrong. Throwing new Error(‘gave up’) alone destroys the only useful information in the failure: why. The second argument to the Error constructor attaches the original, so a log line can print "gave up after 9 attempts" and the 502 underneath it.
One thing this deliberately does not do: jitter. Real backoff multiplies each wait by a random factor, because a thousand clients that failed in the same second will otherwise retry in the same second and turn a blip into an outage. It is left out here only because a random wait cannot be asserted — in production, add it.