Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 2

Circuit breaker pattern in JavaScript

45 A circuit breaker on a fake clock

hard

Wrap a failing service in a breaker: after n failures it opens and refuses calls without making them; after a cooldown it allows one trial call; a failed trial reopens it and a successful one closes it. Drive the cooldown with an injected clock and count how many calls actually reached the service.

Stuck? Three hints, smallest first
  1. 1. Three states — closed, open, half-open — and the transitions are the whole exercise.
  2. 2. While open, throw before calling. The point of the breaker is the call that never happens.
  3. 3. In half-open exactly one call is allowed through. Its outcome decides the next state.

The answer

const fakeClock = () => {
  let now = 0;
  return { get time() { return now; }, advance(ms) { now += ms; } };
};

function breaker(call, { threshold = 3, cooldownMs = 1000, clock }) {
  let state = 'closed';
  let failures = 0;
  let openedAt = 0;

  const wrapped = async (...args) => {
    if (state === 'open') {
      if (clock.time - openedAt < cooldownMs) throw new Error('circuit open, not calling');
      state = 'half-open';                          // one trial call gets through
    }
    try {
      const value = await call(...args);
      state = 'closed';
      failures = 0;
      return value;
    } catch (err) {
      failures++;
      if (state === 'half-open' || failures >= threshold) {
        state = 'open';
        openedAt = clock.time;
        failures = 0;
      }
      throw err;
    }
  };
  wrapped.state = () => state;
  return wrapped;
}

const clock = fakeClock();
let calls = 0;
let healthy = false;
const gateway = async () => {
  calls++;
  if (!healthy) throw new Error('502 from the gateway');
  return 'receipt LAG-0045';
};
const guarded = breaker(gateway, { threshold: 3, cooldownMs: 1000, clock });

const messages = [];
for (let attempt = 0; attempt < 5; attempt++) {
  messages.push(await guarded().catch((err) => err.message));
}
const afterFive = [guarded.state(), calls];

clock.advance(999);
const stillOpen = await guarded().catch((err) => err.message);
clock.advance(1);
const trial = await guarded().catch((err) => err.message);
const afterTrial = [guarded.state(), calls];

clock.advance(1000);
healthy = true;
const recovered = await guarded();
const afterRecovery = [guarded.state(), calls];

healthy = false;
await guarded().catch(() => {});
await guarded().catch(() => {});
const afterTwoMore = [guarded.state(), calls];

console.log('first five  :', messages);
console.log('state, calls:', afterFive, '->', afterTrial, '->', afterRecovery);
console.log('recovered   :', recovered);
console.log('10 attempts made,', calls, 'calls actually reached the gateway');

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('the first three failures go through to the service', messages.slice(0, 3), ['502 from the gateway', '502 from the gateway', '502 from the gateway']);
test('then it opens and refuses without calling anything', [messages.slice(3), afterFive], [['circuit open, not calling', 'circuit open, not calling'], ['open', 3]]);
test('one millisecond before the cooldown it is still refusing', stillOpen, 'circuit open, not calling');
test('at the cooldown exactly one trial call reaches the service', [trial, afterTrial[1]], ['502 from the gateway', 4]);
test('and a failed trial reopens it at once, with no second chance', afterTrial[0], 'open');
test('after the next cooldown a healthy trial closes it again', [recovered, afterRecovery], ['receipt LAG-0045', ['closed', 5]]);
test('closing resets the count, so two failures do not reopen it', afterTwoMore, ['closed', 7]);
test('so ten attempts cost the failing service seven calls, not ten', calls, 7);

A breaker is not about the caller, it is about the callee. A dependency that is down does not want your traffic — retries pile onto a service already struggling, and the queue of hanging requests takes your own process down with it. The last assertion is the entire justification: ten attempts, seven calls, and the three refusals were free and instant.

Half-open is the state people leave out, and without it the breaker is useless in both directions. Never probing means it stays open for ever; letting everything through after the cooldown means the full load returns to a service that may still be broken. One trial call, whose result decides, is the minimum that recovers safely — and the fifth assertion is the strictness that matters: a failed trial reopens immediately rather than allowing a second try.

The clock is injected for the same reason as in exercises 22 and 23. "One millisecond before the cooldown it still refuses, at the cooldown it allows a trial" is a statement about the comparison in the code; with a real clock it would be a statement about how busy the machine was, and the test would be flaky rather than wrong.

What this deliberately omits: a real breaker counts failures over a rolling window, not since the last success, because three failures spread over a day is not an outage. It also usually distinguishes failure types — a 404 is not a reason to open, as exercise 52 argues — and reports state changes, because a breaker that opens silently is an outage you find out about from customers.

Newsletter

New writing, when it lands.

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