Skip to content

CircuitBreaker

CircuitBreaker<E> = object

Defined in: Core/CircuitBreaker.ts:35

Runs fallible tasks and temporarily blocks calls after enough qualifying failures.

Blocked calls return CircuitBreaker.OpenError without starting their task, giving the dependency 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, signal?: AbortSignal) =>
  paymentBreaker.run(callPaymentGateway(payload), { signal });

E = unknown

readonly reset: () => void

Defined in: Core/CircuitBreaker.ts:67

Resets the breaker to Closed and clears recorded failures. In-flight probes continue and return their results, but cannot change the reset breaker’s state.

void

CircuitBreaker.run for running fallible tasks under circuit breaker policies.


readonly run: <EIn, A>(task, options?) => Deferred<Result<EIn | OpenError<E>, A>>

Defined in: Core/CircuitBreaker.ts:56

Starts a fallible task under 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 run.

Optional cancellation signal for this call.

AbortSignal

Deferred<Result<EIn | OpenError<E>, A>>

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


readonly state: () => State<E>

Defined in: Core/CircuitBreaker.ts:42

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:76

Subscribes a listener callback to state transitions.

Returns an unsubscribe function. Listeners must not throw.

(state) => void

The callback invoked upon each state transition.

() => void