Circuit Breaker Pattern
Prevent cascading failures and improve resilience with MoroJS's built-in circuit breaker pattern. Automatically detect and handle service failures gracefully.
On this page
What is a Circuit Breaker?
A circuit breaker prevents cascading failures by automatically detecting and handling service failures. When a service fails repeatedly, the circuit opens to prevent further requests.
Circuit Breaker States
CLOSED
Requests pass through normally. Failures are tracked.
OPEN
Requests fail immediately. Prevents cascade failures.
HALF_OPEN
Testing recovery. Limited requests allowed.
Quick Example
Basic Circuit Breaker Usage
typescript
How It Works
State Transitions
The circuit breaker transitions between three states based on the health of the protected service:
- CLOSED → OPEN: When failure count reaches the threshold, the circuit opens to prevent further requests
- OPEN → HALF_OPEN: After the reset timeout expires, the circuit enters half-open state to test recovery
- HALF_OPEN → CLOSED: If test requests succeed, the circuit closes and normal operation resumes
- HALF_OPEN → OPEN: If test requests fail, the circuit reopens and the reset timeout starts again
Circuit Breaker Configuration
typescript
Usage Examples
Built-in Circuit Breakers for Jobs
typescript
Manual Circuit Breaker with Fallback
typescript
Multiple Circuit Breakers
typescript
Monitoring and Events
State Change Events
typescript
Health Check Endpoint
typescript
Configuration Examples
Different Breaker Configurations
typescript
Dynamic Adaptive Circuit Breaker
typescript
Best Practices
Set Appropriate Thresholds
Base thresholds on service characteristics. Stable services should have lower thresholds, while flaky services can be more tolerant.
Provide Fallbacks
Always have a fallback strategy when the circuit is open. Use cached data, secondary services, or default responses.
Monitor State Changes
Alert on circuit breaker state changes. Open circuits indicate service degradation that needs immediate attention.
Separate Breakers
Use different circuit breakers for independent services. Don't let one service failure affect others.