What is Circuit Breaker in Asp.net Core
Tags: webdev, programming, aspdotnet, opensource
Published: 2023-05-22 16:36:42

A circuit breaker is a design pattern used in ASP.NET Core to enhance the robustness and fault-tolerance of applications that interface with external services. It is a system that keeps track of the responsiveness and performance of an external service and stops cascade failures if either of those things happens.

On the idea of an electrical circuit breaker, the circuit breaker pattern is founded. When there is an electrical fault or overload, the circuit breaker trips and stops the electricity flow, preventing additional damage to the circuit. Like this, in software programs, a circuit breaker keeps track of calls to external services and offers security by opening or tripping the circuit as needed.

Requests can still reach the external service when a circuit breaker is closed, as is the case normally. The circuit breaker, however, changes to the open state if the quantity of mistakes or failures surpasses a set threshold within a predetermined period. All additional requests are short-circuited, or not even made, while the external service is in the open state. Instead, it immediately throws an error or returns a predetermined default response. By doing so, the external service's workload is lightened, and additional failures are avoided.

A limited number of queries can be made to the external service to see if it has recovered after a set amount of time, at which point the circuit breaker becomes partially open. If these requests are granted, the circuit breaker switches back to the closed position, presuming the external service is once more operating properly. If any of these requests are unsuccessful, the circuit breaker returns to the open state, and the procedure is repeated.

Using several libraries and frameworks, such as Polly or the Microsoft.AspNetCore.Http.Abstractions package, one can implement a circuit breaker pattern in ASP.NET Core. These libraries provide the necessary parts, such as error threshold monitoring, state transitions, and fallback methods, to package calls to external services with circuit breaker capabilities.

Circuit breakers can increase the resilience of your ASP.NET Core apps and guard against failures brought on by unreliable or unavailable external services. By gracefully handling failures, it aids in fault isolation, upholds program stability, and improves user experience.

## Implementation Of Circuit Breaker in Asp.net Core 
First, make sure you have the Polly NuGet package installed in your ASP.NET Core project. You can install it using the Package Manager Console or the NuGet Package Manager in Visual Studio.
Next, let's assume you have a service that makes HTTP requests to an external API. We'll create a circuit breaker around this service to handle failures and timeouts.
### 1. Install the required NuGet packages:
```
Install-Package Polly
```

### 2. Create a new class for the circuit breaker policy. Here's an example:
```csharp
using Polly;
using System;
using System.Net.Http;
public class CircuitBreakerService
{
    private readonly HttpClient _httpClient;
    private readonly Policy _circuitBreakerPolicy;
    public CircuitBreakerService()
    {
        _httpClient = new HttpClient();
        _circuitBreakerPolicy = Policy.Handle<Exception>()
            .CircuitBreakerAsync(3, TimeSpan.FromSeconds(30), (ex, t) =>
            {
                // This action is executed when the circuit is opened
                Console.WriteLine("Circuit breaker opened.");
            }, () =>
            {
                // This action is executed when the circuit is reset
                Console.WriteLine("Circuit breaker reset.");
            });
    }
    public async Task<string> MakeRequestAsync()
    {
        // Wrap the HTTP request with the circuit breaker policy
        var response = await _circuitBreakerPolicy.ExecuteAsync(async () =>
        {
            return await _httpClient.GetAsync("https://api.example.com/endpoint");
        });

        if (response.IsSuccessStatusCode)
        {
            return await response.Content.ReadAsStringAsync();
        }
        else
        {
            // Handle unsuccessful response
            return null;
        }
    }
}
```
In the example above, we create a `CircuitBreakerService` class that encapsulates the HTTP request to an external API. The `Policy.Handle<Exception>().CircuitBreakerAsync()` method sets up a circuit breaker policy that monitors exceptions. In this case, the circuit will break if there are 3 exceptions within a 30-second window.
The `MakeRequestAsync()` method wraps the HTTP request with the circuit breaker policy using the `ExecuteAsync()` method. If the circuit is open (broken), the request will not be sent, and the circuit breaker's fallback behavior will be triggered.
### 3. Now, you can use the `CircuitBreakerService` in your ASP.NET Core controllers or other components:

```csharp
public class MyController : Controller
{
    private readonly CircuitBreakerService _circuitBreakerService;

    public MyController(CircuitBreakerService circuitBreakerService)
    {
        _circuitBreakerService = circuitBreakerService;
    }

    public async Task<IActionResult> Index()
    {
        string result = await _circuitBreakerService.MakeRequestAsync();
        if (result != null)
        {
            return Ok(result);
        }
        else
        {
            return StatusCode(500, "Failed to retrieve data.");
        }
    }
}
```

In this example, we inject the `CircuitBreakerService` into an ASP.NET Core controller using dependency injection. The `Index()` action calls the `MakeRequestAsync()` method of the service. If the request is successful, the result is returned as an `Ok` response. Otherwise, a 500-status code with an error message is returned.

By implementing a circuit breaker, you can gracefully handle failures and timeouts, prevent cascading failures, and provide a more robust and resilient ASP.NET Core application.