Function to protect with circuit breaker
Configuration options for the circuit breaker
Protected function that implements circuit breaker logic
const unstableService = () => {
if (Math.random() > 0.7) throw new Error('Service failed');
return 'Success';
};
const protectedService = circuitBreakerSync(unstableService, {
maxFailures: 3, // Trip after 3 consecutive failures
resetAfter: 5000, // Test recovery after 5 seconds
onTripped: (error) => console.log('Circuit breaker tripped:', error.message),
onReset: () => console.log('Circuit breaker reset - service recovered')
});
// Usage
try {
const result = protectedService(); // May throw CircuitBreakerError if open
console.log(result);
} catch (error) {
if (error instanceof CircuitBreakerError) {
console.log('Circuit breaker is open - service unavailable');
} else {
console.log('Service error:', error.message);
}
}
Circuit breaker that protects a function from failing too many times.
Implements the Circuit Breaker design pattern to improve system resilience and fault tolerance by preventing cascading failures in distributed systems. The circuit breaker monitors function calls and automatically "trips" (opens) when failures exceed a threshold, preventing further calls to the failing function until it has time to recover.
The circuit breaker operates in three states:
Key features:
shouldTripOnErrorpredicate