Circuit Breaker
Stop calling a dependency that keeps failing, fail fast for a cool-down period, then probe carefully before sending full traffic again.
On this page
Problem
When a downstream service slows down or starts failing, every caller keeps sending it requests. Each request holds a thread, a connection or a socket until it times out, so the caller's own resources drain while it waits on something that will not answer. A single unhealthy dependency can take down every service that calls it, and then every service that calls those.
Retries make it worse. A struggling dependency that would recover with less load instead receives the original traffic plus every retry, which keeps it pinned at the point of failure. Users wait for the full timeout on each request only to receive an error that the system could have predicted in microseconds.
Context
Use this pattern when:
- A service makes remote calls (HTTP, gRPC, database, cache) to a dependency that can fail or become slow independently.
- Failures tend to be correlated: once the dependency is unhealthy, the next call is very likely to fail too.
- There is something better to do than wait: return a cached value, a default, a degraded response or a fast error.
- Call volume is high enough that a failure rate is statistically meaningful within a short window.
Solution
Wrap calls to the dependency in a state machine with three states. In Closed, calls pass through and the breaker records their outcomes. When the failure rate over a sliding window crosses a threshold (and the window holds a minimum number of calls), the breaker trips to Open.
In Open, calls are rejected immediately without touching the network, giving the dependency room to recover and giving callers an instant answer they can turn into a fallback. After a break duration, the breaker moves to Half-Open and lets a small number of trial calls through. If they succeed, it closes; if any fails, it opens again for another break period.
The breaker is local to each caller instance and reacts to what that instance observes. It is not a health check and not a load balancer: it decides whether this process should spend resources on a call right now.
How it works, step by step
- 1Closed: forward each call and record success or failure in a sliding window (count-based or time-based).
- 2When failures / total ≥ the failure ratio and total ≥ the minimum throughput, trip to Open and note the time.
- 3Open: reject every call immediately with a dedicated exception (for example
BrokenCircuitException) until the break duration elapses. - 4Half-Open: allow one or a few trial calls; reject the rest as if still open.
- 5If the trial calls succeed, reset the window and close. If one fails, open again, optionally with a longer break.
Implementation
In .NET, Polly v8 (also used by Microsoft.Extensions.Http.Resilience) provides a production-grade breaker. The TypeScript version below is a small hand-rolled breaker that shows the state machine itself.
using Polly;
using Polly.CircuitBreaker;
var pipeline = new ResiliencePipelineBuilder<HttpResponseMessage>()
.AddCircuitBreaker(new CircuitBreakerStrategyOptions<HttpResponseMessage>
{
// Trip when at least half of the calls in a 30 s window fail...
FailureRatio = 0.5,
SamplingDuration = TimeSpan.FromSeconds(30),
// ...but only once the window holds 20 calls.
MinimumThroughput = 20,
BreakDuration = TimeSpan.FromSeconds(15),
ShouldHandle = new PredicateBuilder<HttpResponseMessage>()
.Handle<HttpRequestException>()
.Handle<TimeoutException>()
.HandleResult(r => (int)r.StatusCode >= 500),
OnOpened = args =>
{
Console.WriteLine($"Breaker opened for {args.BreakDuration}");
return ValueTask.CompletedTask;
},
})
.Build();
public sealed class InventoryClient(HttpClient http, ResiliencePipeline<HttpResponseMessage> pipeline)
{
public async Task<int?> GetStockAsync(string sku, CancellationToken ct)
{
try
{
using var response = await pipeline.ExecuteAsync(
async token => await http.GetAsync($"/stock/{sku}", token), ct);
response.EnsureSuccessStatusCode();
return await response.Content.ReadFromJsonAsync<int>(ct);
}
catch (BrokenCircuitException)
{
// Open circuit: answer instantly; the caller shows "stock unknown".
return null;
}
}
}Build the pipeline once and share it (for example through dependency injection). A breaker created per request never accumulates enough history to trip.
type State = 'closed' | 'open' | 'half-open';
export class CircuitOpenError extends Error {}
export class CircuitBreaker {
private state: State = 'closed';
private failures = 0;
private successes = 0;
private openedAt = 0;
private trialInFlight = false;
constructor(
private readonly failureThreshold = 5,
private readonly breakMs = 15_000,
) {}
async call<T>(fn: () => Promise<T>): Promise<T> {
if (this.state === 'open') {
if (Date.now() - this.openedAt < this.breakMs) throw new CircuitOpenError('circuit open');
this.state = 'half-open';
}
if (this.state === 'half-open') {
if (this.trialInFlight) throw new CircuitOpenError('trial call in progress');
this.trialInFlight = true;
}
try {
const result = await fn();
this.onSuccess();
return result;
} catch (error) {
this.onFailure();
throw error;
} finally {
this.trialInFlight = false;
}
}
private onSuccess() {
this.successes++;
if (this.state === 'half-open' || this.successes >= this.failureThreshold) {
this.state = 'closed';
this.failures = 0;
this.successes = 0;
}
}
private onFailure() {
this.failures++;
if (this.state === 'half-open' || this.failures >= this.failureThreshold) {
this.state = 'open';
this.openedAt = Date.now();
this.failures = 0;
this.successes = 0;
}
}
}This version trips on consecutive-ish failures for clarity. Production breakers use a failure ratio over a time window with a minimum throughput, as in the Polly example; in Node, the opossum library implements that.
In production
- Count only failures that indicate dependency health: timeouts, connection errors and 5xx. A 404 or a validation error is a correct answer, not a failure.
- Put the timeout inside the breaker so slow calls count as failures; a breaker that only sees exceptions never notices a dependency that hangs.
- Keep one breaker per dependency (or per endpoint group), not one for the whole service, so a failing search API does not block checkout.
- Emit metrics and logs on every state change. An open circuit is an alert-worthy event and the fastest pointer to the failing dependency.
- Order matters when combining strategies: retry outside the breaker so retries stop once it opens, and a timeout per attempt inside it.
Trade-offs
Benefits
- Callers fail in microseconds instead of waiting for timeouts, which preserves threads, connections and user patience.
- The failing dependency gets breathing room to recover instead of being hammered by full traffic plus retries.
- Stops cascading failures from spreading up the call graph.
- Makes graceful degradation explicit: the open state is a clear trigger for a fallback.
Costs
- Thresholds are hard to tune: too sensitive and the breaker trips on noise; too lenient and it trips after damage is done.
- Each instance learns independently, so with many instances some keep calling while others have opened.
- While open, even requests that would have succeeded are rejected, which lowers availability during partial outages.
- Adds state and a new failure mode (an unexpected open circuit) that operators need to understand.
Alternatives
- Timeouts and retries alone
- Simpler and enough for rare, transient blips; insufficient when a dependency is down for minutes because every call still pays the full timeout.
- Bulkhead
- Caps the concurrency spent on one dependency so it cannot exhaust shared resources. Complements a breaker rather than replacing it.
- Load shedding at the dependency
- The overloaded service rejects excess work itself (for example with 503 and Retry-After), which protects it even from callers without breakers.
- Service mesh outlier detection
- Envoy-style ejection removes failing hosts from a pool. It works per host and outside the code, but cannot provide an application-level fallback.
Anti-patterns
- Counting client errors as failures
- A burst of 400 or 404 responses opens the circuit even though the dependency is healthy, blocking valid traffic.
- One global breaker
- Wrapping every outbound call in a single breaker lets one bad dependency block calls to all the healthy ones.
- Breaker without a fallback or user message
- Failing fast is only useful if something sensible happens next; otherwise the user sees the same error, only sooner.
- Retrying inside the breaker
- Retries placed inside keep hammering the dependency and hide failures from the breaker's statistics.
Related lessons
Interview questions
What are the three states of a circuit breaker and what triggers each transition?
Closed passes calls through and tracks outcomes; it trips to Open when the failure rate over a window exceeds a threshold with enough calls in the window. Open rejects calls immediately; after the break duration it moves to Half-Open. Half-Open allows a few trial calls and closes on success or reopens on failure.
How do circuit breakers and retries interact?
Retries go outside the breaker: each retry attempt passes through it, and once it opens, attempts are rejected instantly so the retry loop stops wasting time. Retries placed inside the breaker hide failures from its statistics and keep load on a struggling dependency.
Why does a breaker need a minimum throughput setting?
With few calls, a ratio is noise: two failures out of three calls is 67% but says little about health. A minimum throughput prevents a quiet period from tripping the breaker on a handful of unlucky requests.
With 50 instances each holding its own breaker, what behaviour do you expect during an outage?
Each instance trips independently once it has seen enough failures, so the fleet converges to open over a few seconds rather than at once. During half-open, up to 50 trial calls probe the dependency, which is usually acceptable; if not, longer or randomised break durations spread the probes out.