Definition
Imagine your application calls a payment service to process transactions. One day, that payment service starts having problems - it’s responding incredibly slowly or not at all. Without any protection, your application would keep trying to call it, waiting and waiting for responses that never come. Meanwhile, your users are stuck watching loading spinners, your servers are tied up with hanging requests, and eventually your entire system grinds to a halt because of one misbehaving service.
A Circuit Breaker is a design pattern that prevents this catastrophe. It works exactly like the electrical circuit breaker in your home. When too much current flows through an electrical circuit (like when there’s a short circuit), the breaker “trips” and cuts the power to prevent a fire. Similarly, when a software circuit breaker detects that a service is failing too often, it “trips” and stops trying to call that service for a while.
The pattern has three states: Closed (normal operation - requests flow through), Open (the circuit is tripped - requests fail immediately without even trying), and Half-Open (testing if the service has recovered). When a service starts failing repeatedly, the circuit breaker opens, immediately returning errors to callers instead of making them wait. Periodically, it allows a test request through to see if things have improved. If the test succeeds, the circuit closes and normal operation resumes. If not, it stays open and tries again later.
Example
Netflix Streaming: When Netflix’s recommendation service goes down, you can still watch movies - you just might not see personalized suggestions. Their circuit breaker detects the failure and shows you generic popular titles instead of waiting forever for recommendations that won’t come.
E-commerce Checkout: Your shopping cart uses a circuit breaker for the inventory service. If the inventory system is slow, the circuit opens and checkout proceeds with a “we’ll confirm stock shortly” message rather than making customers wait 30 seconds per item.
Payment Processing: A food delivery app’s circuit breaker for payment processing. After 5 failed payment attempts in a minute, the circuit opens. New orders show “Payment system temporarily unavailable, please try again in a few minutes” instantly rather than timing out after 30 seconds each.
Third-Party API Calls: Your weather app uses a circuit breaker for the external weather API. When that API is overloaded, the circuit opens and your app shows cached weather data from an hour ago rather than crashing or hanging indefinitely.
Database Connections: When your database is overwhelmed, a circuit breaker prevents your application from adding even more load. Instead of thousands of requests piling up waiting for database connections, they fail fast and return errors, giving the database time to recover.
Analogy
The Electrical Panel: The most direct analogy is your home’s electrical panel. If you plug in too many appliances and draw too much current, the breaker trips before your wires overheat and start a fire. You lose power to that circuit temporarily, but your house doesn’t burn down. You can reset the breaker once you’ve unplugged some things. Software circuit breakers work the same way - they cut the connection before the problem spreads.
The Restaurant Kitchen: Imagine a restaurant where orders go to the kitchen. If the kitchen gets overwhelmed and orders take an hour to prepare, a smart maître d’ would stop accepting new orders temporarily. “Kitchen’s backed up - let’s pause seating for 20 minutes.” This gives the kitchen time to catch up, and customers aren’t left waiting forever for food that might never come. The circuit breaker is that maître d'.
The Hospital Triage: When an emergency room is overwhelmed, they don’t try to treat every patient immediately - they’d collapse under the load. Instead, they triage: critical cases get immediate attention, others are told to wait or go elsewhere. A circuit breaker does similar triage for your system - when a service is overwhelmed, it redirects traffic rather than making everyone suffer.
The Immune System: Your body’s immune system can recognize when fighting an infection is doing more harm than good (like autoimmune responses). Sometimes it needs to back off and try a different approach. A circuit breaker gives your system a similar ability - recognize when a strategy isn’t working and try something else instead of making things worse.
Code Example
class CircuitBreaker {
private state: 'CLOSED' | 'OPEN' | 'HALF_OPEN' = 'CLOSED';
private failureCount = 0;
async call<T>(fn: () => Promise<T>): Promise<T> {
if (this.state === 'OPEN') {
throw new Error('Circuit breaker is OPEN');
}
try {
const result = await fn();
this.onSuccess();
return result;
} catch (error) {
this.onFailure();
throw error;
}
}
}