Skip to content

Latest commit

 

History

26 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

PollyChaos

NuGet NuGet Downloads CI License: MIT .NET 10 Ready

Chaos engineering for Polly v8. Inject faults and latency into your resilience pipelines to prove your system handles failures gracefully — before production does it for you.

The Simmy-compatible chaos companion for Polly v8. If you used Polly.Contrib.Simmy with Polly v7, this is what you have been waiting for.

Install

dotnet add package PollyChaos

Quick start

using PollyChaos;

// Throw an exception on 10% of calls
var pipeline = new ResiliencePipelineBuilder()
    .AddChaosFault(injectionRate: 0.1)
    .AddRetry(new RetryStrategyOptions { MaxRetryAttempts = 3 })
    .Build();

await pipeline.ExecuteAsync(ct => httpClient.GetAsync("/api/orders", ct), cancellationToken);

Why PollyChaos?

Feature Polly.Contrib.Simmy (v7) PollyChaos (v8)
Polly version v7 only v8
Fault injection
Latency injection
Enabled toggle
Generic pipeline (Builder<T>)
Callbacks (OnFaultInjected)
.NET 9 support
Zero extra dependencies

Usage

Fault injection

// Throw ChaosException on 10% of calls
var pipeline = new ResiliencePipelineBuilder()
    .AddChaosFault(injectionRate: 0.1)
    .Build();

// Throw a custom exception
var pipeline = new ResiliencePipelineBuilder()
    .AddChaosFault(injectionRate: 0.05, fault: new HttpRequestException("injected failure"))
    .Build();

Latency injection

// Add a 2-second delay on 5% of calls
var pipeline = new ResiliencePipelineBuilder()
    .AddChaosLatency(injectionRate: 0.05, latency: TimeSpan.FromSeconds(2))
    .Build();

Combined chaos pipeline

var pipeline = new ResiliencePipelineBuilder<HttpResponseMessage>()
    .AddChaosFault<HttpResponseMessage>(injectionRate: 0.05)   // 5% exceptions
    .AddChaosLatency<HttpResponseMessage>(injectionRate: 0.1)  // 10% slow calls
    .AddRetry(new RetryStrategyOptions<HttpResponseMessage> { MaxRetryAttempts = 3 })
    .AddCircuitBreaker(new CircuitBreakerStrategyOptions<HttpResponseMessage>())
    .Build();

Toggle via configuration (feature flag)

Flip chaos on/off without rebuilding the pipeline — ideal for integration test environments:

var chaosOptions = new ChaosFaultStrategyOptions
{
    InjectionRate = 0.2,
    Enabled = config.GetValue<bool>("ChaosEngineering:Enabled"),
    FaultFactory = () => new TimeoutException("chaos: downstream timeout"),
    OnFaultInjected = args =>
    {
        logger.LogWarning("Chaos fault injected for {Operation}", args.Context.OperationKey);
        return ValueTask.CompletedTask;
    },
};

var pipeline = new ResiliencePipelineBuilder()
    .AddChaosFault(chaosOptions)
    .Build();

ASP.NET Core integration

// Program.cs
builder.Services.AddResiliencePipeline("orders-client", (pipelineBuilder, context) =>
{
    var config = context.ServiceProvider.GetRequiredService<IConfiguration>();
    var chaosEnabled = config.GetValue<bool>("ChaosEngineering:Enabled");

    pipelineBuilder
        .AddChaosFault(new ChaosFaultStrategyOptions
        {
            InjectionRate = 0.1,
            Enabled = chaosEnabled,
        })
        .AddChaosLatency(new ChaosLatencyStrategyOptions
        {
            InjectionRate = 0.05,
            Latency = TimeSpan.FromSeconds(3),
            Enabled = chaosEnabled,
        })
        .AddRetry(new RetryStrategyOptions { MaxRetryAttempts = 3 })
        .AddCircuitBreaker(new CircuitBreakerStrategyOptions());
});

