patternMajorpending
Circuit breaker pattern — prevent cascade failures
Viewed 0 times
circuit breakerfail fastcascade failureresilienceopossumhalf-open
Problem
When a downstream service fails, continuing to send requests wastes resources, increases latency, and can cascade the failure. Retrying a dead service makes outages worse.
Solution
Implement a circuit breaker with three states: CLOSED (normal, requests pass through), OPEN (failures exceeded threshold, requests fail fast without calling the service), HALF-OPEN (after cooldown, allow one test request to check if service recovered). Track failure count and switch states based on thresholds. Libraries: opossum (Node.js), resilience4j (Java), polly (.NET).
Why
Circuit breakers give failing services time to recover by stopping the flood of requests. Fail-fast behavior improves response time during outages and prevents resource exhaustion.
Code Snippets
Simple circuit breaker implementation
class CircuitBreaker {
constructor(fn, { threshold = 5, cooldown = 30000 } = {}) {
this.fn = fn;
this.threshold = threshold;
this.cooldown = cooldown;
this.failures = 0;
this.state = 'CLOSED'; // CLOSED | OPEN | HALF_OPEN
this.nextAttempt = 0;
}
async call(...args) {
if (this.state === 'OPEN') {
if (Date.now() < this.nextAttempt) {
throw new Error('Circuit is OPEN — failing fast');
}
this.state = 'HALF_OPEN';
}
try {
const result = await this.fn(...args);
this.onSuccess();
return result;
} catch (err) {
this.onFailure();
throw err;
}
}
onSuccess() {
this.failures = 0;
this.state = 'CLOSED';
}
onFailure() {
this.failures++;
if (this.failures >= this.threshold) {
this.state = 'OPEN';
this.nextAttempt = Date.now() + this.cooldown;
}
}
}Revisions (0)
No revisions yet.