Circuit breaker pattern: closed/open/half-open state machine, Polly v8 CircuitBreakerStrategyOptions (FailureRatio 0.1, MinimumThroughput 100, SamplingDuration 30 s, BreakDuration 5 s, ShouldHandle, OnOpened/OnHalfOpened), BrokenCircuitException, ordering in AddStandardResilienceHandler (rate limiter, total timeout, retry, breaker, attempt timeout) and its validation rules, per-instance vs per-authority breakers (SelectPipelineByAuthority), low-traffic pitfalls, fallbacks and monitoring.
A circuit breaker stops calling a dependency that is clearly failing, so you fail fast instead of wasting threads and sockets on timeouts.
BrokenCircuitException for the break duration.In Polly v8 it opens when the failure ratio (default 10%) is exceeded over a 30 s sampling window with at least 100 calls, and it breaks for 5 s. AddStandardResilienceHandler puts it inside the retry (each attempt counts, and an open circuit stops retries) and outside the 10 s attempt timeout (a hung call counts as a failure).
Pair it with a fallback and alert when it opens. The trade-off is protection and fast failure against rejecting some calls that would have succeeded.
"A circuit breaker is a state machine wrapped around calls to a dependency. In the closed state everything passes through and the breaker samples outcomes. When failures cross a threshold, it opens: for the break duration every call fails immediately with a
BrokenCircuitExceptioninstead of waiting 10 seconds for a timeout. That protects my service, since threads and sockets aren't tied up on a dependency that's down, and it protects the dependency, because it gets breathing room to recover. After the break, it goes half-open and lets a trial call through: success closes it, failure opens it again.In Polly v8 the thresholds are explicit.
FailureRatiodefaults to 0.1, so 10% failures.SamplingDurationis 30 seconds.MinimumThroughputis 100 calls, so it doesn't trip on two failures out of three.BreakDurationis 5 seconds. Those are also the defaults inAddStandardResilienceHandler, which chains a rate limiter, a 30-second total timeout, retry, the circuit breaker and a 10-second attempt timeout, from outside in. The order is the important part. The breaker sits inside the retry, so every individual attempt is counted, and once it opens, the retry's next attempt fails fast instead of piling on. The attempt timeout sits inside the breaker, so a hung call becomes a timeout the breaker counts as a failure. The handler even validates that the sampling duration is at least twice the attempt timeout. If you flip the order and put retry inside the breaker, the breaker only sees one outcome per three attempts and opens far too late.The mistake I see is leaving the defaults on a low-traffic dependency. At two calls a minute you never reach 100 calls in 30 seconds, so the breaker never opens. For example, at [company] [an address-validation API went down, and our breaker never tripped because of the minimum throughput], so [every checkout waited for the full timeout]. I [tuned MinimumThroughput and the sampling window for that client and added a fallback that skipped validation], and [checkout p95 during the next outage stayed at [x] ms]. A breaker is only as good as its thresholds for that dependency's traffic, and only useful if you've decided what to do when it's open."
| State | Behaviour | Transition |
|---|---|---|
| Closed | Calls pass; outcomes sampled | Failure ratio > threshold with ≥ minimum throughput → Open |
| Open | Calls rejected immediately (BrokenCircuitException) |
After BreakDuration → Half-open |
| Half-open | A trial call is allowed | Success → Closed; failure → Open |
| Isolated (manual) | Forced open via CircuitBreakerManualControl |
Manual close |
| Option | Default | Tune when |
|---|---|---|
FailureRatio |
0.1 | Dependency has a normal background error rate |
MinimumThroughput |
100 | Low-traffic dependencies (lower it) |
SamplingDuration |
30 s | Must be ≥ 2x attempt timeout in the standard handler |
BreakDuration |
5 s | Slow-recovering dependencies (longer, or BreakDurationGenerator) |
ShouldHandle |
Exceptions (Polly); 5xx/408/429/timeouts (HTTP options) | Domain-specific failures |
| Order (outer → inner) | Effect |
|---|---|
| Retry → Breaker → Attempt timeout | Each attempt counted; open circuit stops retries; hung calls count (recommended) |
| Breaker → Retry | Breaker sees one result per retried call; opens late; retries continue during outages |
| Timeout outside breaker only | Hung calls never recorded as failures |
With a breaker and a cached-price fallback on a pricing service client, a 12-minute pricing outage caused 0.3% of product page requests to show slightly stale prices, instead of the previous incident's pattern of 10-second timeouts and thread-pool growth that took the catalogue down. The OnOpened alert paged on-call within 30 seconds.
Checks whether the candidate understands the breaker's states, thresholds and ordering, can apply the .NET 10 defaults sensibly and plans a fallback.
Green flags
Red flags
Michael Nygard popularised the pattern in Release It! (2007), borrowing the electrical analogy: trip to protect the system, reset after a cool-down.
failure ratio > threshold
(and >= MinimumThroughput)
+--------+ ----------------------> +------+
| Closed | | Open | -- calls rejected: BrokenCircuitException
+--------+ <---------+ +------+
^ | | BreakDuration elapsed
| trial succeeds | v
| +-----------+ <--------+
+---------- | Half-open | trial fails -> Open
+-----------+
Polly v8's advanced circuit breaker tracks outcomes in a rolling window (SamplingDuration, divided into buckets). It opens when, within the window, at least MinimumThroughput actions were executed and the proportion handled as failures by ShouldHandle is at or above FailureRatio. In half-open, a single trial execution is let through; other calls are still rejected until it completes. BreakDurationGenerator lets you grow the break on repeated trips. OnOpened, OnClosed and OnHalfOpened callbacks feed logs and alerts; CircuitBreakerStateProvider exposes the current state for health checks, and CircuitBreakerManualControl lets you isolate or close the circuit by hand.
Polly runs strategies outer to inner in the order added. The standard handler's order:
The standard options validate that TotalRequestTimeout exceeds AttemptTimeout and that the breaker's SamplingDuration is at least double the attempt timeout, so a single slow attempt can't fall outside the window.
HttpClient by default. If that client calls many hosts (or tenants), one bad host trips the breaker for all; SelectPipelineByAuthority() creates a pipeline (and breaker) per authority.When the circuit is open, choose deliberately:
| Fallback | Example |
|---|---|
| Cached/stale data | Last known price from HybridCache |
| Default value | Empty recommendations list |
| Degraded feature | Skip address validation, flag for review |
| Queue for later | Accept the order, process payment asynchronously |
| Fail fast to the caller | 503 with Retry-After |
Polly's AddFallback strategy (outermost) can implement this, or catch BrokenCircuitException in the client.
Alert on OnOpened; chart state changes and rejected calls (Polly's resilience metrics). A breaker that opens and closes repeatedly ("flapping") indicates thresholds too sensitive or a dependency hovering at the edge.
MinimumThroughput = 10; log state transitions.MinimumThroughput = 100 against a stub called twice a minute and confirm it never opens.SamplingDuration below 2x the attempt timeout in the standard handler and read the validation error at start-up.BrokenCircuitException is thrown, and test both paths.Tuning the standard handler's breaker per dependency, a per-host breaker, and a Polly v8 pipeline with a fallback around a breaker.
using Microsoft.Extensions.Http.Resilience;
using Polly;
using Polly.CircuitBreaker;
using Polly.Fallback;
var builder = WebApplication.CreateBuilder(args);
// High-traffic dependency: defaults are close; alert when the circuit opens
builder.Services.AddHttpClient<PricingClient>(c => c.BaseAddress = new Uri("https://pricing.internal"))
.AddStandardResilienceHandler(o =>
{
o.AttemptTimeout.Timeout = TimeSpan.FromSeconds(2);
o.CircuitBreaker.SamplingDuration = TimeSpan.FromSeconds(30); // >= 2x attempt timeout (validated)
o.CircuitBreaker.FailureRatio = 0.2; // tolerate its normal background errors
o.CircuitBreaker.BreakDuration = TimeSpan.FromSeconds(15);
o.CircuitBreaker.OnOpened = args =>
{
// log at Warning; an alert rule on this event pages on-call
Console.WriteLine($"Pricing circuit opened for {args.BreakDuration}");
return ValueTask.CompletedTask;
};
});
// Low-traffic dependency: lower MinimumThroughput or it will never open
builder.Services.AddHttpClient<AddressValidationClient>(c => c.BaseAddress = new Uri("https://address.example.com"))
.AddStandardResilienceHandler(o =>
{
o.CircuitBreaker.MinimumThroughput = 5;
o.CircuitBreaker.SamplingDuration = TimeSpan.FromMinutes(1);
o.CircuitBreaker.BreakDuration = TimeSpan.FromSeconds(30);
});
// One client calling many hosts (e.g. per-tenant URLs): one breaker per authority
builder.Services.AddHttpClient<TenantWebhookClient>()
.AddStandardResilienceHandler()
.SelectPipelineByAuthority();
builder.Services.AddHybridCache();
using Microsoft.Extensions.Caching.Hybrid;
using Polly.CircuitBreaker;
public sealed record Price(string Sku, decimal Amount, bool IsStale);
// Fallback: when the circuit is open (or the call fails), serve the last known price
public sealed class PricingClient(HttpClient http, HybridCache cache, ILogger<PricingClient> logger)
{
public async Task<Price> GetPriceAsync(string sku, CancellationToken ct)
{
try
{
var amount = await http.GetFromJsonAsync<decimal>($"/prices/{sku}", ct);
await cache.SetAsync($"price:{sku}", amount, cancellationToken: ct); // refresh the fallback copy
return new Price(sku, amount, IsStale: false);
}
catch (BrokenCircuitException)
{
logger.LogWarning("Pricing circuit open; serving cached price for {Sku}", sku);
var cached = await cache.GetOrCreateAsync<decimal>($"price:{sku}",
_ => throw new InvalidOperationException("No cached price available."), cancellationToken: ct);
return new Price(sku, cached, IsStale: true); // UI can show 'price may have changed'
}
}
}
public sealed class AddressValidationClient(HttpClient http)
{
public async Task<bool?> ValidateAsync(string address, CancellationToken ct)
{
try { return await http.GetFromJsonAsync<bool>($"/validate?q={Uri.EscapeDataString(address)}", ct); }
catch (BrokenCircuitException) { return null; } // degrade: skip validation, flag the order for review
}
}
public sealed class TenantWebhookClient(HttpClient http)
{
public Task<HttpResponseMessage> SendAsync(Uri url, HttpContent body, CancellationToken ct) => http.PostAsync(url, body, ct);
}
MinimumThroughput = 100 for a low-traffic dependency. Why it is wrong: The threshold is never reached, so the breaker never opens. Instead: Tune thresholds to each dependency's traffic.SelectPipelineByAuthority() or separate named clients.BrokenCircuitException and returning a generic 500. Why it is wrong: It wastes the fast-fail signal and gives users no useful behaviour. Instead: Choose a fallback: cached data, degraded feature, or 503 with Retry-After.ShouldHandle only transient/server failures.OnOpened, and chart rejections.The breaker itself is easy; the decisions around it are the work: thresholds that match each dependency's traffic and error profile, the order relative to retry and timeouts, the scope (per client, per host), and a fallback the product owner has agreed to. A breaker without a fallback just converts slow failures into fast ones, which is better, but not the whole answer.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Standard handler defaults | High-traffic internal HTTP dependencies | May not suit low traffic | Calls at a few per minute |
| Tuned breaker per client | Dependencies with distinct traffic/error profiles | Configuration to maintain | Uniform internal services |
| Per-authority breakers | One client, many hosts/tenants | More pipelines in memory | Single host |
| Breaker + fallback | User-facing features with a degraded mode | Fallback design and data freshness | No sensible fallback exists (fail fast instead) |
| Manual isolation | Planned maintenance, known outages | Operational process | Routine operation |
I measure time-to-open after a dependency fails, rejected calls while open, flapping frequency, and how often the fallback is served, and review thresholds after every incident.
All three symptoms come from wrapper order and duplication. The outermost decorator or handler runs first and can short-circuit everything inside it.
AddStandardResilienceHandler. The standard pipeline is already rate limiter → total timeout → retry → circuit breaker → attempt timeout.To diagnose, list the ServiceDescriptors, walk the resolved chain, inspect the handler order, and read span nesting in traces. Then compose the chain in one place and add tests that assert its order and attempt counts.
A timeout should cancel the work, not just stop waiting. Use a CancellationTokenSource with CancelAfter (linked to the caller's token) and pass it down. Task.WaitAsync(timeout) only stops waiting. For HTTP, HttpClient.Timeout is a single total timeout (100 seconds by default) that throws TaskCanceledException with an inner TimeoutException; in production I prefer AddStandardResilienceHandler, which sets attempt and total timeouts plus retries. In ASP.NET Core 8+, the request timeouts middleware cancels RequestAborted after a configured time. Timeouts must be layered: each inner timeout shorter than the outer one.
Two different limits produce similar errors:
EMFILE, "Too many open files"): the process hit its ulimit -n. Something is leaking files or sockets.EADDRNOTAVAIL, "Cannot assign requested address"): too many outbound connections to the same destination, usually closed sockets stuck in TIME_WAIT for 60 s.The classic .NET cause is new HttpClient() per request. Fix it with a shared HttpClient using SocketsHttpHandler { PooledConnectionLifetime = ... }, or IHttpClientFactory. Diagnose with ls /proc/<pid>/fd | wc -l, lsof -p, ss -s and ss -tan state time-wait.
A bulkhead partitions shared resources so one failing dependency can only exhaust its own share, like the watertight compartments in a ship. In .NET the shared resources are thread-pool threads, sockets, database connection-pool slots, memory and request slots.
AddConcurrencyLimiter, or the standard handler's limiter (1,000 permits, queue 0 by default). Give each dependency a separate named HttpClient with MaxConnectionsPerServer.AddRateLimiter concurrency policies per endpoint group.MaxConcurrentCalls.A bulkhead limits concurrent work. Rate limiting limits requests per time window. Size limits with Little's Law (concurrency = rate x latency) plus headroom, and pair them with timeouts. The trade-off is containment against rejecting work when a compartment is full.
How to tell it (STAR)
**S:** At [company], a [45-minute] outage of our address-validation provider pushed checkout p95 to [31 seconds]. **T:** As the checkout owner, I had to work out why our circuit breaker didn't protect us and fix it. **A:** Metrics showed the breaker never changed state: with the default minimum throughput of 100 calls in 30 seconds, and only one or two calls per pod in that window, it couldn't open. I added a feature flag to skip validation immediately, then gave that client its own thresholds, shorter timeouts, one retry, and a fallback that flags orders for review, and added a chaos test. **R:** In the provider's next outage the breaker opened within [a minute], checkout p95 stayed at [~700 ms], and [n] orders were flagged instead of lost.
Last updated 18 Nov 2026.