Course contentsShow
← Software Engineering
Lesson 1096 of 1,93333. Error Handling and ResilienceFree lesson

The Circuit Breaker Pattern

Preventing cascading failures by stopping calls to failing services and allowing time for recovery before retrying.

The Circuit Breaker Pattern

What you'll learn: How to protect your system from cascading failures by automatically stopping calls to broken services until they recover.

The Problem: Cascading Failures

When a downstream service starts failing (slow responses, errors, timeouts), continuing to call it wastes resources and can cause your entire system to grind to a halt. Retries can make things worse by hammering an already struggling service. You need a way to "break the circuit" and give the failing service breathing room to recover.

How Circuit Breakers Work

The Circuit Breaker pattern wraps remote calls in a state machine with three states:

Closed (Normal Operation)

Requests flow through normally. The circuit breaker tracks failures. If failure count or rate crosses a threshold, it trips to Open.

Open (Blocking Calls)

All requests fail immediately without even attempting the call (fail-fast). This prevents wasting resources and gives the downstream service time to recover. After a timeout period, move to Half-Open.

Half-Open (Testing Recovery)

Allow a limited number of test requests through. If they succeed, assume recovery and return to Closed. If they fail, return to Open and wait longer.

Real-World Analogy

Think of your home's electrical circuit breaker. When a short circuit occurs, the breaker trips (opens) to prevent damage. You don't flip it back immediately—you investigate, fix the problem, then cautiously test by flipping it back on. If sparks fly again, it trips again. Same principle here.

Working with Other Patterns

Circuit breakers complement timeouts and retries. Timeouts prevent hanging forever. Retries handle transient failures. Circuit breakers handle sustained failures by stopping the retry storm and allowing graceful degradation.

Key Takeaway: The Circuit Breaker pattern prevents cascading failures by monitoring service health, failing fast when problems persist, and automatically testing for recovery—protecting both your system and the struggling downstream service.