Stop calling a dependency that is failing, fail fast with a fallback while it recovers, and check periodically whether it's back.
A circuit breaker sits between your service and a dependency and watches how calls go. While they succeed, it does nothing. When too many fail, it «opens» and rejects calls immediately, without touching the network, for a cool-down period. Then it lets a handful through to test the water and closes again only if they succeed. It doesn't fix the dependency: it stops you from piling up waiting requests until you fall over too.
The problem
A situation where the obvious design starts to hurt.
Your online shop's checkout calls a carrier's rates API to show delivery options and prices. It normally answers in 120 ms. On a Friday evening, during a sale, the carrier starts answering in 25 seconds, and some calls never answer at all.
Each checkout instance can hold about 200 requests in flight. At 300 checkouts a minute, in under a minute every slot is taken by a request waiting on the carrier. New requests queue up, the load balancer's health checks start timing out, instances get restarted, and checkout —payment included— is down. The payment provider is perfectly healthy; a non-essential call has taken out the essential one.
Retrying makes it worse: every failed call becomes two or three, aimed at a provider that is already drowning. You need something that notices the carrier is unhealthy and stops sending it traffic, so checkout can carry on without it.
The solution
What the pattern proposes.
Wrap every call to the carrier in a breaker with three states. Closed: calls go through and the breaker records the outcome of the last 20. If at least 10 have been recorded and half or more failed —timeouts, connection errors, 5xx— it trips to open. Open: every call fails instantly, without a network round trip, and checkout falls back to a flat-rate shipping table. After 15 seconds the breaker goes half-open and lets three trial calls through; if all three succeed it closes, if any fails it opens again for another 15 seconds.
Two things make it work. First, a tight timeout on the call (2 seconds here): without it, a hanging request never counts as a failure and the breaker never opens. Second, a fallback that makes sense to the business: the shopper sees «standard delivery, 4,95 €» instead of the exact quote, and the order still goes through. While the carrier is down, checkout's latency goes back to normal and the carrier gets the quiet it needs to recover.
An everyday analogy
The same idea, outside software.
Think of a shop assistant who phones the warehouse to check stock. If the warehouse line rings out three times in a row, a sensible assistant doesn't keep every customer waiting while they redial: for the next quarter of an hour they say «we'll confirm by email» and serve the next person. Every so often they try the warehouse again, and when it picks up, they go back to checking live.
Structure
The pieces and how they relate.
Participants
- Checkout API (caller)
- Needs shipping options to build the order. Decides what to do when the breaker refuses: here, use flat rates.
- Circuit breaker
- Wraps calls to one dependency. Keeps the recent outcomes, the state and the cool-down timer, and decides whether a call may go out.
- Carrier rates API (dependency)
- The third-party service that may slow down or fail. It never knows the breaker exists.
- Flat-rate table (fallback)
- A degraded but valid answer the caller can use without the dependency: static prices, a cached value, a default.
Pseudocode
The solution to the scenario, language-neutral.
state = CLOSED, recent = last 20 results
call(request):
if state is OPEN:
if cool-down (15 s) not over: fail fast // no network call at all
state = HALF_OPEN // time to probe
if state is HALF_OPEN and 3 probes already in flight: fail fast
try:
result = send(request) with a 2 s timeout
record(success)
return result
on timeout, connection error or 5xx:
record(failure)
rethrow
record(outcome):
if state is HALF_OPEN:
failure -> state = OPEN, restart cool-down
3rd success in a row -> state = CLOSED, forget history
return
add outcome to recent
if at least 10 results and failure rate >= 50%:
state = OPEN, restart cool-down
shippingOptions(cart):
try: return call(carrier.rates(cart))
on any failure: return flatRates(cart) // degrade, don't break checkoutThe code
The same solution in TypeScript, Python and PHP.
type State = "closed" | "open" | "half-open";
export class CircuitOpenError extends Error {}
export class CircuitBreaker {
private state: State = "closed";
private results: boolean[] = []; // last calls, true = failed
private openedAt = 0;
private inFlight = 0; // trial calls while half-open
private successes = 0;
constructor(
private readonly opts = { window: 20, failureRate: 0.5, minCalls: 10, openMs: 15_000, probes: 3 },
private readonly now = () => Date.now(),
) {}
async call<T>(fn: () => Promise<T>): Promise<T> {
if (this.state === "open") {
if (this.now() - this.openedAt < this.opts.openMs) throw new CircuitOpenError("circuit open");
this.state = "half-open"; // cool-down over: let a few calls through
this.inFlight = 0;
this.successes = 0;
}
if (this.state === "half-open") {
if (this.inFlight >= this.opts.probes) throw new CircuitOpenError("probing");
this.inFlight++;
}
try {
const value = await fn();
this.record(false);
return value;
} catch (err) {
this.record(true);
throw err;
}
}
private record(failed: boolean) {
if (this.state === "half-open") {
if (failed) this.trip();
else if (++this.successes >= this.opts.probes) this.reset();
return;
}
this.results.push(failed);
if (this.results.length > this.opts.window) this.results.shift();
const failures = this.results.filter(Boolean).length;
if (this.results.length >= this.opts.minCalls && failures / this.results.length >= this.opts.failureRate)
this.trip();
}
private trip() {
this.state = "open";
this.openedAt = this.now();
this.results = [];
}
private reset() {
this.state = "closed";
this.results = [];
}
}
// One breaker per dependency, shared by every request of this instance.
const carrierBreaker = new CircuitBreaker();
export async function shippingOptions(cart: Cart): Promise<ShippingOption[]> {
try {
return await carrierBreaker.call(() => fetchCarrierRates(cart, { timeoutMs: 2_000 }));
} catch {
// Breaker open, timeout or carrier error: checkout goes on with flat rates.
return flatRates(cart);
}
}import time
from collections import deque
from collections.abc import Awaitable, Callable
from typing import TypeVar
T = TypeVar("T")
class CircuitOpenError(Exception):
pass
class CircuitBreaker:
def __init__(self, window=20, failure_rate=0.5, min_calls=10, open_seconds=15.0, probes=3, clock=time.monotonic):
self.failure_rate = failure_rate
self.min_calls = min_calls
self.open_seconds = open_seconds
self.probes = probes
self.clock = clock
self.state = "closed"
self.results: deque[bool] = deque(maxlen=window) # last calls, True = failed
self.opened_at = 0.0
self.in_flight = 0 # trial calls while half-open
self.successes = 0
async def call(self, fn: Callable[[], Awaitable[T]]) -> T:
if self.state == "open":
if self.clock() - self.opened_at < self.open_seconds:
raise CircuitOpenError("circuit open")
self.state = "half-open" # cool-down over: let a few calls through
self.in_flight = 0
self.successes = 0
if self.state == "half-open":
if self.in_flight >= self.probes:
raise CircuitOpenError("probing")
self.in_flight += 1
try:
value = await fn()
except Exception:
self._record(failed=True)
raise
self._record(failed=False)
return value
def _record(self, failed: bool) -> None:
if self.state == "half-open":
if failed:
self._trip()
else:
self.successes += 1
if self.successes >= self.probes:
self.state = "closed"
self.results.clear()
return
self.results.append(failed)
failures = sum(self.results)
if len(self.results) >= self.min_calls and failures / len(self.results) >= self.failure_rate:
self._trip()
def _trip(self) -> None:
self.state = "open"
self.opened_at = self.clock()
self.results.clear()
# One breaker per dependency, shared by every request of this process.
carrier_breaker = CircuitBreaker()
async def shipping_options(cart: Cart) -> list[ShippingOption]:
try:
return await carrier_breaker.call(lambda: fetch_carrier_rates(cart, timeout=2.0))
except Exception:
# Breaker open, timeout or carrier error: checkout goes on with flat rates.
return flat_rates(cart)<?php
final class CircuitOpenException extends RuntimeException {}
/**
* PHP usually serves each request in a fresh process: in production keep this state in APCu or Redis so that
* every worker shares it. It lives in memory here to keep the mechanism readable.
*/
final class CircuitBreaker
{
private string $state = 'closed';
/** @var bool[] last calls, true = failed */
private array $results = [];
private float $openedAt = 0.0;
private int $inFlight = 0; // trial calls while half-open
private int $successes = 0;
public function __construct(
private int $window = 20,
private float $failureRate = 0.5,
private int $minCalls = 10,
private float $openSeconds = 15.0,
private int $probes = 3,
) {}
public function call(callable $fn): mixed
{
if ($this->state === 'open') {
if (microtime(true) - $this->openedAt < $this->openSeconds) {
throw new CircuitOpenException('circuit open');
}
$this->state = 'half-open'; // cool-down over: let a few calls through
$this->inFlight = 0;
$this->successes = 0;
}
if ($this->state === 'half-open') {
if ($this->inFlight >= $this->probes) {
throw new CircuitOpenException('probing');
}
$this->inFlight++;
}
try {
$value = $fn();
} catch (Throwable $e) {
$this->record(true);
throw $e;
}
$this->record(false);
return $value;
}
private function record(bool $failed): void
{
if ($this->state === 'half-open') {
if ($failed) {
$this->trip();
} elseif (++$this->successes >= $this->probes) {
$this->state = 'closed';
$this->results = [];
}
return;
}
$this->results[] = $failed;
if (count($this->results) > $this->window) {
array_shift($this->results);
}
$failures = count(array_filter($this->results));
if (count($this->results) >= $this->minCalls && $failures / count($this->results) >= $this->failureRate) {
$this->trip();
}
}
private function trip(): void
{
$this->state = 'open';
$this->openedAt = microtime(true);
$this->results = [];
}
}
function shippingOptions(array $cart, CircuitBreaker $carrierBreaker): array
{
try {
return $carrierBreaker->call(fn () => fetchCarrierRates($cart, timeoutSeconds: 2.0));
} catch (Throwable) {
// Breaker open, timeout or carrier error: checkout goes on with flat rates.
return flatRates($cart);
}
}When to use it
Situations where it pays off.
A synchronous call to a dependency you don't control sits on a request path that matters.
That's exactly where a slow dependency eats your capacity: the breaker caps the damage to the duration of the timeout, and only until it opens.
You have a reasonable fallback, even a partial one.
Failing fast is only half the value. Answering with cached data, a default or a «try later» keeps the user's flow alive.
Your retries could turn a struggling dependency into a dead one.
An open breaker stops retries at the source, so the dependency gets the breathing room it needs to recover.
Many instances call the same dependency and you want them to back off together.
Each instance's breaker reacts to the same symptoms, so traffic to the dependency drops quickly across the fleet.
How to implement it
Steps to introduce it in existing code.
Put a timeout on the call first. A breaker can't count a failure that never ends.
Decide what counts as a failure: timeouts, connection errors and 5xx do; 4xx and validation errors don't —they're your bug, not the dependency's.
Pick a window and thresholds from real traffic: a minimum number of calls (so 2 failures out of 2 at 3 a.m. don't trip it), a failure rate and a cool-down.
Create one breaker per dependency, or per endpoint if their health differs, and share it across requests in the process.
Write the fallback with the product team and make it visible: a flag in the response, a metric, a log line per state change.
Test it: inject latency and errors in staging and check that the breaker opens, checkout stays fast and it closes again when the dependency recovers.
Pros and cons
What you gain and what you pay.
Pros
- Caps the damage a slow dependency can do to your capacity and latency.
- Gives the failing dependency room to recover instead of hammering it.
- Makes failures explicit and fast, so callers can degrade gracefully.
- State changes are a clear, alertable signal that a dependency is in trouble.
Cons
- Thresholds are guesses until tuned with real traffic; wrong ones either never trip or trip on noise.
- While open, some requests that would have succeeded are rejected too.
- Per-instance breakers see only their own traffic and may disagree with each other.
- Adds a moving part that has to be tested, monitored and understood by whoever is on call.
Trade-offs
Decisions you'll have to make, each with its price.
Failure-rate threshold vs consecutive-failure count
You gainA rate over a window (50 % of the last 20) ignores isolated blips and works at any traffic level.
You payNeeds a minimum number of calls, and at low traffic it reacts slowly. Consecutive failures are simpler but trip on short bursts.
Short vs long cool-down
You gainShort (5-15 s) recovers quickly when the outage was brief.
You payProbes a struggling dependency more often. Long cool-downs, or ones that grow after each failed probe, are gentler but keep the fallback on for longer.
One breaker per host vs per endpoint
You gainPer endpoint isolates a broken
/ratesfrom a healthy/labels.You payMore breakers to configure and watch, and less data per breaker to decide with.
Local state per instance vs shared state
You gainLocal is simple, fast and has no new dependency.
You payInstances learn separately; shared state (Redis) makes them agree but adds a dependency on the critical path.
How it fails
What goes wrong in production and how to prevent it.
The breaker never opens because calls hang for 30 seconds before failing
What to doSet a timeout below your own latency budget (2 s here). The breaker only reacts to outcomes it gets to see.
It flaps between open and closed every few seconds
What to doRequire a minimum number of calls in the window, several successful probes before closing, and a cool-down that grows when probes fail.
Client errors trip it: a bad deploy on your side sends invalid requests and the breaker blames the carrier
What to doCount only timeouts, connection errors and 5xx as failures. Alert separately on 4xx.
The fallback is silent and wrong for hours
What to doMark degraded responses, emit a metric per state change and alert when a breaker stays open longer than a few minutes.
In a system design interview
When to bring it up and how to explain it.
Bring it up when your design has a synchronous call to something you don't own —payments, a carrier, another team's service— and the interviewer asks «what happens if that's slow?». Mention it together with timeouts and a fallback, never alone.
What you could say
The rates call is on the checkout path but it isn't essential, so I'd protect it three ways. A 2-second timeout so a slow carrier can't hold our requests. A circuit breaker per carrier: if half of the last 20 calls fail, it opens and we stop calling for 15 seconds, then let a few probes through. And a fallback: flat-rate shipping, flagged in the response so we can measure how often it happens. That way a carrier outage costs us precise quotes for a while, not checkout. I'd alert when a breaker stays open more than five minutes, and I wouldn't retry on top of an open breaker.
Likely follow-ups
Where does the breaker's state live if you have 30 instances?
In each instance by default: they all see the same symptoms and trip within seconds of each other. I'd share it in Redis only if probing from 30 instances at once were a problem for the dependency.
How do retries and the breaker fit together?
Retries go inside the breaker, few and with jittered backoff, so every attempt counts towards its statistics. Once it's open, nothing retries.
What if there's no sensible fallback, like payments?
Then fail fast with a clear error and let the user try again later; that's still better than holding the request for 30 seconds and taking down everything else.
Relations with other guides
Patterns it's often confused or combined with.
- Timeouts and Deadline Propagation
The prerequisite: without a deadline per call, a hanging request never becomes a failure the breaker can count.
- Retry with Backoff: Exponential Delays, Jitter and Retry Budgets
Retries handle brief, isolated failures; the breaker stops retries when failure is no longer brief.
- Bulkhead: Isolate Resources So One Failure Stays Contained
A bulkhead caps how many resources one dependency can use; the breaker decides whether to call it at all. They work well together.
- State Pattern: Explicit State Machines Without the Switch Statements
A breaker is a small state machine: closed, open and half-open, each with its own rule for letting calls through.
Common questions
Short answers to the usual doubts.
Do I need to write my own breaker?
Rarely. Most languages have a solid library (opossum in Node, resilience4j in Java, pybreaker in Python) and service meshes offer outlier detection. Write one in an interview or to understand it; in production, configure a library and spend the time on thresholds and fallbacks.
Is a breaker the same as a rate limiter?
No. A rate limiter caps how much traffic you send or accept, whatever the outcome. A breaker reacts to outcomes: it lets everything through while the dependency is healthy and nothing while it isn't.
Should the breaker go on the client or the server side?
On the caller, because it protects the caller's capacity. The dependency can protect itself with rate limiting and load shedding.
Now, practise it
Put it to work straight away.
Tests, exercises and problems that use what you've just read.
- Resilience and high concurrencyTake the test
- A slow or failing external providerSolve the exercise
- Retries with exponential backoffSolve the exercise