Architecture Intermediate
Circuit Breaker Pattern — Protection Against Cascading Failures¶
Circuit BreakerResiliencePatterns 3 min read
Implementing the Circuit Breaker pattern for resilient microservices. States, configuration, and practical examples.
The Cascading Failure Problem¶
When service B stops responding, service A waits for a timeout. Requests pile up and failure spreads through the entire system. Circuit Breaker fails fast instead of waiting.
Three States¶
- Closed — normal operation, counts error rate
- Open — requests are immediately rejected
- Half-Open — allows test requests through
class CircuitBreaker {
constructor(opts = {}) {
this.threshold = opts.failureThreshold || 5;
this.resetTimeout = opts.resetTimeout || 30000;
this.state = 'CLOSED';
this.failures = 0;
this.lastFailure = null;
}
async call(fn) {
if (this.state === 'OPEN') {
if (Date.now() - this.lastFailure > this.resetTimeout)
this.state = 'HALF_OPEN';
else throw new Error('Circuit OPEN');
}
try {
const result = await fn();
this.failures = 0; this.state = 'CLOSED';
return result;
} catch (e) {
this.failures++;
this.lastFailure = Date.now();
if (this.failures >= this.threshold) this.state = 'OPEN';
throw e;
}
}
}
Libraries¶
- Node.js: opossum
- Java: Resilience4j
- Python: pybreaker
- .NET: Polly
Summary¶
Circuit Breaker is a must-have in distributed architecture. Always combine with fallback logic and monitoring.
Need Help with Implementation?¶
Our team has experience designing and implementing modern architectures. We’re happy to help.