Community JavaScript Snippet

A Circuit Breaker State Machine in JavaScript

The 80-line breaker I drop in front of every flaky upstream. Three explicit states, a half-open probe, and a clock you can swap out for tests. No `opossum`, no `cockatiel`, no Redis.

A Circuit Breaker State Machine in JavaScript

The 80-line breaker I drop in front of every flaky upstream. Three explicit states, a half-open probe, and a clock you can swap out for tests. No `opossum`, no `cockatiel`, no Redis.

JavaScript
Frontend
3 snippets
circuit-breaker
resilience
fault-tolerance
code-template
vikramross

By @vikramross

March 9, 2026

·

Updated May 20, 2026

407 views

3

4.5 (11)

Pulling the state machine out of the wrapper is the move that makes a circuit breaker testable. Three states, three transitions: CLOSED counts failures and trips OPEN at the threshold, OPEN refuses calls until openMs has passed and then flips to HALF_OPEN, HALF_OPEN lets exactly one probe through and either snaps back to CLOSED on success or back to OPEN on failure. The injectable now clock is the only reason this code is not flaky to test; once you have it you can fast-forward time without jest.useFakeTimers(). Notice that failures resets only on success, not on the OPEN-to-HALF_OPEN transition, so a flapping upstream cannot soft-reset the count by waiting.