07 · Senior Frontend Engineering
hardcodingjavascript~18 min

Circuit Breaker for Flaky APIs

Objective: Protect a UI and a backend from retry storms with a small state machine.

Implement `createBreaker(fn, { threshold, resetMs, now })`. After `threshold` consecutive failures the breaker opens and rejects immediately; after `resetMs` it allows one trial call (half-open).

  • Closed: calls go through; a success resets the failure count.
  • After `threshold` consecutive failures the state is open and calls reject with an Error whose message is 'Circuit open' without calling fn.
  • Once `now() - openedAt >= resetMs`, the next call is a trial: success closes the breaker, failure re-opens it.
  • Expose `state()` returning 'closed' | 'open' | 'half-open'.
JavaScript

⌘/Ctrl + Enter to run tests · Esc then Tab leaves the editor

Output
> Nothing has run yet.
Interview follow-up questions
  • What should the UI show while the breaker is open?
  • How do you stop many concurrent callers from all becoming the trial call?
  • Where do you place a breaker: per endpoint, per host or per feature?