📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

How does the circuit breaker pattern work? Explain the closed, open and half-open states, failure-ratio thresholds, minimum throughput, sampling and break duration, why it sits inside the retry and outside the per-attempt timeout, what AddStandardResilienceHandler configures by default, and how you choose a fallback.

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.

Mid-Level Theory Intermediate circuit-breaker design-patterns fallback httpclient polly resilience

🎯 Key points

  • Closed: calls flow and outcomes are sampled; open: calls fail fast with BrokenCircuitException for the break duration; half-open: a trial call decides whether to close or re-open
  • Polly v8 opens when FailureRatio (default 0.1) is exceeded within SamplingDuration (default 30 s) and at least MinimumThroughput (default 100) calls were sampled; BreakDuration default 5 s
  • Purpose: stop wasting threads, sockets and time on a dependency that's failing, and give it room to recover
  • Order: retry outside the breaker (each attempt is counted, and an open circuit stops further retries), attempt timeout inside (a hung call counts as a failure)
  • AddStandardResilienceHandler: rate limiter -> total timeout 30 s -> retry -> circuit breaker -> attempt timeout 10 s; SamplingDuration must be at least twice the attempt timeout
  • Low-traffic endpoints may never reach MinimumThroughput, so the breaker never opens; tune it per dependency
  • Breaker state is per process and per pipeline; SelectPipelineByAuthority gives one breaker per host so one bad host doesn't block others
  • Pair with a fallback (cached value, default, degraded feature, 503 with Retry-After) and alert on OnOpened

⏱ 30-second answer

A circuit breaker stops calling a dependency that is clearly failing, so you fail fast instead of wasting threads and sockets on timeouts.

  • Closed: calls flow and outcomes are sampled.
  • Open: when failures pass a threshold, calls are rejected straight away with BrokenCircuitException for the break duration.
  • Half-open: a trial call decides whether to close the circuit or open it again.

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 BrokenCircuitException instead 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. FailureRatio defaults to 0.1, so 10% failures. SamplingDuration is 30 seconds. MinimumThroughput is 100 calls, so it doesn't trip on two failures out of three. BreakDuration is 5 seconds. Those are also the defaults in AddStandardResilienceHandler, 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."


States

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

Polly v8 defaults (also used by the standard handler)

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

Ordering

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

Production example

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.

🔍 What the interviewer is checking

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

  • Explains closed, open and half-open with transitions.
  • Knows failure ratio, minimum throughput, sampling and break duration.
  • Puts the breaker inside retry and outside the attempt timeout, and explains why.
  • Mentions low-traffic and per-host pitfalls.
  • Chooses a fallback and alerts on opening.

Red flags

  • Can't explain half-open.
  • Retry inside the breaker.
  • Treats all exceptions, including 4xx, as failures.
  • No idea what happens to callers while it's open.

📚 Learn in depth

1. The state machine

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
                    +-----------+

2. How Polly v8 samples

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.

3. Placement in the pipeline

Polly runs strategies outer to inner in the order added. The standard handler's order:

  1. Rate limiter (concurrency limiter: 1,000 permits, queue 0): sheds load before doing any work.
  2. Total request timeout (30 s): the overall budget.
  3. Retry (3, exponential, jitter): re-attempts transient failures.
  4. Circuit breaker: counts each attempt; fails fast when open.
  5. Attempt timeout (10 s): bounds each try, turning hangs into countable failures.

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.

4. Scope of a breaker

  • Breaker state lives in memory in one process. Ten pods each have their own breaker and each must trip independently; that's usually fine and avoids a shared point of failure.
  • One pipeline per named 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.
  • Breakers per dependency, never one global breaker.

5. Fallbacks

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.

6. Monitoring

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.

Try it yourself

  1. Put a stub that fails 50% of calls behind a breaker with MinimumThroughput = 10; log state transitions.
  2. Swap retry and breaker order and count how many failed attempts happen before it opens.
  3. Set MinimumThroughput = 100 against a stub called twice a minute and confirm it never opens.
  4. Configure SamplingDuration below 2x the attempt timeout in the standard handler and read the validation error at start-up.
  5. Add a fallback that returns a cached value when BrokenCircuitException is thrown, and test both paths.

💻 Code

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);
}

