Implementing Circuit Breaker in ASP.NET Core with Microsoft Resilience
Learn how to safeguard your services by handling transient failures with resilience.
Modern web applications often rely on multiple external services. But what happens when one of those services starts failing? Continuous failures can cascade through your system, slowing down or even crashing your application. This is where the Circuit Breaker pattern comes into play.
Circuit breakers protect your application from repeated failures by temporarily blocking calls to a failing service and allowing it to recover. In ASP.NET Core, you can implement this pattern seamlessly using Polly and the Microsoft.Extensions.Http.Resilience package.
What is a Circuit Breaker?
The Circuit Breaker pattern is inspired by electrical circuit breakers: it prevents an application from repeatedly trying to execute an operation that is likely to fail.
Closed state: Requests flow normally.
Open state: Requests fail immediately without hitting the failing service.
Half-open state: After a defined interval, a few requests are allowed to test if the service has recovered.
In short, a circuit breaker “breaks” the circuit when failures exceed a threshold and prevents your application from overloading a struggling service.
Why Use a Circuit Breaker?
Using a circuit breaker in your applications provides multiple benefits:
Improved Resilience: Prevents cascading failures when downstream services are unavailable or slow.
Fail Fast: Instead of waiting for timeouts on failing services, requests fail immediately when the circuit is open.
System Stability: Protects your resources (threads, memory) from being overwhelmed by repeated failures.
Graceful Degradation: Gives your application time to recover or fallback to alternative flows.
Operational Insights: Monitoring circuit states helps detect failing services early.
In this article, we’ll explore how to implement the Cache-Aside pattern in .NET Core 9 using HybridCache, which supports both in-memory and Redis caching.
Setting Up a Circuit Breaker in ASP.NET Core
First, add the required NuGet packages for caching:
dotnet add package Microsoft.Extensions.Http.ResilienceIn ASP.NET Core, you can implement the Circuit Breaker pattern easily using Microsoft.Extensions.Http.Resilience. Here’s a sample configuration:
// Add HttpClient with Circuit Breaker
builder.Services.AddHttpClient("ExternalApiClient")
.AddResilienceHandler("circuit-breaker-pipeline", builder =>
{
builder.AddCircuitBreaker(new HttpCircuitBreakerStrategyOptions
{
FailureRatio = 0.1, // 10% failure ratio triggers the circuit
MinimumThroughput = 10, // Minimum number of requests before evaluation
SamplingDuration = TimeSpan.FromSeconds(30),
BreakDuration = TimeSpan.FromSeconds(15) // Open circuit for 15 seconds
});
});Using the Circuit Breaker in Controllers
After configuring the HttpClient, you can use it in your controller:
namespace CircuitBreakerApi.Controllers
{
using Microsoft.AspNetCore.Mvc;
using System.Net.Http;
using System.Threading.Tasks;
[ApiController]
[Route("[controller]")]
public class ExternalApiController : ControllerBase
{
private readonly IHttpClientFactory _httpClientFactory;
public ExternalApiController(IHttpClientFactory httpClientFactory)
{
_httpClientFactory = httpClientFactory;
}
[HttpGet("data")]
public async Task<IActionResult> GetExternalData()
{
var client = _httpClientFactory.CreateClient("ExternalApiClient");
try
{
var response = await client.GetAsync("https://jsonplaceholder.typicode.com/todos/1");
if (response.IsSuccessStatusCode)
{
var data = await response.Content.ReadAsStringAsync();
return Ok(data);
}
else
{
return StatusCode((int)response.StatusCode, "External API failed");
}
}
catch (Exception ex)
{
// Circuit breaker will throw if the circuit is open
return StatusCode(503, $"Request failed: {ex.Message}");
}
}
}
}How It Works
Monitoring: The circuit breaker monitors requests and tracks failures.
Breaking: If failures exceed the threshold, the circuit opens, preventing further requests to the failing service.
Recovery: After a break duration, the circuit enters half-open, allowing a few requests to check if the service has recovered.
Closing: If the service responds successfully, the circuit closes, and normal traffic resumes.
Benefits Recap
Better user experience: Avoid long waits and timeouts for end users.
Resource protection: Prevent threads, memory, and CPU from being exhausted.
Faster failure detection: Immediate awareness when downstream services fail.
Resilient systems: Helps maintain overall application stability.
Engaging Thought:
Have you ever noticed your app slowing down because an external API was failing? Imagine how a circuit breaker could have stopped that cascade—how would your system behave differently under failure?
👉 Full working code available at:
🔗https://sourcecode.kanaiyakatarmal.com/CircuitBreaker
I hope you found this guide helpful and informative.
Thanks for reading!
If you enjoyed this article, feel free to share it and follow me for more practical, developer-friendly content like this.

