Vali-Mediator.Resilience 2.0.0

dotnet add package Vali-Mediator.Resilience --version 2.0.0
                    
NuGet\Install-Package Vali-Mediator.Resilience -Version 2.0.0
                    
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="Vali-Mediator.Resilience" Version="2.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Vali-Mediator.Resilience" Version="2.0.0" />
                    
Directory.Packages.props
<PackageReference Include="Vali-Mediator.Resilience" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Vali-Mediator.Resilience --version 2.0.0
                    
#r "nuget: Vali-Mediator.Resilience, 2.0.0"
                    
#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.
#:package Vali-Mediator.Resilience@2.0.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Vali-Mediator.Resilience&version=2.0.0
                    
Install as a Cake Addin
#tool nuget:?package=Vali-Mediator.Resilience&version=2.0.0
                    
Install as a Cake Tool

Vali-Mediator.Resilience

A zero-dependency resilience library for .NET 7/8/9/10, built to complement Vali-Mediator — or be used entirely on its own.

No Polly. No extra frameworks. Just a clean, fluent API with production-grade policies.


Features

Policy Highlights
Retry Fixed / Linear / Exponential / Exponential+Jitter / Custom backoff · per-exception, per-ErrorType, per-result predicates · OnRetry callback
Circuit Breaker Sliding-window state machine (Closed → Open → HalfOpen) · absolute threshold or rate-based threshold · OnOpen/OnClose/OnHalfOpen callbacks · keyed registry for shared state
Timeout Optimistic (CancellationToken) and Pessimistic (Task.WhenAny) strategies · OnTimeout callback
Fallback Typed fallback value or async factory · conditional activation · OnFallback callback
Bulkhead Semaphore-based concurrency limiter · optional queue with configurable timeout · OnRejected callback
Hedge Launches a parallel attempt after a delay; first successful response wins, the rest are cancelled · OnHedge callback
Rate Limiter Token Bucket or Sliding Window algorithm · optional per-partition limiting (per user/IP) with bounded memory · OnRejected callback
Chaos Injects faults (exceptions, latency, bad results) at a configurable rate — for testing the other policies, not for production
Presets ForExternalApi, ForDatabase, ForCritical, NoResilience
Vali-Mediator IResilient + ResilienceBehavior<TRequest,TResponse> auto-applies policy from the request

Execution order

When several policies are combined on the same ResiliencePolicy, they wrap the call in this fixed order:

Fallback → Chaos → Rate Limiter → Retry → Timeout → Circuit Breaker → Bulkhead → Hedge → your delegate

Rate limiting and chaos are evaluated once per logical call (not retried); timeout applies per attempt.


Installation

dotnet add package Vali-Mediator.Resilience

Standalone Usage

Retry with exponential jitter

var policy = ResiliencePolicy.Create("payment-gateway")
    .Retry(options =>
    {
        options.MaxRetries = 3;
        options.BackoffType = BackoffType.ExponentialWithJitter;
        options.InitialDelay = TimeSpan.FromMilliseconds(200);
        options.MaxDelay = TimeSpan.FromSeconds(5);
        options.OnRetry = (ctx, delay) =>
        {
            Console.WriteLine($"Retry {ctx.AttemptNumber}, waiting {delay.TotalMilliseconds:0}ms");
            return Task.CompletedTask;
        };
    })
    .Build();

string html = await policy.ExecuteAsync(ct => httpClient.GetStringAsync(url, ct));

Circuit Breaker + Timeout + Fallback

var policy = ResiliencePolicy.Create("inventory-service")
    .CircuitBreaker(options =>
    {
        options.CircuitKey = "inventory-service";
        options.FailureThreshold = 5;
        options.SamplingDuration = TimeSpan.FromSeconds(30);
        options.BreakDuration = TimeSpan.FromSeconds(60);
        options.OnOpen = (ctx, ex) =>
        {
            logger.LogWarning("Circuit opened: {Key}", ctx.OperationKey);
            return Task.CompletedTask;
        };
    })
    .Timeout(TimeSpan.FromSeconds(10))
    .Fallback<InventoryDto>(options =>
    {
        options.FallbackValue = InventoryDto.Empty;
        options.OnFallback = (ctx, ex) =>
        {
            logger.LogWarning(ex, "Falling back on {Key}", ctx.OperationKey);
            return Task.CompletedTask;
        };
    })
    .ExecuteAsync(ct => inventoryClient.GetAsync(productId, ct));

