Implement circuit breaker pattern
✓Works with OpenClaudeYou are a resilience engineer implementing fault-tolerance patterns. The user wants to implement a circuit breaker pattern that prevents cascading failures by failing fast when a service is down.
What to check first
- Verify you have a dependency for circuit breaker functionality:
npm listshould showopossumor similar installed - Confirm your service endpoint URLs and expected timeout thresholds before implementing
- Check if you need to handle specific HTTP status codes as failures (e.g., 500, 503) vs. actual network errors
Steps
- Install the circuit breaker library:
npm install opossum(or useaxios-retrywith circuit breaker wrapper) - Import the CircuitBreaker class and define your protected function that calls the external service
- Create a new CircuitBreaker instance wrapping the function, setting
threshold(number of failures to trip),timeout(how long to wait before retry), andresetTimeout(duration in OPEN state before attempting half-open) - Attach event listeners to the circuit breaker instance for
open,halfOpen, andcloseevents to log state transitions - Wrap your service calls with the circuit breaker's
.fire()method instead of calling the function directly - Implement a fallback response handler that catches
CircuitBreakerOpenErrorand returns degraded/cached data - Test the circuit breaker by simulating failures and verifying it opens after threshold is exceeded
- Monitor metrics: count failures per window, track state changes, and alert when circuit remains open beyond expected recovery time
Code
const CircuitBreaker = require('opossum');
const axios = require('axios');
// The function you want to protect
async function callExternalService(userId) {
const response = await axios.get(
`https://api.external.com/users/${userId}`,
{ timeout: 5000 }
);
return response.data;
}
// Configure circuit breaker options
const options = {
timeout: 3000, // Operation timeout in ms
errorThresholdPercentage: 50, // Trip if 50% of requests fail
resetTimeout: 30000, // Wait 30s before attempting recovery
volumeThreshold: 10, // Need 10 requests in window before considering failure rate
rollingCountTimeout: 60000 // 60s rolling window
};
// Create circuit breaker
const breaker = new CircuitBreaker(callExternalService, options);
// Handle circuit breaker events
breaker.on('open', () => {
console.warn('Circuit breaker OPENED - service unavailable');
});
breaker.on('halfOpen', () => {
console.info('Circuit breaker HALF_OPEN - testing recovery');
});
breaker.on('close', () => {
console.info('Circuit breaker CLOSED - service recovered');
});
breaker.fallback(() => {
console.log('Fallback: returning cached data');
Note: this example was truncated in the source. See the GitHub repo for the latest full version.
Common Pitfalls
- Treating this skill as a one-shot solution — most workflows need iteration and verification
- Skipping the verification steps — you don't know it worked until you measure
- Applying this skill without understanding the underlying problem — read the related docs first
When NOT to Use This Skill
- When a simpler manual approach would take less than 10 minutes
- On critical production systems without testing in staging first
- When you don't have permission or authorization to make these changes
How to Verify It Worked
- Run the verification steps documented above
- Compare the output against your expected baseline
- Check logs for any warnings or errors — silent failures are the worst kind
Production Considerations
- Test in staging before deploying to production
- Have a rollback plan — every change should be reversible
- Monitor the affected systems for at least 24 hours after the change
Related Networking Skills
Other Claude Code skills in the same category — free to download.
HTTP Client
Create configured HTTP client with interceptors
Retry Logic
Implement retry logic with exponential backoff
Request Queue
Queue and batch HTTP requests
Proxy Setup
Set up reverse proxy configuration
SSL Setup
Configure SSL/TLS certificates
DNS Setup
Configure DNS records
Load Balancer
Set up load balancing configuration
Nginx Reverse Proxy
Configure Nginx as reverse proxy with upstream servers
Want a Networking skill personalized to YOUR project?
This is a generic skill that works for everyone. Our AI can generate one tailored to your exact tech stack, naming conventions, folder structure, and coding patterns — with 3x more detail.