Background Jobs

AxilJS Circuit Breaker for Fault Tolerance

Protect TypeScript and Node.js applications from cascading failures with the AxilJS CircuitBreaker, failure thresholds, reset timeouts, and fallback responses.

4 min readDocumentationEdit this page

Circuit Breaker

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.

typescript
import { CircuitBreaker } from '@axiljs/circuit'
 
const cb = new CircuitBreaker('payment', {
  failureThreshold: 5,
  resetTimeoutMs: 30000,
  fallback: () => ({
    error: 'Unavailable'
  })
})
 
const result = await cb.execute(
  () => paymentService.charge(amount)
)

The circuit breaker wraps the operation that depends on an external or potentially unreliable service.

In this example:

  • payment identifies the circuit.
  • failureThreshold: 5 configures the number of failures before the circuit opens.
  • resetTimeoutMs: 30000 configures a 30-second reset timeout.
  • fallback provides 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:

text
CLOSED
   │
   │ failures exceed threshold
   ▼
 OPEN
   │
   │ reset timeout expires
   ▼
HALF_OPEN
   │
   │ success
   ▼
CLOSED

The complete state transition is:

text
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.

typescript
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.

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.

typescript
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.

typescript
const cb = new CircuitBreaker('payment', {
  failureThreshold: 5,
  resetTimeoutMs: 30000,
  fallback: () => ({
    error: 'Unavailable'
  })
})

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.

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

text
Application Request
        │
        ▼
CircuitBreaker.execute()
        │
        ▼
   Circuit State
        │
   ┌────┼─────────┐
   ▼    ▼         ▼
 CLOSED OPEN   HALF_OPEN
   │    │         │
   │    │         └──► Recovery Attempt
   │    │
   │    └────────────► Fallback
   │
   ▼
Protected Service
   │
   ├── Success ──► Continue
   │
   └── Failure ──► Failure Count

This isolates failures from an unhealthy dependency and provides a controlled recovery path instead of continuously sending requests to a failing service.

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.

Help improve the documentation

AxilJS is open source and documentation improvements are welcome.

AxilJS DocumentationMIT License · Built by SyntaxilitY