Advertisement
Advanced ASP.NET Core, Error Handling

How would you implement a circuit breaker pattern to prevent cascading failures when a downstream dependency is consistently failing?

Short answer

A circuit breaker (implementable via Polly's CircuitBreakerPolicy) tracks consecutive failures against a downstream dependency, and once a failure threshold is exceeded, 'opens' the circuit -- immediately failing subsequent calls without even attempting them for a cooldown…

Save ASP.NET Core mock interview
Advertisement
AModel answer
A circuit breaker (implementable via Polly's CircuitBreakerPolicy) tracks consecutive failures against a downstream dependency, and once a failure threshold is exceeded, 'opens' the circuit -- immediately failing subsequent calls without even attempting them for a cooldown period, preventing the calling application from wasting resources on calls almost certain to fail and giving the struggling downstream dependency breathing room to recover, rather than the calling service continuing to hammer it during an outage.
var circuitBreaker = Policy
    .Handle<HttpRequestException>()
    .CircuitBreakerAsync(exceptionsAllowedBeforeBreaking: 5, durationOfBreak: TimeSpan.FromSeconds(30));

try {
    await circuitBreaker.ExecuteAsync(() => CallDownstreamServiceAsync());
} catch (BrokenCircuitException) {
    // circuit is open -- fail fast without even attempting the call
    return Results.Problem("Service temporarily unavailable", statusCode: 503);
}
Real-world example
An order-processing service wraps its calls to a flaky inventory-checking dependency in a circuit breaker, so after 5 consecutive failures it stops attempting new calls entirely for 30 seconds, immediately returning a 503 to callers instead of piling up slow, doomed-to-fail requests during the dependency's outage.
Likely follow-ups
  • How does a circuit breaker's half-open state work to test if the dependency has recovered?
  • How would you combine circuit breaking with retry logic without them conflicting?
Related topics