A circuit breaker in software is a resilience pattern that wraps calls to a remote dependency, counts failures, and stops sending requests once failures cross a threshold, returning an immediate error or fallback instead. In software architecture, the circuit breaker pattern protects distributed systems from cascading failures: a slow or broken service is isolated for a cooldown period, then probed carefully before normal traffic resumes.
The name borrows from the electrical device that opens a circuit under overload. The software version does not protect wires but threads, connections and latency budgets, which are exhausted quickly when callers keep waiting on a dependency that cannot answer.
How a circuit breaker moves between states
A circuit breaker is a small state machine placed in front of an outbound call, usually inside a client library, a service mesh proxy or an API gateway. It observes the outcome of each call and decides, before the next call, whether the request may proceed at all.
The classic design has three states. Transitions are driven by measured failure rates and timers rather than by manual intervention, which is what makes the pattern effective during incidents that unfold in seconds.
| State | What happens to calls | Transition trigger |
|---|---|---|
| Closed | Calls pass through; results are recorded | Failure rate exceeds threshold, so it opens |
| Open | Calls fail fast without reaching the dependency | Cooldown timer expires, so it becomes half-open |
| Half-open | A limited number of trial calls pass through | Trials succeed, so it closes; any failure reopens it |
The half-open state is the subtle part. Letting all traffic through the moment the timer expires would hit a recovering service with a full load spike, often knocking it over again. A small number of probe requests tests recovery while the remaining callers still receive fast failures.
Key parameters and how to tune them
The behavior of a breaker depends almost entirely on its configuration values, and poor defaults are the most common reason the pattern disappoints in production. The table summarizes the parameters found in most mature implementations, such as Resilience4j, Polly and the circuit breaking features of Envoy and Istio.
| Parameter | Typical range | Effect of a higher value |
|---|---|---|
| Failure rate threshold | 25 to 60 percent | Trips later; tolerates more errors |
| Sliding window size | 10 to 100 calls or 10 to 60 s | Smoother decisions; slower reaction |
| Minimum number of calls | 5 to 20 | Prevents tripping on tiny samples |
| Open-state duration | 5 to 60 s | Longer rest for the dependency; longer outage for callers |
| Half-open trial calls | 1 to 10 | Faster confidence; more load on recovery |
| Slow-call threshold | Near the p99 latency target | Treats fewer slow responses as failures |
Two refinements matter in practice. Modern breakers count slow calls as failures, because a dependency that answers in eight seconds harms callers as much as one that refuses connections. Many also apply exponential backoff to the open-state duration, lengthening the rest period after repeated failed probes.
Teams should also decide which errors count. A client error such as HTTP 400 or 404 says nothing about the health of the dependency, so it should normally be excluded, while timeouts, connection resets and HTTP 503 responses should be included.
Circuit breaker compared with related resilience patterns
A circuit breaker is one tool in a layered resilience strategy and works best alongside timeouts, retries and bulkheads. Each pattern addresses a different failure mode, and confusing them leads to designs that look robust on diagrams but fail under real load.
| Pattern | Problem it solves | Relationship to the breaker |
|---|---|---|
| Timeout | A single call waiting too long | Supplies the failures the breaker counts |
| Retry with backoff | Brief, transient errors | Must sit inside the breaker so retries stop when open |
| Bulkhead | One dependency consuming all threads | Limits concurrency; the breaker limits attempts |
| Rate limiter | Callers sending too much traffic | Protects the provider; the breaker protects the caller |
| Fallback | What to return when a call fails | Often triggered by an open breaker |
The ordering of retries and breakers is a frequent source of trouble. Retries placed outside the breaker multiply traffic during an outage, which is exactly the retry storm the breaker exists to prevent. In a microservices or service-oriented architecture, a sidecar pattern proxy can apply these policies uniformly so that each service team does not reimplement them.
Designing fallbacks and choosing where breakers live
An open breaker is only useful if the caller has a sensible fallback. Failing fast without a plan simply converts a slow error into a quick one; the real value appears when the application degrades gracefully.
| Situation | Recommended fallback | Reason |
|---|---|---|
| Product recommendations unavailable | Show a static bestseller list | Feature is optional; page still works |
| Pricing service unavailable | Return a clear error, block checkout | Stale prices create financial risk |
| User profile service slow | Serve cached data with a staleness flag | Slightly old data is acceptable |
| Notification service down | Queue messages for later delivery | Work is deferrable, not lost |
Placement is the other design choice. Client-side breakers in application code give each caller its own view of dependency health and allow fallbacks tied to business logic. Infrastructure breakers in a mesh or gateway are easier to govern centrally but usually can only reject requests, not substitute meaningful responses. Many teams combine both, documenting the choice in an architecture decision record.
- Use one breaker per dependency, or per endpoint when endpoints fail independently.
- Expose breaker state as metrics and alerts so operators see trips immediately.
- Test trips deliberately with fault injection before relying on them in an incident.
Limitations and common mistakes
A circuit breaker does not fix the failing dependency; it only limits the damage. It also introduces its own failure modes, and misconfigured breakers can cause outages in otherwise healthy systems.
| Symptom | Likely cause | Fix |
|---|---|---|
| Breaker trips on a handful of errors | Minimum call count too low | Raise the sample size before evaluation |
| Outage spreads despite the breaker | Timeouts longer than the caller budget | Set aggressive timeouts first |
| Healthy service marked as failing | Client errors counted as failures | Exclude 4xx responses from failure counts |
| Recovered service crashes again | Too many half-open trial calls | Reduce probes and add backoff |
| Instances disagree on health | Per-instance state with low traffic | Accept it or share health signals |
The last point deserves attention. Breaker state is usually local to each process, so in a cluster of many instances with sparse traffic, some instances trip while others keep calling. Shared state is possible but adds coordination cost and a new dependency, which is why most teams accept the inconsistency.
In simple terms
Imagine calling a shop that never picks up. After a few failed attempts, a sensible person stops dialing for a while and tells customers the shop is unavailable, then tries once more later. A circuit breaker gives software the same common sense.
When a service it depends on keeps failing or answering too slowly, the program stops asking for a short time and responds right away with an error or a backup answer. This keeps one broken part from dragging the whole system down, and it gives the broken part room to recover.
A practical example
An online retailer runs a checkout service that calls a separate fraud-scoring service. During a holiday sale, the fraud service slows to response times of over ten seconds because its database is overloaded. Without protection, checkout threads pile up waiting, the connection pool runs dry within a minute, and even customers paying by gift card cannot complete orders.
The team configures a breaker with a 50 percent failure threshold over a 20-call window, a two-second slow-call limit and a 30-second open duration. The fallback approves orders under a modest value and holds larger ones for manual review.
At the next slowdown, the breaker opens within seconds. Checkout stays responsive, low-value orders continue, and the fraud service recovers once traffic eases. Half-open probes succeed after about two minutes and normal scoring resumes, turning a potential site-wide outage into a brief, contained degradation.