|
| 1 | +# Custom Resilience Pipelines |
| 2 | + |
| 3 | +Use `AddResilienceHandler` when you need full control over which strategies run and in what order. You get the same Polly building blocks as the standard handler, but assembled manually. |
| 4 | + |
| 5 | +## Basic shape |
| 6 | + |
| 7 | +```csharp |
| 8 | +services.AddHttpClient<PaymentsClient>(c => c.BaseAddress = new("https://pay.example.com")) |
| 9 | + .AddResilienceHandler("PaymentsPipeline", pipeline => |
| 10 | + { |
| 11 | + // Order matters: outermost strategy listed first |
| 12 | + pipeline.AddRetry(new HttpRetryStrategyOptions |
| 13 | + { |
| 14 | + MaxRetryAttempts = 2, |
| 15 | + BackoffType = DelayBackoffType.Exponential, |
| 16 | + UseJitter = true, |
| 17 | + Delay = TimeSpan.FromMilliseconds(500), |
| 18 | + // Safe for idempotent GETs, but be careful with mutations |
| 19 | + ShouldHandle = new PredicateBuilder<HttpResponseMessage>() |
| 20 | + .HandleResult(r => (int)r.StatusCode >= 500 || r.StatusCode == HttpStatusCode.RequestTimeout) |
| 21 | + .Handle<HttpRequestException>() |
| 22 | + }); |
| 23 | + |
| 24 | + pipeline.AddCircuitBreaker(new HttpCircuitBreakerStrategyOptions |
| 25 | + { |
| 26 | + SamplingDuration = TimeSpan.FromSeconds(30), |
| 27 | + FailureRatio = 0.5, |
| 28 | + MinimumThroughput = 5, |
| 29 | + BreakDuration = TimeSpan.FromSeconds(30), |
| 30 | + ShouldHandle = new PredicateBuilder<HttpResponseMessage>() |
| 31 | + .HandleResult(r => (int)r.StatusCode >= 500) |
| 32 | + .Handle<HttpRequestException>() |
| 33 | + }); |
| 34 | + |
| 35 | + pipeline.AddTimeout(TimeSpan.FromSeconds(15)); |
| 36 | + }); |
| 37 | +``` |
| 38 | + |
| 39 | +## HttpRetryStrategyOptions key properties |
| 40 | + |
| 41 | +| Property | Description | Default | |
| 42 | +|----------|-------------|---------| |
| 43 | +| `MaxRetryAttempts` | Number of retries (not attempts) | 3 | |
| 44 | +| `BackoffType` | `Constant`, `Linear`, `Exponential` | `Exponential` | |
| 45 | +| `Delay` | Base delay between attempts | 2 s | |
| 46 | +| `UseJitter` | Add randomness to spread retries | `true` | |
| 47 | +| `ShouldHandle` | What to retry on | 5xx, 408, 429, `HttpRequestException`, `TimeoutRejectedException` | |
| 48 | + |
| 49 | +## HttpCircuitBreakerStrategyOptions key properties |
| 50 | + |
| 51 | +| Property | Description | Default | |
| 52 | +|----------|-------------|---------| |
| 53 | +| `FailureRatio` | Fraction of failures to trip breaker | 0.1 (10 %) | |
| 54 | +| `MinimumThroughput` | Min requests before ratio applies | 100 | |
| 55 | +| `SamplingDuration` | Sliding window | 30 s | |
| 56 | +| `BreakDuration` | How long breaker stays open | 5 s | |
| 57 | + |
| 58 | +## TimeoutRejectedException gotcha |
| 59 | + |
| 60 | +When a retry wraps a timeout, Polly raises `TimeoutRejectedException` (not `TimeoutException`) when the attempt times out. If your `ShouldHandle` doesn't include it, the retry won't fire: |
| 61 | + |
| 62 | +```csharp |
| 63 | +// Wrong — TimeoutException is NOT what Polly throws |
| 64 | +.Handle<TimeoutException>() |
| 65 | + |
| 66 | +// Correct |
| 67 | +.Handle<TimeoutRejectedException>() |
| 68 | +// or just don't specify Handle<> for it — HttpRetryStrategyOptions handles it by default |
| 69 | +``` |
| 70 | + |
| 71 | +Using `HttpRetryStrategyOptions` (the HTTP-specific type) rather than `RetryStrategyOptions<HttpResponseMessage>` makes this easier — it comes with sensible defaults already including `TimeoutRejectedException`. |
| 72 | + |
| 73 | +## Dynamic reload from configuration |
| 74 | + |
| 75 | +Use the two-argument overload to reload options at runtime without restarting: |
| 76 | + |
| 77 | +```csharp |
| 78 | +services.AddHttpClient<SearchClient>() |
| 79 | + .AddResilienceHandler( |
| 80 | + "SearchPipeline", |
| 81 | + (pipeline, context) => |
| 82 | + { |
| 83 | + // Reloads whenever IOptionsMonitor<HttpRetryStrategyOptions>("SearchRetry") changes |
| 84 | + context.EnableReloads<HttpRetryStrategyOptions>("SearchRetry"); |
| 85 | + |
| 86 | + var retryOptions = context.GetOptions<HttpRetryStrategyOptions>("SearchRetry"); |
| 87 | + pipeline.AddRetry(retryOptions); |
| 88 | + }); |
| 89 | +``` |
| 90 | + |
| 91 | +Configure the named options in `appsettings.json` under the matching key and bind with `services.Configure<HttpRetryStrategyOptions>("SearchRetry", config.GetSection("SearchRetry"))`. |
| 92 | + |
| 93 | +## Per-authority circuit breaker |
| 94 | + |
| 95 | +If a named client talks to multiple host names (via routing or redirects), isolate circuit breaker state per authority so one unhealthy host doesn't trip the breaker for others: |
| 96 | + |
| 97 | +```csharp |
| 98 | +services.AddHttpClient("multi-region") |
| 99 | + .AddResilienceHandler("MultiRegionPipeline", pipeline => |
| 100 | + { |
| 101 | + pipeline.AddCircuitBreaker(new HttpCircuitBreakerStrategyOptions()); |
| 102 | + }) |
| 103 | + .SelectPipelineByAuthority(); |
| 104 | +``` |
0 commit comments