Rate-based circuit breaker

var policy = ResiliencePolicy.Create("payments")
    .CircuitBreaker(options =>
    {
        options.CircuitKey = "payments";
        options.FailureRateThreshold = 0.5;   // open when ≥50% of calls fail
        options.MinimumThroughput = 20;        // need at least 20 calls to evaluate
        options.SamplingDuration = TimeSpan.FromSeconds(60);
        options.BreakDuration = TimeSpan.FromSeconds(30);
    })
    .Build();

Bulkhead

var policy = ResiliencePolicy.Create("db")
    .Bulkhead(options =>
    {
        options.MaxConcurrentCalls = 20;
        options.MaxQueuedCalls = 5;
        options.QueueTimeout = TimeSpan.FromSeconds(3);
        options.OnRejected = ctx =>
        {
            metrics.IncrementCounter("db.rejected");
            return Task.CompletedTask;
        };
    })
    .Build();

Hedge — launch a parallel attempt if the first is slow

var policy = ResiliencePolicy.Create("catalog-read")
    .Hedge(options =>
    {
        options.HedgeDelay = TimeSpan.FromMilliseconds(200); // fire a hedge if no response by then
        options.MaxHedgedAttempts = 1;                        // one extra parallel call
        options.OnHedge = ctx =>
        {
            logger.LogInformation("Hedge attempt #{Attempt} for {Key}", ctx.AttemptNumber, ctx.OperationKey);
            return Task.CompletedTask;
        };
    })
    .Build();

var product = await policy.ExecuteAsync(ct => catalogClient.GetProductAsync(id, ct));

Rate Limiter — global or per-partition (per user/IP)

// Global token bucket: 10 capacity, refills 5 tokens/second
var policy = ResiliencePolicy.Create("search-api")
    .RateLimiter(bucketCapacity: 10, tokensPerInterval: 5)
    .Build();

// Per-user sliding window — each key gets its own independent counter
var loginPolicy = ResiliencePolicy.Create("login")
    .RateLimiter(options =>
    {
        options.Algorithm = RateLimiterAlgorithm.SlidingWindow;
        options.PermitLimit = 5;
        options.Window = TimeSpan.FromMinutes(1);
        options.PartitionKeyResolver = req => ((LoginCommand)req).Email;
    })
    .Build();

Chaos — inject faults to test the other policies (non-production)

var policy = ResiliencePolicy.Create("payments")
    .Chaos(injectionRate: 0.1, options => // 10% of calls
    {
        options.ExceptionFactory = () => new HttpRequestException("Injected by chaos testing");
        options.OnChaosInjected = () => { logger.LogWarning("Chaos fault injected"); return Task.CompletedTask; };
    })
    .Retry(3)
    .Build();

Void operation

await policy.ExecuteAsync(ct => cache.FlushAsync(ct));

Presets

// HTTP API calls — Retry × 3 (jitter) + CB(5 fails/30s) + Timeout 15s
var policy = ResiliencePolicy.Presets.ForExternalApi("payment-gateway");

// Database — Retry × 2 (linear) + CB(3 fails/20s) + Timeout 30s + Bulkhead 20
var policy = ResiliencePolicy.Presets.ForDatabase("sqlserver");

// Critical paths — Retry × 5 (jitter) + Rate CB(50%/20 calls/60s) + Timeout 20s + Bulkhead 5
var policy = ResiliencePolicy.Presets.ForCritical("auth");

// No resilience (pass-through)
var policy = ResiliencePolicy.Presets.NoResilience();

Vali-Mediator Integration

Setup

builder.Services.AddValiMediator(config =>
{
    config.RegisterServicesFromAssemblyContaining<Program>();
    config.AddResilienceBehavior();  // registers ResilienceBehavior<,>
});

// Optional: shared circuit state across all policies (singleton registry)
builder.Services.AddResilienceRegistry();

Policy resolution order

ResilienceBehavior resolves the policy for each request in this order:

Priority Mechanism Use when
1 AddResiliencePolicy<T> / AddResiliencePolicyProvider<T,P> Recommended — policy lives outside the command
2 IResilient on the command Legacy / backward compat (deprecated)
3 AddGlobalResiliencePolicy Default for all requests without a specific policy

Inline policy — no class needed

