CodeBlanks Logo Icon CodeBlanks

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.

Practice 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.

Starter code

index.js
// Define the CircuitBreaker class
// write here

// Print "Breaker ready"
// write here

Sample solution

index.js
class CircuitBreaker {
  constructor() {
    this.failures = 0;
    this.state = "closed";
  }
  recordFailure() {
    this.failures++;
    if (this.failures >= 5) this.state = "open";
  }
}
console.log("Breaker ready");

Expected output

Breaker ready

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the breaker state

Question
if (failures >= 5) this.state = "____";
Answer
if (failures >= 5) this.state = "open";

Explanation: After 5 failures the breaker goes open.

2 Match each state to its meaning

Term Meaning
closed Normal, calls go through
open Calls are blocked
half-open One probe is made
threshold Failure limit

3 Why use a circuit breaker?

index.js
if (failures >= threshold) open()
  • Isolates a failing service to protect the system Correct answer
  • Returns faster responses
  • Compresses database backups
  • Deletes log files

Explanation: A breaker isolates a failing service.

All lessons in Advanced