20 February, 2025

Circuit Breaker Pattern in .net 8

 

The Circuit Breaker Pattern will typically send an error response when it is in the open state. This means that the circuit breaker has detected too many failures in the underlying service or resource, and instead of trying to call it repeatedly (which could lead to further failures or resource exhaustion), it immediately returns an error. This helps protect the system from cascading failures.

Key Points:

  • Closed State: When all calls are successful, the circuit is closed and calls go through normally.
  • Open State: If the error threshold is exceeded, the circuit opens, and all calls are immediately rejected with an error response without attempting to call the service.
  • Half-Open State: After a cooling period, the circuit breaker allows a limited number of test calls. If these succeed, it closes the circuit; if they fail, it reopens it.

In summary, the circuit breaker sends an error response when it is in the open state because it has determined that the underlying service is likely to fail.

using System;
using System.Threading;

public enum CircuitState
{
    Closed,
    Open,
    HalfOpen
}

public class CircuitBreaker
{
    private readonly int _failureThreshold;
    private readonly TimeSpan _openTimeout;
    private int _failureCount;
    private DateTime _lastFailureTime;
    private CircuitState _state;

    public CircuitBreaker(int failureThreshold, TimeSpan openTimeout)
    {
        _failureThreshold = failureThreshold;
        _openTimeout = openTimeout;
        _state = CircuitState.Closed;
    }

    public T Execute<T>(Func<T> action)
    {
        // Check state and manage open state timeout
        if (_state == CircuitState.Open)
        {
            if (DateTime.UtcNow - _lastFailureTime > _openTimeout)
            {
                // Move to half-open state to test if service has recovered
                _state = CircuitState.HalfOpen;
            }
            else
            {
                throw new Exception("Circuit breaker is open. Request blocked.");
            }
        }

        try
        {
            T result = action();

            // If the call succeeds in half-open, reset the circuit
            if (_state == CircuitState.HalfOpen)
            {
                Reset();
            }

            return result;
        }
        catch (Exception)
        {
            RegisterFailure();
            throw;
        }
    }

    private void RegisterFailure()
    {
        _failureCount++;
        _lastFailureTime = DateTime.UtcNow;

        if (_failureCount >= _failureThreshold)
        {
            _state = CircuitState.Open;
        }
    }

    private void Reset()
    {
        _failureCount = 0;
        _state = CircuitState.Closed;
    }
}

public class Service
{
    private readonly Random _random = new Random();

    public string GetData()
    {
        // Simulate a service call that may fail
        if (_random.NextDouble() < 0.5)
        {
            throw new Exception("Service failure!");
        }
        return "Success!";
    }
}

public class Program
{
    public static void Main()
    {
        var circuitBreaker = new CircuitBreaker(failureThreshold: 3, openTimeout: TimeSpan.FromSeconds(5));
        var service = new Service();

        for (int i = 0; i < 10; i++)
        {
            try
            {
                // Wrap the service call with circuit breaker logic
                string response = circuitBreaker.Execute(() => service.GetData());
                Console.WriteLine($"Call {i + 1}: {response}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Call {i + 1}: {ex.Message}");
            }

            // Wait a bit between calls
            Thread.Sleep(1000);
        }
    }
}

Explanation:

  • CircuitBreaker Class:

    • The breaker starts in a Closed state.
    • On every failed call, RegisterFailure() increments the failure count and, if the threshold is met, sets the state to Open.
    • If in Open state, further calls will immediately throw an exception unless the timeout has expired, in which case the state moves to HalfOpen.
    • In HalfOpen state, if the next call succeeds, the breaker resets (returns to Closed). Otherwise, it transitions back to Open.
  • Service Class:

    • Simulates a service that randomly fails.
  • Program Class (Main Method):

    • Demonstrates making multiple calls via the circuit breaker, handling errors, and showing the state changes.

This example gives a clear overview of how you might implement a basic circuit breaker in C# for managing service calls.

No comments:

Post a Comment

Microservices vs Monolithic Architecture

 Microservices vs Monolithic Architecture Here’s a clear side-by-side comparison between Microservices and Monolithic architectures — fro...