CodexBloom - Programming Q&A Platform

Trouble Implementing Circuit Breaker Pattern in .NET 6 with Polly - Not scenarios as Expected

👀 Views: 1 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-06
polly circuit-breaker dotnet-6 C#

I'm trying to implement the Circuit Breaker pattern using Polly in my .NET 6 application, but I'm working with an scenario where the circuit doesn't seem to open as expected after multiple failures. Here's a simplified version of my code: ```csharp var circuitBreakerPolicy = Policy .Handle<Exception>() .CircuitBreaker(3, TimeSpan.FromSeconds(30)); var result = await circuitBreakerPolicy.ExecuteAsync(async () => { // Simulating an API call that may unexpected result return await httpClient.GetAsync("https://myapi.com/data"); }); ``` In this example, I assume that after three consecutive exceptions, the circuit breaker should open and prevent further calls for 30 seconds. However, I still see multiple exceptions being thrown, and my API continues to be called beyond the threshold I've set. I've also wrapped the `ExecuteAsync` call in a try-catch block to log any exceptions, and I can see that failures are occurring, but the circuit doesn't seem to be opening. I verified that I am indeed getting exceptions thrown, so it's puzzling why the circuit breaker isn't functioning as expected. I've tried debugging this by logging the state of the circuit breaker, but it appears to remain closed even after consecutive failures. I also checked the Polly documentation and examples, but I couldn't find anything that points to a misconfiguration on my part. Is there something I'm missing, or is there a common pitfall with Polly's Circuit Breaker policy that I should be aware of? What would be the recommended way to handle this?