Circuit breaker · software

Also known as: circuit breaker pattern

On this page 7

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.

StateWhat happens to callsTransition trigger
ClosedCalls pass through; results are recordedFailure rate exceeds threshold, so it opens
OpenCalls fail fast without reaching the dependencyCooldown timer expires, so it becomes half-open
Half-openA limited number of trial calls pass throughTrials succeed, so it closes; any failure reopens it
The three states of a circuit breaker

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.

ParameterTypical rangeEffect of a higher value
Failure rate threshold25 to 60 percentTrips later; tolerates more errors
Sliding window size10 to 100 calls or 10 to 60 sSmoother decisions; slower reaction
Minimum number of calls5 to 20Prevents tripping on tiny samples
Open-state duration5 to 60 sLonger rest for the dependency; longer outage for callers
Half-open trial calls1 to 10Faster confidence; more load on recovery
Slow-call thresholdNear the p99 latency targetTreats fewer slow responses as failures
Common circuit breaker parameters

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.

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.

PatternProblem it solvesRelationship to the breaker
TimeoutA single call waiting too longSupplies the failures the breaker counts
Retry with backoffBrief, transient errorsMust sit inside the breaker so retries stop when open
BulkheadOne dependency consuming all threadsLimits concurrency; the breaker limits attempts
Rate limiterCallers sending too much trafficProtects the provider; the breaker protects the caller
FallbackWhat to return when a call failsOften triggered by an open breaker
How the circuit breaker differs from neighboring patterns

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.

SituationRecommended fallbackReason
Product recommendations unavailableShow a static bestseller listFeature is optional; page still works
Pricing service unavailableReturn a clear error, block checkoutStale prices create financial risk
User profile service slowServe cached data with a staleness flagSlightly old data is acceptable
Notification service downQueue messages for later deliveryWork is deferrable, not lost
Fallback strategies by situation

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.

SymptomLikely causeFix
Breaker trips on a handful of errorsMinimum call count too lowRaise the sample size before evaluation
Outage spreads despite the breakerTimeouts longer than the caller budgetSet aggressive timeouts first
Healthy service marked as failingClient errors counted as failuresExclude 4xx responses from failure counts
Recovered service crashes againToo many half-open trial callsReduce probes and add backoff
Instances disagree on healthPer-instance state with low trafficAccept it or share health signals
Typical circuit breaker problems

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.