CacheFlow.CircuitBreaker 0.0.7

dotnet add package CacheFlow.CircuitBreaker --version 0.0.7                
NuGet\Install-Package CacheFlow.CircuitBreaker -Version 0.0.7                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="CacheFlow.CircuitBreaker" Version="0.0.7" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add CacheFlow.CircuitBreaker --version 0.0.7                
#r "nuget: CacheFlow.CircuitBreaker, 0.0.7"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install CacheFlow.CircuitBreaker as a Cake Addin
#addin nuget:?package=CacheFlow.CircuitBreaker&version=0.0.7

// Install CacheFlow.CircuitBreaker as a Cake Tool
#tool nuget:?package=CacheFlow.CircuitBreaker&version=0.0.7                

CacheFlow.CircuitBreaker

A resilient circuit breaker implementation for CacheFlow that prevents cascading failures and provides intelligent failure handling with configurable thresholds and recovery mechanisms.

Features

  • 🛡️ Thread-safe Circuit Breaker: Robust implementation for concurrent environments
  • High Performance: Minimal overhead during normal operation
  • 🎯 Configurable Thresholds: Customize failure limits and recovery times
  • 📊 Sliding Window: Efficient failure tracking with automatic cleanup
  • 🔄 Automatic Recovery: Self-healing with half-open state testing
  • 📝 Comprehensive Logging: Detailed failure and state transition tracking
  • 🎨 Decorator Pattern: Clean integration with existing CacheFlow implementations
  • 🚦 State Management: Closed, Open, and Half-Open states
  • ⚠️ Exception Handling: Clear error reporting with CircuitBreakerOpenException

Installation

dotnet add package CacheFlow.CircuitBreaker

Quick Start

// Add circuit breaker to your services
services.AddCacheFlow()
        .AddCircuitBreaker(options =>
        {
            options.FailureThreshold = 5;
            options.MinimumThroughput = 3;
            options.DurationOfBreak = TimeSpan.FromSeconds(30);
            options.SamplingDuration = TimeSpan.FromSeconds(60);
        });

// Use in your code
public class UserService
{
    private readonly CacheFlowManager _cache;

    public UserService(CacheFlowManager cache)
    {
        _cache = cache;
    }

    public async Task<UserProfile> GetUserProfileAsync(string userId)
    {
        try
        {
            return await _cache.GetOrCreateAsync(
                $"user:{userId}",
                userId,
                async (id, ct) => await FetchUserProfileFromDatabase(id)
            );
        }
        catch (CircuitBreakerOpenException)
        {
            // Handle circuit breaker open state
            return await FetchUserProfileFromDatabase(userId);
        }
    }
}

Configuration Options

Option Description Default
FailureThreshold Number of failures before circuit opens 5
DurationOfBreak Time circuit stays open 30 seconds
SamplingDuration Window for counting failures 60 seconds
MinimumThroughput Minimum requests before tripping 3

Circuit States

  • Closed: Normal operation, requests flow through
  • Open: Protection mode, requests blocked
  • Half-Open: Testing mode, limited requests allowed

Best Practices

  1. Configuration

    • Set appropriate thresholds based on your system
    • Adjust sampling duration to match traffic patterns
    • Configure break duration based on recovery time
  2. Error Handling

    • Always implement fallback mechanisms
    • Log circuit breaker state changes
    • Monitor failure patterns
  3. Performance

    • Circuit breaker adds minimal overhead
    • Use appropriate thresholds for your load
    • Monitor recovery success rates

Integration Example

public class CacheService
{
    private readonly CacheFlowManager _cache;
    private readonly ILogger<CacheService> _logger;

    public CacheService(CacheFlowManager cache, ILogger<CacheService> logger)
    {
        _cache = cache;
        _logger = logger;
    }

    public async Task<T> GetWithFallbackAsync<T>(
        string key,
        Func<Task<T>> factory,
        Func<Task<T>> fallback)
    {
        try
        {
            return await _cache.GetOrCreateAsync(key, key, async (k, ct) => await factory());
        }
        catch (CircuitBreakerOpenException ex)
        {
            _logger.LogWarning(ex, "Circuit breaker open, using fallback for key: {Key}", key);
            return await fallback();
        }
    }
}

Advanced Usage

Custom Tags Support

await _cache.GetOrCreateAsync(
    key,
    state,
    factory,
    new CacheFlowEntryOptions { Duration = TimeSpan.FromMinutes(10) },
    new[] { "profile", "user-data" }
);

Batch Operations

// All operations protected by circuit breaker
await _cache.RemoveByTagAsync("user-data");

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

This project is licensed under the terms mentioned in the package.

Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 is compatible.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.