Pipeline order

Place chaos strategies outside (before) retry so injected faults are retried — just like real failures:

var pipeline = new ResiliencePipelineBuilder()
    .AddChaosFault(injectionRate: 0.1)   // 1. inject faults
    .AddChaosLatency(injectionRate: 0.1) // 2. inject latency
    .AddRetry(...)                        // 3. retry failures
    .AddCircuitBreaker(...)              // 4. trip if too many failures
    .Build();

Related Packages

Package Downloads Description
PollyHealthChecks Downloads ASP.NET Core health checks for Polly v8 circuit breakers — expose circuit-breaker state (Closed, HalfOpen, Open, Isolated) as /health endpoint responses
PollyOpenTelemetry Downloads OpenTelemetry instrumentation for Polly v8 resilience pipelines
PollyBackoff Downloads Backoff delay strategies for Polly v8 resilience pipelines
PollyGrpc Downloads Polly v8 resilience interceptor for gRPC
PollyEFCore Downloads Polly v8 resilience pipelines for Entity Framework Core — wrap every EF Core query and SaveChanges with retry, timeout and circuit-breaker via a single AddPollyResilience() call
PollyMailKit Downloads Polly v8 resilience pipelines for MailKit — retry, timeout, and circuit-breaker for SmtpClient.SendAsync and any MailKit SMTP operation
PollyOpenAI Downloads Polly v8 resilience for OpenAI and Azure OpenAI API calls
PollySignalR Downloads Polly v8 reconnect policy for SignalR
PollyHangfire Downloads Polly v8 resilience pipelines for Hangfire — retry, timeout, and circuit-breaker for IBackgroundJobClient.Enqueue and Schedule
PollyMediatR Downloads Polly v8 resilience pipelines for MediatR — add retry, timeout, circuit-breaker, rate-limiting, hedging, and chaos engineering to any MediatR request handler with a single line of DI registration
PollyAzureQueueStorage Downloads Polly v8 resilience pipelines for Azure Queue Storage — retry, timeout, and circuit-breaker for Azure.Storage.Queues QueueClient
PollyRedis Downloads Polly v8 resilience for StackExchange.Redis
PollyAzureServiceBus Downloads Polly v8 resilience for Azure Service Bus — retry, circuit breaker, and timeout for sending and receiving messages
PollyKafka Downloads Polly v8 resilience for Confluent.Kafka — retry, circuit breaker, and timeout for producers and consumers
PollyRateLimiter Downloads Convenience extension methods for Polly v8 resilience pipelines: AddFixedWindowRateLimiter, AddSlidingWindowRateLimiter, and AddTokenBucketRateLimiter
PollyCaching Downloads A caching resilience strategy for Polly v8 pipelines
PollyBulkhead Downloads Bulkhead isolation strategy for Polly v8 resilience pipelines

Support

If PollyChaos helps you ship more resilient software, consider supporting the project:

Sponsor

💼 Need .NET resilience help? Visit solidqualitysolutions.com for consulting and architecture services.

| PollyRabbitMQ | Polly v8 resilience for RabbitMQ.Client channels |

Also by the same author

🌐 swevo.github.io

Package Description
AutoLog.Generator Compile-time high-performance logging — [Log(Level, Message)] generates LoggerMessage.Define. AOT-safe.
AutoHttpClient.Generator Compile-time typed HTTP client — [HttpClient] on an interface generates a strongly-typed client. AOT-safe Refit alternative.
AutoDispatch.Generator Compile-time CQRS dispatcher — [Handler] generates a strongly-typed IDispatcher. MediatR alternative.
AutoWire Compile-time DI auto-registration — [Scoped]/[Singleton]/[Transient] generates IServiceCollection registration code.
AutoMap.Generator Compile-time object mapping — [Map(typeof(Dto))] generates ToDto() extension methods. AutoMapper alternative.

License

MIT

Releases

Packages

Contributors

Languages