Lesson 11 of 14
Circuit Breaker
Circuit Breaker
When a downstream service is failing, continuously retrying just makes things worse — it wastes resources and prevents recovery. The Circuit Breaker pattern stops sending requests to a failing service and lets it recover.
The Three States
success too many failures timeout elapsed
CLOSED ──────────────────────► OPEN ──────────► HALF-OPEN
◄─────────────────────────────────────────────────
success │ failure
▼
OPEN
- CLOSED — normal operation. Requests pass through. Track failures.
- OPEN — service is down. Reject all requests immediately. Start a timeout.
- HALF-OPEN — tentatively try one request. If it succeeds, go CLOSED. If it fails, go back OPEN.
class CircuitBreaker {
constructor(threshold, timeout) {
this.threshold = threshold; // failures before opening
this.timeout = timeout; // ms before trying again
this.failures = 0;
this.state = "CLOSED";
this.openedAt = null;
}
call(fn) {
if (this.state === "OPEN") {
if (Date.now() - this.openedAt >= this.timeout) {
this.state = "HALF-OPEN";
} else {
throw new Error("Circuit OPEN");
}
}
try {
const result = fn();
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.openedAt = Date.now();
}
}
}
Used By
- Netflix Hystrix — the original circuit breaker library for microservices.
- Resilience4j — modern Java circuit breaker.
- AWS SDK — built-in retries with exponential backoff and jitter.
- Envoy/Istio — service mesh with circuit breaking at the proxy level.
Your Task
Implement a CircuitBreaker class. For testing purposes, use a callsAttempted counter instead of real time — the circuit opens after threshold failures and allows a retry after timeout additional calls.
JavaScript loading...
Loading...
Click "Run" to execute your code.