// Program.cs
services.AddResiliencePolicy<LoginCommand>(req =>
    ResiliencePolicy.Create()
        .RateLimiter(opts =>
        {
            opts.Algorithm = RateLimiterAlgorithm.SlidingWindow;
            opts.PermitLimit = 5;
            opts.Window = TimeSpan.FromMinutes(1);
            opts.PartitionKeyResolver = r => ((LoginCommand)r).Email; // per user
        })
        .Build());

Class-based policy provider — for injected dependencies

public class PlaceOrderPolicyProvider : IResiliencePolicyProvider<PlaceOrderCommand>
{
    private readonly ResilienceSettings _settings;

    public PlaceOrderPolicyProvider(IOptions<ResilienceSettings> opts)
        => _settings = opts.Value;

    public ResiliencePolicy GetPolicy(PlaceOrderCommand request) =>
        ResiliencePolicy.Create("place-order")
            .Retry(opts =>
            {
                opts.MaxRetries = _settings.MaxRetries;
                opts.BackoffType = BackoffType.ExponentialWithJitter;
            })
            .CircuitBreaker(opts =>
            {
                opts.CircuitKey = "payment-gateway";
                opts.FailureThreshold = 5;
                opts.BreakDuration = TimeSpan.FromSeconds(30);
            })
            .Timeout(TimeSpan.FromSeconds(10))
            .Build();
}

// Auto-discovered — no manual registration needed
// (see Auto-Discovery below)

Auto-Discovery

All IResiliencePolicyProvider<T> implementations are automatically discovered from your registered assemblies:

builder.Services.AddValiMediator(config =>
{
    config.RegisterServicesFromAssemblyContaining<Program>();
    config.AddResilienceBehavior();
});

// Auto-discovers and registers all policy providers
builder.Services.RegisterResiliencePoliciesFromAssemblyContaining<Program>();

The default lifetime is Scoped. For stateless providers, use Singleton:

builder.Services.RegisterResiliencePoliciesFromAssemblyContaining<Program>(
    lifetime: ServiceLifetime.Singleton);

Global policy — applies to all commands without a specific policy

services.AddGlobalResiliencePolicy(
    ResiliencePolicy.Create()
        .Retry(3)
        .Timeout(TimeSpan.FromSeconds(30))
        .Build());

// Or vary by request type
services.AddGlobalResiliencePolicy(req =>
    ResiliencePolicy.Create()
        .Retry(req is IQuery ? 3 : 1)
        .Build());

Partitioned rate limiting — per user/IP

services.AddResiliencePolicy<ResetPasswordCommand>(req =>
    ResiliencePolicy.Create()
        .RateLimiter(opts =>
        {
            opts.Algorithm = RateLimiterAlgorithm.SlidingWindow;
            opts.PermitLimit = 3;
            opts.Window = TimeSpan.FromMinutes(15);
            opts.PartitionKeyResolver = r => ((ResetPasswordCommand)r).Email;
        })
        .Build());

Each unique key gets its own independent counter. User A exhausting their limit does not affect User B.


Exception Types

Exception Thrown when
CircuitOpenException A request arrives while the circuit is Open. Contains CircuitKey and RetryAfter.
BulkheadRejectedException Concurrency slots and queue are both full. Contains limits.
RateLimitExceededException No token/slot available and the queue (if any) timed out.
TimeoutException Operation exceeded the configured Timeout.

ResilienceContext

All callbacks receive a ResilienceContext:

options.OnRetry = (ctx, delay) =>
{
    ctx.AttemptNumber   // 0-based attempt index
    ctx.ElapsedTime     // time since operation started
    ctx.LastException   // exception from last attempt
    ctx.OperationKey    // key from ResiliencePolicy.Create("key")
    ctx.Properties      // Dictionary<string,object?> for custom data
    ctx.CancellationToken
    return Task.CompletedTask;
};

Circuit Breaker Registry

By default each ResiliencePolicy instance owns its own circuit state. To share state across instances (e.g. multiple command types hitting the same downstream service), register the singleton registry:

// DI registration (recommended)
services.AddResilienceRegistry();

// Standalone — pass the registry when building
var registry = new CircuitBreakerRegistry();
var policy = ResiliencePolicy.Create("shared-circuit")
    .CircuitBreaker(o => { o.CircuitKey = "shared-circuit"; ... })
    .UseRegistry(registry)
    .Build();

// Inspect or reset
CircuitState? state = registry.GetState("shared-circuit");
registry.Reset("shared-circuit");

Backoff Types

