Design Patterns

Circuit Breaker

Understanding the circuit breaker pattern for fault tolerance.

2 min readConcepts · System Design

What is Circuit Breaker?

The Circuit Breaker pattern prevents an application from repeatedly trying to execute an operation that's likely to fail. Like an electrical circuit breaker, it "trips" when failures exceed a threshold.


The Problem

Without circuit breaker, cascading failures occur:

The ProblemFlowchart

Circuit Breaker States

Circuit Breaker StatesState diagram
StateBehavior
ClosedNormal operation, requests pass through
OpenFail immediately, don't call service
Half-OpenAllow limited requests to test recovery

How It Works

How It WorksSequence diagram

Configuration Parameters

ParameterDescriptionTypical Value
Failure thresholdFailures to trip5-10
Success thresholdSuccesses to close3-5
TimeoutTime before half-open30-60 seconds
Sliding windowTime window for counting10-60 seconds

Code Example

class CircuitBreaker {
  constructor(options) {
    this.failureThreshold = options.failureThreshold || 5;
    this.resetTimeout = options.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 is OPEN');
      }
    }

    try {
      const result = await fn();
      this.onSuccess();
      return result;
    } catch (error) {
      this.onFailure();
      throw error;
    }
  }

  onSuccess() {
    this.failures = 0;
    this.state = 'CLOSED';
  }

  onFailure() {
    this.failures++;
    this.lastFailure = Date.now();
    if (this.failures >= this.failureThreshold) {
      this.state = 'OPEN';
    }
  }
}

Libraries

LanguageLibrary
JavaResilience4j, Hystrix
JavaScriptopossum
.NETPolly
Gogobreaker

Interview Tips

  • Explain the three states and transitions
  • Discuss failure thresholds and timeouts
  • Mention fallback strategies
  • Compare with retry pattern (complementary)
  • Give use cases: external API calls, database connections

Finished reading?

Mark it done to track your progress in Concepts.