Skip to content

CircuitBreaker

CircuitBreaker<E> = object

Defined in: Core/CircuitBreaker.ts:39

A stateful fault-isolation barrier that protects downstream services from retry storms.

CircuitBreaker monitors task failures and temporarily blocks execution (“trips”) when failures exceed a configured threshold, fast-failing subsequent calls in 0ms with CircuitBreaker.OpenError to give the failing service time to recover.

  • Closed: Normal execution. Every success resets failure counts (or prunes the sliding window). If failures reach failureThreshold, transitions to Open.
  • Open: Downstream service is failing. Calls immediately fast-fail in 0ms with CircuitBreaker.OpenError. Once resetTimeout elapses, transitions on-demand to HalfOpen.
  • HalfOpen: Trial recovery mode. Allows limited single-probe calls through while fast-failing concurrent callers. If successThreshold consecutive probes succeed, resets to Closed. If any probe fails with a tripping error, immediately transitions back to Open.
const paymentBreaker = CircuitBreaker.make<PaymentGatewayError>({
  failureThreshold: 5,
  resetTimeout: Duration.seconds(30),
  successThreshold: 2,
  shouldTrip: (err) => err.status >= 500 || err.kind === "NetworkTimeout",
});

const chargeCard = (payload: ChargeInput) =>
  pipe(
    callPaymentGateway(payload),
    paymentBreaker.protect,
  );

E = unknown

readonly protect: <EIn, A>(task) => Result<EIn | OpenError<E>, A>

Defined in: Core/CircuitBreaker.ts:59

Protects a fallible task with the circuit breaker’s fault-isolation policies.

  • While Closed: executes the task normally, tracking failures.
  • While Open: fast-fails immediately in 0ms with CircuitBreaker.OpenError<E>.
  • While HalfOpen: allows a single probe call while fast-failing concurrent requests.

EIn extends E = E

A = unknown

Result<EIn, A>

The fallible async computation to protect.

Result<EIn | OpenError<E>, A>

CircuitBreaker.reset to manually force circuit recovery back to Closed state.


readonly reset: () => void

Defined in: Core/CircuitBreaker.ts:68

Manually forces the circuit breaker back to its initial Closed state with zero recorded failures.

void

CircuitBreaker.protect for protecting fallible tasks under circuit breaker policies.


readonly state: () => State<E>

Defined in: Core/CircuitBreaker.ts:46

Returns the current observable lifecycle state of the circuit breaker.

When the circuit is Open and resetTimeout has elapsed, this evaluates to HalfOpen with probeInFlight: false, signaling that the circuit is ready to test downstream recovery.

State<E>


readonly subscribe: (listener) => () => void

Defined in: Core/CircuitBreaker.ts:77

Subscribes a listener callback to state transitions.

Returns an unsubscribe function. Listener exceptions are isolated and never disrupt circuit execution.

(state) => void

The callback invoked upon each state transition.

() => void