⚠ Common mistakes

  • Mistake: Putting the circuit breaker outside the retry. Why it is wrong: It counts one outcome per retried call, opens late, and retries continue against a failing dependency. Instead: Retry outside, breaker inside, attempt timeout innermost.
  • Mistake: No per-attempt timeout inside the breaker. Why it is wrong: Hung calls never complete, so they're never counted as failures. Instead: Add an attempt timeout inside the breaker.
  • Mistake: Keeping 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.
  • Mistake: One breaker shared by calls to many hosts or tenants. Why it is wrong: One bad host blocks calls to healthy ones. Instead: SelectPipelineByAuthority() or separate named clients.
  • Mistake: Catching 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.
  • Mistake: Counting 4xx client errors as breaker failures. Why it is wrong: Bad requests from one caller can open the circuit for everyone. Instead: ShouldHandle only transient/server failures.
  • Mistake: No alerting on state changes. Why it is wrong: The breaker silently protects you while a dependency is down for hours. Instead: Log and alert on OnOpened, and chart rejections.
  • Mistake: Creating a new pipeline per request. Why it is wrong: Breaker state resets every call, so it never opens. Instead: Build pipelines once (named client or DI) and reuse them.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate explains why the breaker sits inside the retry Why: Checks diagnosing wrong handler order such as retry outside or inside the breaker
    How to answer

    All three symptoms come from wrapper order and duplication. The outermost decorator or handler runs first and can short-circuit everything inside it.

    • Cached errors: the cache sits outside a fallback that turns exceptions into "empty" results, so it stores the outage for the full TTL. Put the fallback outermost (Fallback → Cache → real search): exceptions pass through the cache uncached, and the empty answer is never stored.
    • Retry storms: retries in two layers multiply attempts, for example a custom handler on top of AddStandardResilienceHandler. The standard pipeline is already rate limiter → total timeout → retry → circuit breaker → attempt timeout.
    • Duplicate logs: a decorator or handler is registered twice, or a custom logging handler sits on top of the built-in HttpClient logging.

    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.

  2. When: Candidate says hung calls must time out to be counted Why: Checks per-attempt and total timeouts around the breaker
    How to answer

    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.

  3. When: Candidate says the breaker saves threads and sockets during outages Why: Checks HttpClient socket behaviour that breakers and timeouts protect
    How to answer

    Two different limits produce similar errors:

    1. Descriptor exhaustion (EMFILE, "Too many open files"): the process hit its ulimit -n. Something is leaking files or sockets.
    2. Ephemeral port exhaustion (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.

  4. When: Candidate mentions limiting in-flight calls as well as breaking the circuit Why: Checks bulkheads as the complement to circuit breakers
    How to answer

    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.

    • Outbound: a concurrency limiter per dependency. Use Polly's AddConcurrencyLimiter, or the standard handler's limiter (1,000 permits, queue 0 by default). Give each dependency a separate named HttpClient with MaxConnectionsPerServer.
    • Inbound: ASP.NET Core AddRateLimiter concurrency policies per endpoint group.
    • Messaging: separate queues and consumers with their own 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.

🛠 Real-world problems: how you handle them

Circuit breaker never opened for a low-traffic address API
Situation
Checkout at [company] called a third-party address-validation API at about [2–3] calls a minute per pod, through an `HttpClient` with `AddStandardResilienceHandler` defaults. [8] pods in Azure Kubernetes Service.
Signals
During a [45-minute] provider outage, checkout p95 rose from [600 ms] to [31 s]; Application Insights showed address-validation dependency calls timing out at 10 s three times per request; no `OnOpened` log events; conversion dropped by [x]%.
Investigation
Application Insights showed every request making four attempts (one plus three retries) until the 30-second total timeout. Reviewed the breaker options: `MinimumThroughput` was 100 in a 30-second window, but each pod saw about [1–2] calls in that window, so the breaker could never open. Polly's resilience metrics confirmed zero breaker state changes.
Resolution
Immediate: a feature flag skipped address validation and flagged orders for manual review. Real fix: a dedicated breaker configuration for that client (MinimumThroughput 5, 1-minute sampling, 30 s break), attempt timeout 2 s and total 5 s, retries reduced to 1, and a fallback that skips validation when the circuit is open.
Prevention
A review of breaker thresholds against each dependency's call rate (documented per client); alerts on `OnOpened` and on dependency p95; a chaos test in staging that blackholes the address API and asserts checkout p95 stays under [1.5 s].

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.

↩ Usually asked after

More in Enterprise Patterns

Last updated 18 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me