Type Formula
Fixed InitialDelay every attempt
Linear InitialDelay × attempt
Exponential InitialDelay × Multiplier^attempt
ExponentialWithJitter Exponential ± 20% random jitter (thundering-herd prevention)
Custom RetryOptions.CustomDelayFactory(attemptIndex)

Donations

If Vali-Mediator is useful to you, consider supporting its development:


License

Apache License 2.0

Contributions

Issues and pull requests are welcome on GitHub.

Product Compatible and additional computed target framework versions.
.NET net7.0 is compatible.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  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.  net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.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.

Version Downloads Last Updated
2.0.0 136 10/1/2026
1.2.4 255 4/23/2026
1.2.3 153 4/23/2026
1.2.2 140 4/20/2026
1.2.1 151 4/20/2026
1.2.0 140 4/20/2026
1.1.0 167 4/13/2026
1.0.1 158 3/18/2026
1.0.0 137 3/16/2026

v2.0.0 — Requires Vali-Mediator >= 3.0.0. BREAKING: new execution order, per-request policies (WithSharedState), Hedge/circuit breaker/bulkhead/rate limiter fixes, option validation. See CHANGELOG.md.

           v1.2.4 — Tests for auto-discovery:
           - Unit tests for RegisterResiliencePoliciesFromAssemblyContaining<T>() and RegisterResiliencePoliciesFromAssembly(): provider discovery, default Scoped lifetime, lifetime override, null argument guards, and policy validity.
           - Total test count: 87 → 97.

           v1.2.3 — Auto-discovery for IResiliencePolicyProvider<T>:
           - RegisterResiliencePoliciesFromAssemblyContaining<T>(): auto-discovers and registers all policy providers.
           - RegisterResiliencePoliciesFromAssembly(assembly, lifetime): explicit assembly variant.
           Eliminates manual AddResiliencePolicyProvider<T,P>() calls for each provider class.

           v1.2.2 — Bug fix: ResilienceBehavior now caches the resolved ResiliencePolicy per request type using a
           static field (one cache slot per TRequest+TResponse combination). This covers both AddResiliencePolicy<T>
           lambdas and class-based IResiliencePolicyProvider<T> providers. Stateful policies (Circuit Breaker,
           Rate Limiter, Bulkhead, Hedge) now correctly preserve their state across all requests of the same type,
           regardless of behavior lifetime or provider implementation.

           v1.2.1 — Bug fix: DelegateResiliencePolicyProvider now caches the built ResiliencePolicy after the first request,
           matching the behavior of a static provider. Previously the lambda was invoked on every call, causing
           stateful policies (Circuit Breaker, Rate Limiter, Bulkhead, Hedge) to lose their state between requests.

           v1.2.0 — Policy providers & partitioned rate limiting:
           - IResiliencePolicyProvider<TRequest>: declare policies in a separate class, keeping commands clean.
           - services.AddResiliencePolicy<T>(lambda): inline registration without a class.
           - services.AddResiliencePolicyProvider<T,TProvider>(): class-based registration for DI-dependent providers.
           - IGlobalResiliencePolicyProvider / services.AddGlobalResiliencePolicy(): fallback policy for all requests.
           - RateLimiterOptions.PartitionKeyResolver: per-user/IP rate limiting via a key selector func.
           - IResilient marked [Obsolete] — use AddResiliencePolicy<T>() instead.

           v1.1.0 — Package structure: now uses Vali-Mediator as NuGet dependency instead of local ProjectReference.

           v1.0.1 — Documentation: enabled XML documentation file for full IntelliSense support.

           v1.0.0 — Initial release:
           - RetryPolicy: Fixed / Linear / Exponential / ExponentialWithJitter / Custom backoff, per-exception and per-ErrorType conditions, OnRetry callback.
           - CircuitBreakerPolicy: sliding-window failure tracking, Closed → Open → HalfOpen state machine, configurable thresholds, callbacks.
           - TimeoutPolicy: Optimistic (CancellationToken) and Pessimistic (Task.WhenAny) strategies.
           - FallbackPolicy: typed fallback value or factory, conditional activation, OnFallback callback.
           - BulkheadPolicy: semaphore-based concurrency limiter with optional queue, OnRejected callback.
           - ResiliencePolicy: composable fluent builder combining all policies.
           - ResiliencePresets: ForExternalApi, ForDatabase, ForCritical, NoResilience.
           - Vali-Mediator integration: IResilient interface + ResilienceBehavior pipeline.
           - CircuitBreakerRegistry: keyed singleton registry for sharing circuit state across calls.