Async function to protect with circuit breaker
Configuration options for the circuit breaker
Protected async function that implements circuit breaker logic
const unstableApiCall = async (url: string) => {
const response = await fetch(url);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return response.json();
};
const protectedApiCall = circuitBreaker(unstableApiCall, {
maxFailures: 5,
resetAfter: 10000,
shouldTripOnError: (error) => {
// Only trip on server errors, not client errors
return error.message.includes('HTTP 5') || error.name === 'NetworkError';
},
onTripped: (error, store) => {
console.log(`Circuit breaker tripped after ${store.failures} failures`);
},
onHalfOpen: () => console.log('Testing service recovery...'),
onReset: () => console.log('Service recovered - circuit breaker reset')
});
// Usage
try {
const data = await protectedApiCall('/api/users');
console.log('API response:', data);
} catch (error) {
if (error instanceof CircuitBreakerError) {
console.log('API temporarily unavailable - circuit breaker is open');
// Implement fallback logic here
} else {
console.log('API error:', error.message);
}
}
Async 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 async 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