Node.js
Circuit breaker
Learn the circuit breaker pattern.
Circuit breaker
A circuit breaker is a pattern that stops calls when the called service keeps failing. Three states exist: closed (normal), open (calls blocked) and half-open (probe). This prevents a failing service from dragging the whole system down.
Example: if the order service fails 5 times in a row, the breaker goes open and stops calling for a while. When the wait ends it moves to half-open and tries one call; if it succeeds, it returns to closed. This isolates the failing service and lets the rest of the system keep working. Without a circuit breaker, a slow service blocks all callers and causes a cascading failure. Three states: closed → open → half-open → closed.
Three states
closed: normal state, calls go through. open: calls are blocked and fail fast. half-open: when the wait ends, one probe call is made; if it succeeds, the breaker returns to closed, otherwise it stays open.
Example: if (this.state === "open") throw new Error("Breaker open");. In the open state no call is made at all; the calling code gets an error. In the half-open state only one call is made and the state is updated based on its result. This mechanism gives a failing service a rest period instead of continuously retrying and stressing the system. The breaker's failure threshold and timeout are configurable; typical values are 5 failures and 30 seconds.
Exercise Write a CircuitBreaker skeleton
Define a CircuitBreaker class. In the constructor assign this.failures = 0 and this.state = "closed". In a recordFailure method do this.failures++ and add if (this.failures >= 5) this.state = "open". Print "Breaker ready" with console.log.
Show example solution
class CircuitBreaker {
constructor() {
this.failures = 0;
this.state = "closed";
}
recordFailure() {
this.failures++;
if (this.failures >= 5) this.state = "open";
}
}
console.log("Breaker ready");
Test yourself
-
Complete the breaker state
if (failures >= 5) this.state = "____";
Show answer
if (failures >= 5) this.state = "open";
-
Match each state to its meaning
- closed
- Normal, calls go through
- open
- Calls are blocked
- half-open
- One probe is made
- threshold
- Failure limit
-
Why use a circuit breaker?
if (failures >= threshold) open()
- Isolates a failing service to protect the system
- Returns faster responses
- Compresses database backups
- Deletes log files
Show answer
Isolates a failing service to protect the system — A breaker isolates a failing service.
Next lesson: Summary - Microservices