Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 2

Retry only retryable errors in JavaScript

52 Retry only what is worth retrying

hard

Retrying a declined card is pointless and retrying a timeout is essential, so make the retry take a predicate. Give it two error classes and an HTTP status, and prove that a permanent failure costs zero waits and one attempt while a transient one is retried with a growing gap. Exercise 22 is the backoff schedule; this is about which failures reach it at all.

Stuck? Three hints, smallest first
  1. 1. Ask the predicate before the wait. A failure you will not retry should not cost even one delay.
  2. 2. Class for your own failures, status code for a failure that arrived over the wire: 4xx is your fault, 5xx is theirs.
  3. 3. When you refuse to retry, wrap the failure rather than replacing it, so the caller still has the original.

The answer

class TransientError extends Error {
  constructor(message, options) { super(message, options); this.name = 'TransientError'; }
}
class PermanentError extends Error {
  constructor(message, options) { super(message, options); this.name = 'PermanentError'; }
}

const 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(); },
  };
};

const worthRetrying = (err) =>
  err instanceof TransientError || (typeof err.status === 'number' && err.status >= 500);

async function retryIf(task, { attempts = 4, baseMs = 100, retryable, clock }) {
  let last;
  for (let attempt = 1; attempt <= attempts; attempt++) {
    try { return { value: await task(attempt), attempts: attempt }; }
    catch (err) {
      last = err;
      if (!retryable(err)) throw new Error('not retryable: ' + err.name, { cause: err });
      if (attempt === attempts) break;
      await clock.wait(baseMs * attempt);
    }
  }
  throw new Error('gave up after ' + attempts + ' attempts', { cause: last });
}

const withStatus = (status, message) => Object.assign(new Error(message), { status });

const flaky = fakeClock();
let tries = 0;
const recovered = await retryIf(async () => {
  tries++;
  if (tries < 3) throw new TransientError('socket hang up');
  return 'receipt LAG-0052';
}, { baseMs: 100, retryable: worthRetrying, clock: flaky });

const declined = fakeClock();
const refused = await retryIf(async () => { throw new PermanentError('card declined'); },
  { retryable: worthRetrying, clock: declined }).catch((err) => err);

const serverError = fakeClock();
let fiveHundreds = 0;
const gaveUpOn500 = await retryIf(async () => { fiveHundreds++; throw withStatus(503, 'service unavailable'); },
  { attempts: 3, baseMs: 100, retryable: worthRetrying, clock: serverError }).catch((err) => err);

const notFound = fakeClock();
let lookups = 0;
const gaveUpOn404 = await retryIf(async () => { lookups++; throw withStatus(404, 'no such till'); },
  { attempts: 3, retryable: worthRetrying, clock: notFound }).catch((err) => err.message);

const clean = fakeClock();
const firstTime = await retryIf(async () => 'nothing to retry', { retryable: worthRetrying, clock: clean });

console.log('recovered  :', recovered, 'after waits', flaky.waits);
console.log('declined   :', refused.message, '/ cause:', refused.cause.name, '- waits:', declined.waits);
console.log('503        :', gaveUpOn500.message, 'after', fiveHundreds, 'attempts and waits', serverError.waits);
console.log('404        :', gaveUpOn404, 'after', lookups, '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.

8 checks

test('a transient failure is retried until it works', recovered, { value: 'receipt LAG-0052', attempts: 3 });
test('with a growing gap, and no real time spent', [flaky.waits, flaky.time], [[100, 200], 300]);
test('a permanent failure is not retried even once', [declined.waits, refused.message], [[], 'not retryable: PermanentError']);
test('and the original comes along as the cause, still typed', [refused.cause instanceof PermanentError, refused.cause.message], [true, 'card declined']);
test('a 503 is somebody else\'s problem, so it is retried to exhaustion', [fiveHundreds, serverError.waits], [3, [100, 200]]);
test('and the last failure is kept as the cause of giving up', gaveUpOn500.cause.status, 503);
test('a 404 is your problem, so it is attempted once and no more', [lookups, notFound.waits, gaveUpOn404], [1, [], 'not retryable: Error']);
test('a task that works first time waits for nothing at all', [firstTime.attempts, clean.waits], [1, []]);

A retry loop without a predicate is a way of turning one wrong answer into four. A declined card, a validation failure, a missing record and a malformed request are all settled — the answer will be identical in 200ms, so the only things retrying buys are latency for the customer and load for the service. The third and seventh assertions are the same rule from two angles: no waits, one attempt, and the failure handed straight back.

Where the predicate looks matters as much as what it says. Asking before the wait is what makes "not retryable" cost nothing; asking after would still delay the caller for a failure you had already decided not to retry. And wrapping with cause rather than rethrowing plainly lets the caller tell "this failed and we did not try again" from "this failed four times", which are different operational events.

The rule of thumb encoded in worthRetrying: your own classes for failures you raise, status codes for failures that arrive over the wire, 5xx and timeouts retryable, 4xx not. Two exceptions worth remembering — 429 is retryable but only after the interval the server names in Retry-After, and 408 and 409 often are too. Also: retry only what is idempotent. A retried POST that already succeeded but timed out on the way back charges the customer twice, which is what idempotency keys exist to prevent.

Newsletter

New writing, when it lands.

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