CacheFlow.CircuitBreaker extends CacheFlow with robust circuit breaker capabilities: - Thread-safe circuit breaker implementation - Configurable failure thresholds - Adjustable sampling windows - Automatic recovery mechanisms - Sliding window failure counting - Comprehensive failure tracking - Intelligent state management - Exception-based circuit breaking - Decorator pattern integration - Detailed failure logging Perfect for applications requiring resilient caching with failure protection.
$ dotnet add package CacheFlow.CircuitBreakerA resilient circuit breaker implementation for CacheFlow that prevents cascading failures and provides intelligent failure handling with configurable thresholds and recovery mechanisms.
dotnet add package CacheFlow.CircuitBreaker
// 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 ICacheFlowManager _cache;
public UserService(ICacheFlowManager 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);
}
}
}
| 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 |
Configuration
Error Handling
Performance
public class CacheService
{
private readonly ICacheFlowManager _cache;
private readonly ILogger<CacheService> _logger;
public CacheService(ICacheFlowManager 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();
}
}
}
await _cache.GetOrCreateAsync(
key,
state,
factory,
new CacheFlowEntryOptions { Duration = TimeSpan.FromMinutes(10) },
new[] { "profile", "user-data" }
);
// All operations protected by circuit breaker
await _cache.RemoveByTagAsync("user-data");
Contributions are welcome! Please feel free to submit a Pull Request.
This project is licensed under the terms mentioned in the package.