# Chaos Engineering in .NET With Simmy

> You have retries, circuit breakers, and timeouts configured. Have you ever seen them fire? Simmy injects faults, latency, and bad responses into your Polly pipelines so you can prove your resilience policies work before a real outage tests them. Fault injection often turns up a policy that was a misconfigured no-op.

Published: 2026-11-26. Author: Milan Jovanović. Topic: Resilience. Tags: chaos-engineering, dotnet, polly, resilience.

Canonical: https://milanjovanovic.tech/blog/chaos-engineering-simmy-dotnet

Your resilience setup probably looks great in code review.
Retries with exponential backoff, a circuit breaker, timeouts on every client.

Have you ever *seen* any of it fire?

The first round of deliberate fault injection often turns up a policy that was a no-op.
A `ShouldHandle` predicate that never matches.
A resilience handler attached to the wrong `HttpClient`.
A retry count bound from configuration that resolves to zero in staging.

**Simmy** lets you find that out in a planned experiment instead of during an outage.

## Chaos Strategies Ship Inside Polly Now

Simmy used to be a separate contrib package.
Since Polly 8.3, it's part of `Polly.Core` under the `Polly.Simmy` namespace, so if you're on [**Polly v8 resilience pipelines**](https://milanjovanovic.tech/blog/polly-v8-resilience-pipelines), you already have it.

```bash
dotnet add package Polly.Core
```

There are four chaos strategies:

- **Fault**: throws an exception (`HttpRequestException`, `TimeoutException`, whatever you configure).
- **Latency**: delays the call, simulating a slow dependency.
- **Outcome**: returns a fabricated result, like a `500` or a `429` response, without touching the network.
- **Behavior**: runs arbitrary code before the call, useful for things like killing a connection or restarting a container.

Each one has an `InjectionRate` (0.0 to 1.0, the probability it activates per execution) and an `EnabledGenerator` (a runtime on/off switch, evaluated per execution).

## Injecting Latency and Faults

Here's a pipeline for an HTTP client that, when chaos is enabled, adds 5 seconds of latency to 10 percent of calls and throws an `HttpRequestException` on 5 percent.
`chaosSettings` is an instance of the `ChaosSettings` class shown later:

```csharp
using Polly;
using Polly.Retry;
using Polly.Simmy;
using Polly.Simmy.Fault;
using Polly.Simmy.Latency;
using Polly.Timeout;

ResiliencePipeline<HttpResponseMessage> pipeline =
    new ResiliencePipelineBuilder<HttpResponseMessage>()
        // Real resilience strategies first (outermost).
        .AddRetry(new RetryStrategyOptions<HttpResponseMessage>
        {
            ShouldHandle = new PredicateBuilder<HttpResponseMessage>()
                .Handle<HttpRequestException>()
                .Handle<TimeoutRejectedException>()
                .HandleResult(r => (int)r.StatusCode >= 500),
            MaxRetryAttempts = 3,
            BackoffType = DelayBackoffType.Exponential,
            UseJitter = true
        })
        .AddTimeout(TimeSpan.FromSeconds(2))
        // Chaos strategies last (innermost).
        .AddChaosLatency(new ChaosLatencyStrategyOptions
        {
            InjectionRate = 0.10,
            Latency = TimeSpan.FromSeconds(5),
            EnabledGenerator = args =>
                ValueTask.FromResult(chaosSettings.Enabled)
        })
        .AddChaosFault(new ChaosFaultStrategyOptions
        {
            InjectionRate = 0.05,
            FaultGenerator = new FaultGenerator()
                .AddException<HttpRequestException>(),
            EnabledGenerator = args =>
                ValueTask.FromResult(chaosSettings.Enabled)
        })
        .Build();
```

In Polly v8, strategies execute in the order you add them: first added is outermost.
**Chaos strategies go last**, which puts them innermost, between your resilience strategies and the real call.

An injected fault should travel *outward* through the timeout and the retry, exactly like a real failure from the dependency would.
Put the chaos strategy first (outermost) and the fault bypasses everything you're trying to test.
You'd be injecting failures into your callers, not into your resilience layer.

![A resilience pipeline with retry outermost, then timeout, then chaos strategies innermost next to the real dependency, so an injected fault flows outward through the timeout and retry exactly like a real failure would](https://milanjovanovic.tech/blogs/articles/chaos-engineering-simmy-dotnet/chaos-pipeline-order.png)

The retry's `ShouldHandle` includes `TimeoutRejectedException`.
Without it, injected latency trips the 2-second timeout and the retry never runs, because the predicate only matches `HttpRequestException` and 5xx responses.

Run this in staging and watch what happens.
If your logs don't show retry attempts and your timeout metric doesn't move while chaos is on, you've found a no-op policy.

## Injecting Bad Responses With Outcome

Faults test exception handling.
The outcome strategy tests the status codes your `ShouldHandle` predicates claim to handle.
Add it to the same builder, after the timeout:

```csharp
using System.Net;
using System.Net.Http.Headers;
using Polly.Simmy.Outcomes;

.AddChaosOutcome(new ChaosOutcomeStrategyOptions<HttpResponseMessage>
{
    InjectionRate = 0.08,
    OutcomeGenerator = new OutcomeGenerator<HttpResponseMessage>()
        .AddResult(() => new HttpResponseMessage(HttpStatusCode.InternalServerError))
        .AddResult(() => new HttpResponseMessage(HttpStatusCode.TooManyRequests)
        {
            Headers = { RetryAfter = new RetryConditionHeaderValue(
                TimeSpan.FromSeconds(2)) }
        })
        .AddResult(() => new HttpResponseMessage(HttpStatusCode.RequestTimeout)),
    EnabledGenerator = args => ValueTask.FromResult(chaosSettings.Enabled)
})
```

Outcome injection catches predicate bugs that faults can't.
For example, your retry handles `>= 500` but the vendor's overload signal is `429`.
Inject a stream of `429`s with a `Retry-After` header and check whether your client **honors the header** or hammers straight through it.

## Wiring Chaos Into HttpClient With a Kill Switch

In a real service you want chaos on the same pipelines production traffic uses, controlled by configuration, so the same binary runs clean in production and chaotic in staging.
`AddResilienceHandler` comes from the `Microsoft.Extensions.Http.Resilience` package:

```bash
dotnet add package Microsoft.Extensions.Http.Resilience
```

```csharp
public class ChaosSettings
{
    public bool Enabled { get; set; }
    public double LatencyInjectionRate { get; set; } = 0.05;
    public double FaultInjectionRate { get; set; } = 0.02;
}
```

```csharp
using Microsoft.Extensions.Options;
using Polly;
using Polly.Retry;
using Polly.Simmy;
using Polly.Simmy.Fault;
using Polly.Simmy.Latency;
using Polly.Timeout;

builder.Services.Configure<ChaosSettings>(
    builder.Configuration.GetSection("Chaos"));

builder.Services.AddHttpClient("payments", client =>
{
    client.BaseAddress = new Uri("https://api.payment-provider.com");
})
.AddResilienceHandler("payments-pipeline", (pipeline, context) =>
{
    var chaos = context.ServiceProvider
        .GetRequiredService<IOptionsMonitor<ChaosSettings>>();

    pipeline.AddRetry(new RetryStrategyOptions<HttpResponseMessage>
    {
        ShouldHandle = new PredicateBuilder<HttpResponseMessage>()
            .Handle<HttpRequestException>()
            .Handle<TimeoutRejectedException>()
            .HandleResult(r => (int)r.StatusCode >= 500),
        MaxRetryAttempts = 3,
        BackoffType = DelayBackoffType.Exponential,
        UseJitter = true
    });

    pipeline.AddTimeout(TimeSpan.FromSeconds(2));

    pipeline.AddChaosLatency(new ChaosLatencyStrategyOptions
    {
        InjectionRate = chaos.CurrentValue.LatencyInjectionRate,
        Latency = TimeSpan.FromSeconds(5),
        EnabledGenerator = _ =>
            ValueTask.FromResult(chaos.CurrentValue.Enabled)
    });

    pipeline.AddChaosFault(new ChaosFaultStrategyOptions
    {
        InjectionRate = chaos.CurrentValue.FaultInjectionRate,
        FaultGenerator = new FaultGenerator()
            .AddException<HttpRequestException>(),
        EnabledGenerator = _ =>
            ValueTask.FromResult(chaos.CurrentValue.Enabled)
    });
});
```

Because `EnabledGenerator` is evaluated on every execution and reads `IOptionsMonitor`, flipping `Chaos:Enabled` in configuration is an immediate kill switch, no redeploy.
A feature flag service works just as well here.

In `appsettings.Staging.json`:

```json
{
  "Chaos": {
    "Enabled": true,
    "LatencyInjectionRate": 0.10,
    "FaultInjectionRate": 0.05
  }
}
```

Production keeps `Enabled: false` until you're confident enough to turn it on at a fraction of a percent.

## How Do You Run a Chaos Experiment?

Randomly breaking staging and eyeballing the logs is better than nothing, but chaos engineering is supposed to be hypothesis-driven.
A basic experiment loop:

1. **State the hypothesis.** "With the payment API failing 5 percent of calls, checkout error rate stays flat and p99 stays under 800 ms, because retries absorb the failures."
2. **Enable one strategy** at a defined rate, for a defined window.
3. **Measure** the same dashboards you'd use in an incident: retry counts, breaker state changes, [**fallback**](https://milanjovanovic.tech/blog/fallback-pattern-polly-dotnet) activations, end-to-end error rate.
4. **Compare against the hypothesis.** A mismatch is a finding: either the policy is misconfigured or your mental model of the system is wrong.

Common findings from step 4:
Retry predicates that don't match the injected fault.
A [**circuit breaker**](https://milanjovanovic.tech/blog/retry-vs-circuit-breaker) whose failure threshold is so high it never opens.
Timeouts configured on the client but not the pipeline, so retries never see them.
Alerts that don't fire during the experiment, which means the on-call rotation would have found out from customers.

Latency injection deserves special attention because it's the failure mode teams test least.
Injecting 5-second latency is how you verify your [**timeout strategy**](https://milanjovanovic.tech/blog/timeout-strategy-dotnet) and your [**bulkheads**](https://milanjovanovic.tech/blog/bulkhead-pattern-dotnet) actually bound the damage, and it pairs well with a **k6 load test** running against the chaotic environment to see the queueing effects under real concurrency.

## Summary

You don't know a resilience policy works until you've seen it fire.

Simmy makes that test cheap: it's already inside Polly v8, chaos strategies drop into the pipelines you already run, and `EnabledGenerator` gives you a per-execution kill switch driven by configuration.

Add chaos strategies last in the pipeline so faults flow through your real resilience layers.
Start in staging with fault, latency, and outcome injection.
Write down what you expect, measure what happens, and fix the gap.

## Frequently asked questions

### What is Simmy?

Simmy is the chaos engineering component of Polly. Since Polly 8.3 it ships inside the Polly.Core package under the Polly.Simmy namespace. It provides chaos strategies that inject faults, latency, custom outcomes, and behaviors into resilience pipelines at a configurable rate.

### Where should chaos strategies go in a Polly pipeline?

Add them last, so they sit innermost, between your resilience strategies and the real call. That way injected faults pass through your retries, circuit breakers, and timeouts exactly like real failures would.

### Should I run chaos experiments in production?

Start in staging with a meaningful injection rate and automated tests that assert your policies respond correctly. Production chaos is valuable but should come later, with a low injection rate, a kill switch via EnabledGenerator, and tight scoping to non-critical flows first.

### Why do resilience policies turn out to be no-ops?

Common causes: the ShouldHandle predicate does not match the exception or status code that actually occurs, the handler is registered on a different HttpClient than the one used, strategy ordering prevents a strategy from ever seeing the failure, or configuration binds zero retries in some environments. Fault injection surfaces all of these quickly.
