Below is a clear, interview-ready and practical explanation of the Circuit Breaker pattern in .NET Core, along with real-time examples and code using Polly (the standard library for resilience in .NET).
✅ Circuit Breaker Pattern in .NET Core
What it is
Circuit Breaker is a resilience pattern used to prevent your system from repeatedly calling a failing external service (API/database/message broker).
It protects the system from cascading failures.
๐ States of Circuit Breaker
| State | Meaning |
|---|---|
| Closed | Everything works normally (calls allowed). |
| Open | Calls blocked immediately because external service is failing. |
| Half-Open | Allows limited trial calls to see if the service recovered. |
⭐ Why we use it
-
To avoid hitting a failing service over & over
-
To prevent resource consumption (threads, CPU, DB connections)
-
To improve latency by quickly failing requests
-
To give time for the external system to recover
๐ฆ Circuit Breaker in .NET Core using Polly
Install package:
dotnet add package Polly.Extensions.Http
✔️ Simple Circuit Breaker Example
services.AddHttpClient("StockApiClient")
.AddTransientHttpErrorPolicy(policy =>
policy.CircuitBreakerAsync(
handledEventsAllowedBeforeBreaking: 3, // After 3 failures
durationOfBreak: TimeSpan.FromSeconds(30), // Keep circuit open for 30 sec
onBreak: (result, ts) =>
{
Console.WriteLine("Circuit opened!");
},
onReset: () =>
{
Console.WriteLine("Circuit closed!");
},
onHalfOpen: () =>
{
Console.WriteLine("Circuit half-open: trying test call.");
}
));
Meaning:
-
If API fails 3 times → Circuit goes OPEN
-
For the next 30 seconds → all calls fail immediately
-
After 30 sec → Circuit goes HALF-OPEN
-
If next call succeeds → RESET (Closed)
-
If fails → OPEN again
✔️ Circuit Breaker + Retry (Best Practice)
services.AddHttpClient("PaymentService")
.AddPolicyHandler(
HttpPolicyExtensions
.HandleTransientHttpError()
.RetryAsync(3) // retry 3 times
)
.AddPolicyHandler(
HttpPolicyExtensions
.HandleTransientHttpError()
.CircuitBreakerAsync(5, TimeSpan.FromSeconds(20))
);
Retry handles intermittent failures.
Circuit Breaker handles persistent failures.
✔️ Using Circuit Breaker in Controller
public class StockController : ControllerBase
{
private readonly IHttpClientFactory _factory;
public StockController(IHttpClientFactory factory) => _factory = factory;
[HttpGet("price/{symbol}")]
public async Task<IActionResult> GetStockPrice(string symbol)
{
var client = _factory.CreateClient("StockApiClient");
var response = await client.GetAsync($"/api/stock/{symbol}");
if (!response.IsSuccessStatusCode)
return StatusCode((int)response.StatusCode, "External service failed");
var data = await response.Content.ReadAsStringAsync();
return Ok(data);
}
}
๐ฏ Real-Time Scenarios Where You Use Circuit Breaker
1. Payment Gateways
If Razorpay/Stripe API is failing, don’t call them continuously.
Circuit stops the calls.
2. Microservices Architecture
If Order Service relies on Inventory Service and Inventory is down →
stop hammering it; return fallback immediately.
3. Slow database or cache
If Redis/Azure SQL is timing out → circuit opens → API returns quick response instead of long delays.
4. Third-party APIs (SMS, Email, Notification)
Avoid getting throttled or blocked by calling continuously.
๐ How You Answer in Interviews (30-second answer)
“Circuit Breaker is a resilience pattern that prevents the system from making calls to a failing external service.
In .NET Core, we implement it using Polly.
After a defined number of failures, the circuit moves to Open state and blocks all calls for a specified time.
This prevents cascading failures and improves performance.
I generally combine Retry + Circuit Breaker in HttpClient when calling microservices or external systems.”
No comments:
Post a Comment