Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 2

Circuit breaker with a half-open trial in JavaScript

89 A circuit breaker: closed, open, and the one trial call

hard

Stop hammering a service that is already down. Count consecutive failures, and after a threshold refuse calls outright for a cooldown without touching the upstream at all. When the cooldown elapses, let exactly one trial call through: if it works, close the circuit; if it fails, open it again for another cooldown. The clock is injected, and a success anywhere resets the failure count.

Stuck? Three hints, smallest first
  1. 1. Three pieces of state: the phase, the consecutive failure count, and the time it opened.
  2. 2. Half-open is not a separate timer. It is what "open" means once now - openedAt has reached the cooldown.
  3. 3. A failure during the trial must re-open the circuit and reset openedAt, or the next call gets waved straight through.

The answer

function makeClock() {
  let now = 0;
  return { now: () => now, advance(ms) { now += ms; } };
}

function circuitBreaker({ threshold = 3, cooldownMs = 1000, clock }) {
  let phase = 'closed';
  let failures = 0;
  let openedAt = 0;
  let refused = 0;

  // Half-open is a derived phase, not a stored one.
  const view = () =>
    phase === 'open' && clock.now() - openedAt >= cooldownMs ? 'half-open' : phase;

  return {
    get state() { return view(); },
    get refused() { return refused; },
    get failures() { return failures; },
    async call(work) {
      const at = view();
      if (at === 'open') {
        refused++;
        throw new Error('circuit open, upstream not called');
      }
      try {
        const value = await work();
        failures = 0;
        phase = 'closed';
        return value;
      } catch (err) {
        failures++;
        if (at === 'half-open' || failures >= threshold) {
          phase = 'open';
          openedAt = clock.now();
          failures = 0;
        }
        throw err;
      }
    },
  };
}

const clock = makeClock();
let upstreamCalls = 0;
let mode = 'down';
const upstream = async () => {
  upstreamCalls++;
  if (mode === 'down') throw new Error('503 from the bank');
  return 'balance: 148250 kobo';
};

const cb = circuitBreaker({ threshold: 3, cooldownMs: 1000, clock });
const attempt = async () => { try { return await cb.call(upstream); } catch (err) { return err.message; } };

const firstThree = [await attempt(), await attempt(), await attempt()];
const openedState = cb.state;
const callsWhenItOpened = upstreamCalls;

const whileOpen = await attempt();
const untouchedUpstream = upstreamCalls;

clock.advance(1000);
const beforeTheTrial = cb.state;
const failedTrial = await attempt();
const afterFailedTrial = cb.state;

clock.advance(999);
const stillOpen = cb.state;
clock.advance(1);
mode = 'up';
const passedTrial = await attempt();
const afterPassedTrial = cb.state;

// Two failures, then a success, then two more: the count was reset in between.
mode = 'down';
await attempt();
await attempt();
mode = 'up';
await attempt();
mode = 'down';
await attempt();
await attempt();
const stillClosed = [cb.state, cb.failures];

console.log('first three   :', firstThree[2], '-> state', openedState);
console.log('while open    :', whileOpen, '| upstream calls still', untouchedUpstream);
console.log('after cooldown:', beforeTheTrial, '-> trial says', failedTrial);
console.log('trial passes  :', passedTrial, '-> state', afterPassedTrial);

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('three consecutive failures open the circuit', [firstThree[2], openedState], ['503 from the bank', 'open']);
test('while it is open the call fails fast and the upstream is never touched', [whileOpen, untouchedUpstream, callsWhenItOpened], ['circuit open, upstream not called', 3, 3]);
test('and it counts what it refused, which is the number worth alerting on', cb.refused, 1);
test('once the cooldown has elapsed the phase is half-open, waiting for one trial', beforeTheTrial, 'half-open');
test('a failed trial re-opens it immediately and restarts the cooldown', [failedTrial, afterFailedTrial, stillOpen], ['503 from the bank', 'open', 'open']);
test('a passing trial closes it and the caller gets the real answer', [passedTrial, afterPassedTrial], ['balance: 148250 kobo', 'closed']);
test('a success resets the count, so two later failures do not reach the threshold', stillClosed, ['closed', 2]);
test('across all of that the upstream was called ten times and refused once', [upstreamCalls, cb.refused], [10, 1]);

The state machine is the whole exercise, and the fourth assertion is the piece people leave out. Half-open is not a third timer, it is a question asked at call time: the circuit is open, but has the cooldown elapsed? Deriving it means there is nothing to schedule, nothing to clean up, and no window where a stale timer disagrees with the stored phase.

The second assertion is the reason breakers exist. Once open, the caller fails in microseconds without a socket, a DNS lookup or a 30-second timeout — which is what stops a slow dependency from exhausting your connection pool and turning one sick service into an outage. Failing fast is the feature; the refusal count is the signal you page on.

Two edges to get right. A failure during the trial must reset openedAt, or the next call sees a cooldown that expired long ago and the breaker degenerates into no breaker at all. And the count is of consecutive failures: the last assertion shows a success wiping it, which is what keeps an occasional unrelated error from opening a circuit over the course of a day. What this version does not do is decide what to serve instead. A breaker is only half an answer — the other half is the fallback, whether that is a cached balance, a queued write or an honest "try again shortly". Throwing faster is not the same as degrading gracefully.

Newsletter

New writing, when it lands.

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