Circuit Breaker
Protect TypeScript and Node.js applications from cascading failures with the AxilJS CircuitBreaker, failure thresholds, reset timeouts, and fallback responses.
On this page13
AxilJS provides a CircuitBreaker for protecting applications and services from cascading failures.
The circuit breaker pattern prevents repeated calls to an unhealthy dependency after failures exceed a configured threshold. It can temporarily stop requests and use a fallback response until the dependency has an opportunity to recover.
Usage
Import CircuitBreaker from @axiljs/circuit and configure it with a failure threshold, reset timeout, and optional fallback.
1import { CircuitBreaker } from '@axiljs/circuit'
2
3const cb = new CircuitBreaker('payment', {
4 failureThreshold: 5,
5 resetTimeoutMs: 30000,
6 fallback: () => ({
7 error: 'Unavailable'
8 })
9})
10
11const result = await cb.execute(
12 () => paymentService.charge(amount)
13)The circuit breaker wraps the operation that depends on an external or potentially unreliable service.
In this example:
paymentidentifies the circuit.failureThreshold: 5configures the number of failures before the circuit opens.resetTimeoutMs: 30000configures a 30-second reset timeout.fallbackprovides an alternative response when the protected operation is unavailable.execute()runs the protected operation through the circuit breaker.
Circuit Breaker States
A circuit breaker transitions between three states:
| From | Event | To |
|---|---|---|
CLOSED | failures exceed the threshold | OPEN |
OPEN | reset timeout expires | HALF_OPEN |
HALF_OPEN | probe request succeeds | CLOSED |
HALF_OPEN | probe request fails | OPEN |
The complete state transition is:
In short: CLOSED → (failures) → OPEN → (timeout) → HALF_OPEN → (success) → CLOSED.
CLOSED
In the CLOSED state, requests are allowed to execute normally.
Failures are tracked by the circuit breaker. Once the configured failure threshold is reached, the circuit transitions to OPEN.
OPEN
In the OPEN state, the circuit stops normal execution against the protected dependency.
The configured reset timeout determines when the circuit can attempt recovery.
If a fallback is configured, it can provide an alternative result while the dependency is unavailable.
HALF_OPEN
After the reset timeout expires, the circuit transitions to HALF_OPEN.
This state gives the protected dependency an opportunity to recover.
A successful operation transitions the circuit back to CLOSED.
Failure Threshold
The failureThreshold option determines how many failures cause the circuit to open.
const cb = new CircuitBreaker('payment', {
failureThreshold: 5
})With a threshold of 5, the circuit is configured to open after the configured failure condition reaches five failures.
More precisely: until minimumRequests (default 10) calls have been counted, the circuit opens once failureThreshold failures have occurred. After that, it opens when the failure rate reaches failureRateThreshold (default 0.5). In HALF_OPEN, a single probe call is let through; a failure reopens the circuit.
Choose a threshold appropriate to the reliability characteristics and traffic pattern of the protected service.
Reset Timeout
Use resetTimeoutMs to configure how long the circuit remains open before attempting recovery.
const cb = new CircuitBreaker('payment', {
resetTimeoutMs: 30000
})The value is specified in milliseconds. 30000 represents 30 seconds.
Fallback Handling
A fallback can provide an alternative result when the protected operation is unavailable.
1const cb = new CircuitBreaker('payment', {
2 failureThreshold: 5,
3 resetTimeoutMs: 30000,
4 fallback: () => ({
5 error: 'Unavailable'
6 })
7})Fallbacks are useful when an application can return a degraded response instead of propagating a dependency failure to the caller.
Protecting External Services
A circuit breaker is particularly useful around operations that depend on services outside the current application process.
const result = await cb.execute(
() => paymentService.charge(amount)
)The protected operation can represent a payment service, HTTP API, database-dependent operation, or another service whose failure could affect the availability of the calling application.
Circuit Breaker Workflow
A typical execution flow is:
When the circuit is CLOSED, the protected service is called: a success continues normally, and a failure increments the failure count.
This isolates failures from an unhealthy dependency and provides a controlled recovery path instead of continuously sending requests to a failing service.
Options
| Option | Default | Description |
|---|---|---|
failureThreshold | 5 | Failures that open the circuit before minimumRequests is reached |
resetTimeoutMs | 60000 | Time in OPEN before a HALF_OPEN probe |
requestTimeoutMs | 10000 | Timeout for each protected call |
minimumRequests | 10 | Calls needed before the failure rate is used |
failureRateThreshold | 0.5 | Failure rate (0–1) that opens the circuit |
fallback | throws CircuitOpenError | Called instead of the operation while the circuit is open |
rollingWindowMs | 0 | Count calls only within this window; 0 = cumulative counters |
maxConcurrent | unlimited | Bulkhead: maximum concurrent executions |
maxQueue | 0 | Bulkhead: callers that may wait for a slot; beyond that BulkheadRejectedError is thrown |
logger | console | Where state-change messages go: false = silent, or an object with info(msg) and warn(msg) |
Other methods: getState(), getStats() and reset().
Logging and State-Change Events
Note
New in 0.3.3: the logger option.
By default each transition is printed to the console. Use the logger option to silence it or route it to your own logger; opening the circuit is reported through warn, recovery through info.
1import { CircuitBreaker } from '@axiljs/circuit'
2
3const quiet = new CircuitBreaker('payment', { logger: false })
4
5const routed = new CircuitBreaker('payment', {
6 logger: { info: (m) => log.info(m), warn: (m) => log.warn(m) }
7})State changes are always observable through the stateChange event, whatever the logger setting. A full bulkhead also emits bulkheadRejected.
1quiet.on('stateChange', (next, previous) => {
2 metrics.gauge('circuit_open', 'Circuit open', ['name'])
3 .set(next === 'OPEN' ? 1 : 0, { name: quiet.name })
4 console.log(`payment circuit: ${previous} → ${next}`)
5})Why Use a Circuit Breaker?
The circuit breaker pattern is useful for improving resilience in distributed systems and service-oriented applications.
Common use cases include:
- Payment service calls
- External HTTP APIs
- Microservice-to-microservice requests
- Third-party integrations
- Remote service dependencies
- Unreliable network operations
- Preventing cascading service failures
By stopping repeated calls to a failing dependency, a circuit breaker can help prevent one unhealthy service from causing broader application instability.
Was this page helpful?