JavaScriptFundamental (ES6), part 2
Retry with a capped backoff and an attempt log in JavaScript
88 A retry that gives up, and reports every attempt it made
hardRetry a failing call with doubling waits, capped at a maximum, and when it runs out of attempts report rather than throw: every attempt, its error, and the delay that followed it. Let the caller mark some errors as not worth retrying, so a 400 stops immediately while a 503 does not. The clock is an argument.
Stuck? Three hints, smallest first
- 1. Push a record per attempt:
{ attempt, error, delay }. The last attempt has no delay after it. - 2.
Math.min(maxMs, baseMs * 2 ** (attempt - 1))is the capped backoff. - 3. A
retryablepredicate decides whether to keep going. Give it a default of "always" so the simple case stays simple.
function makeClock() {
let now = 0;
const jobs = [];
const drain = async () => { for (let turn = 0; turn < 20; turn++) await Promise.resolve(); };
return {
wait(ms) { return new Promise((resolve) => jobs.push({ at: now + ms, resolve })); },
async advance(ms) {
// Drain FIRST, then move the clock. Anything 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.
await drain();
now += ms;
for (const job of jobs.filter((j) => j.at <= now)) {
jobs.splice(jobs.indexOf(job), 1);
job.resolve();
}
await drain();
},
get time() { return now; },
};
}
async function retry(work, { attempts = 4, baseMs = 200, maxMs = 1000, retryable = () => true, clock }) {
const tries = [];
let outcome = { ok: false, tries, reason: 'never ran' };
for (let attempt = 1; attempt <= attempts; attempt++) {
try {
const value = await work(attempt);
outcome = { ok: true, value, attempt, tries };
break;
} catch (err) {
const lastChance = attempt === attempts;
const stop = lastChance || !retryable(err);
const delay = stop ? null : Math.min(maxMs, baseMs * 2 ** (attempt - 1));
tries.push({ attempt, error: err.message, delay });
if (stop) {
outcome = { ok: false, tries, reason: lastChance ? 'out of attempts' : 'not retryable' };
break;
}
await clock.wait(delay);
}
}
return outcome;
}
// 1. Always fails, five attempts, so the cap gets exercised.
const clockA = makeClock();
let callsA = 0;
const alwaysDown = async () => { callsA++; throw new Error('503 from paystack'); };
const runA = retry(alwaysDown, { attempts: 5, baseMs: 200, maxMs: 1000, clock: clockA });
await clockA.advance(200);
await clockA.advance(400);
await clockA.advance(800);
await clockA.advance(1000);
const gaveUp = await runA;
const delays = gaveUp.tries.map((t) => t.delay);
const uncappedFourth = 200 * 2 ** 3;
// 2. A 503 then a 400. The 400 is not worth retrying.
const clockB = makeClock();
let callsB = 0;
const thenRejected = async (attempt) => {
callsB++;
throw new Error(attempt === 1 ? '503 service unavailable' : '400 invalid account number');
};
const runB = retry(thenRejected, { attempts: 5, baseMs: 200, clock: clockB, retryable: (e) => e.message.startsWith('5') });
await clockB.advance(200);
const bailedOut = await runB;
// 3. Fails twice, then works.
const clockC = makeClock();
const flaky = async (attempt) => {
if (attempt < 3) throw new Error('503 from paystack');
return 'receipt/NG-4417';
};
const runC = retry(flaky, { baseMs: 200, clock: clockC });
await clockC.advance(200);
await clockC.advance(400);
const eventually = await runC;
console.log('gave up :', gaveUp.reason, '| delays', delays);
console.log('bailed out :', bailedOut.reason, 'after', bailedOut.tries.length, 'attempts');
console.log('eventually :', eventually.value, 'on attempt', eventually.attempt);
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 gave up and said which way it gave up', [gaveUp.ok, gaveUp.reason], [false, 'out of attempts']);
test('every attempt is reported with the delay that followed it, the last one with none', delays, [200, 400, 800, 1000, null]);
test('the fourth delay is the cap, not the doubling', [delays[3], uncappedFourth], [1000, 1600]);
test('five attempts means five calls and 2400ms of simulated waiting', [callsA, clockA.time], [5, 2400]);
test('a non-retryable error stops it early, with a different reason', [bailedOut.reason, callsB], ['not retryable', 2]);
test('so only the first failure was followed by a wait', bailedOut.tries.map((t) => t.delay), [200, null]);
test('the success path says which attempt worked and what it waited for first', [eventually.ok, eventually.value, eventually.attempt], [true, 'receipt/NG-4417', 3]);
test('and carries the failures it survived on the way', eventually.tries.map((t) => t.delay), [200, 400]);
Returning an outcome instead of throwing is the design choice here, and the point of it is the tries array. A retry that rethrows the last error tells you a call failed; this tells you it failed five times over 2.4 seconds with the same 503, which is the difference between guessing and knowing. Log that array once, at the boundary, rather than a line per attempt.
The cap matters more than the doubling. Uncapped exponential backoff reaches half a minute by attempt eight, and a user has long since given up and pressed the button again; the third assertion is the cap doing its job where the raw doubling would have said 1600ms. Real deployments add jitter on top — a random fraction of each delay — because otherwise every client that failed in the same instant retries in the same instant, and a brief wobble becomes a stampede. It is left out here only because this page has to be deterministic.
The retryable predicate is the part most retry helpers omit and then regret. Retrying a 400, a 401 or a validation failure cannot possibly help: the request is wrong and will still be wrong in 800ms. Worse, retrying a non-idempotent POST that actually succeeded but timed out is how one order becomes three. Retry on timeouts, connection resets and 5xx; report everything else on the first failure.