Configuring HttpClient resilience in .NET 10 with Microsoft.Extensions.Http.Resilience (the standard handler's strategies and defaults, attempt versus total timeout, no blind retries on unsafe methods, custom Polly pipelines) and testing it deterministically with WireMock.Net.
Add Microsoft.Extensions.Http.Resilience and call AddStandardResilienceHandler() on the HttpClient registration. It builds a Polly v8 pipeline. From outside in:
Retry-After),Use Retry.DisableForUnsafeHttpMethods() so POST and PATCH aren't retried. Retrying them blindly can charge a customer twice unless the API supports an idempotency key.
Test it with WireMock.Net: a scenario that returns 503, 503, then 200, and WithDelay for timeouts. Shrink the delays and thresholds in the test. The trade-off is that retries hide brief failures but add load and latency, so the total timeout has to cap them.
"In .NET 10 I don't hand-roll Polly policies any more. I add
Microsoft.Extensions.Http.Resilienceand callAddStandardResilienceHandler()on the typed client. That puts five Polly v8 strategies in aDelegatingHandler. From the outside in: a concurrency rate limiter, a 30-second total timeout, a retry with three attempts and jittered exponential back-off starting at 2 seconds, a circuit breaker, and a 10-second timeout per attempt. The order matters. The attempt timeout is inside the retry, so a hung call is cut off and retried. The total timeout is outside, so the user never waits longer than 30 seconds in total, back-off included. The retry handles 408, 429, 5xx,HttpRequestExceptionand timeouts, and it honoursRetry-After.The breaker's defaults are tuned for high traffic: a 10% failure ratio over 30 seconds, but only once there have been 100 requests, then it opens for 5 seconds and callers get
BrokenCircuitExceptionstraight away. For a low-volume partner API I lower the minimum throughput, or it will never open. I bind all of this from configuration per client. The one rule I never break: no blind retries on POST. If the first attempt reached the server and only the response was lost, a retry creates a second payment. So I callDisableForUnsafeHttpMethods(), or send an idempotency key the server deduplicates on. When the defaults don't fit,AddResilienceHandlerlets me build my own Polly pipeline, for example hedging for reads.To test it, I point the client at WireMock.Net. A scenario returns 503, 503, then 200, and I assert the call succeeded and WireMock logged three requests.
WithDelaytests the timeouts, and a stream of 503s tests that the breaker opens. In the test I shrink the delays to milliseconds and the breaker's minimum throughput to 2, so the tests run in well under a second. The mistake I see is trusting that the pipeline works because it compiles. You only find out it's wrong during an outage."
| Order (outer → inner) | Strategy | Default |
|---|---|---|
| 1 | Rate limiter | 1,000 concurrent requests, no queue |
| 2 | Total request timeout | 30 s for the whole call, including retries and back-off |
| 3 | Retry | 3 retries, exponential + jitter, base delay 2 s, Retry-After honoured |
| 4 | Circuit breaker | 10% failure ratio, 30 s sampling, min 100 requests, 5 s break |
| 5 | Attempt timeout | 10 s per try |
The options are validated at start-up. The total timeout must be longer than the attempt timeout, and the breaker's sampling duration must be at least twice the attempt timeout.
| Call | Retry? | Why |
|---|---|---|
| GET, HEAD, OPTIONS | Yes | Safe and idempotent |
| PUT, DELETE | Usually | Idempotent by definition, if the server implements them that way |
| POST, PATCH | Only with an idempotency key | A lost response looks like a failure, so a retry duplicates the effect |
A pricing service calling a partner API with p99 of about 400 ms, and around 0.5% transient 503s during their deployments, can cut user-visible errors from 0.5% to well under 0.05% with the standard handler. The total timeout keeps the worst case at a few seconds, rather than letting threads pile up behind a hung partner.
Checks whether the candidate understands the resilience pipeline (ordering, defaults, idempotency) and tests it rather than trusting configuration.
Green flags
AddStandardResilienceHandler and the order of its strategies, and can explain attempt versus total timeout.DisableForUnsafeHttpMethods.Red flags
Thread.Sleep or fixed delays.HttpClient instead of running the real handler chain.IHttpClientFactory builds a chain of DelegatingHandlers for each named or typed client. AddStandardResilienceHandler adds one handler that runs a Polly v8 ResiliencePipeline<HttpResponseMessage> around everything below it.
RatesClient.GetAsync
│
▼
[Rate limiter] → [Total timeout 30 s] → [Retry ×3] → [Circuit breaker] → [Attempt timeout 10 s]
│
SocketsHttpHandler → network
Each retry goes back through the breaker and gets a fresh attempt timeout. The total timeout's token cancels everything, including a back-off delay in progress.
Polly v8's retry uses DelayBackoffType.Exponential with UseJitter = true by default in the HTTP options. The delays grow about 2 s, 4 s, 8 s, randomised by the "decorrelated jitter" algorithm, so many clients don't retry in lockstep. ShouldHandle is a predicate over the outcome. The HTTP default treats HttpRequestException, TimeoutRejectedException, 408, 429 and status 500 and above as transient. With ShouldRetryAfterHeader the server's Retry-After replaces the computed delay.
The breaker samples outcomes in a sliding window (SamplingDuration). Once MinimumThroughput calls have happened in the window and the failure ratio reaches FailureRatio, it opens. For BreakDuration every call fails immediately with BrokenCircuitException, without touching the network. Then it goes half-open and lets one probe through: success closes it, failure opens it again. Its job is to protect the dependency and your threads, not to make a single call succeed.
AddStandardResilienceHandler(o => { o.Retry.MaxRetryAttempts = 2; ... }), or bind a configuration section such as Resilience:Rates.AddResilienceHandler("rates", b => b.AddTimeout(...).AddRetry(new HttpRetryStrategyOptions { ... })).AddStandardHedgingHandler() sends a second request when the first is slow, which helps p99 latency but doubles load on slow paths.Unit-testing Polly itself is pointless, because it's already tested. What you test is your configuration with your client: that a 503 is retried, that a POST isn't, that a slow response times out, and that a failing partner opens the breaker. WireMock.Net runs a real HTTP server on a random port, so the full handler chain runs. Shrink the time-based settings in tests, or inject a FakeTimeProvider through the pipeline's TimeProvider for full control.
o.Retry, o.CircuitBreaker and both timeouts at start-up to see the defaults.DisableForUnsafeHttpMethods() and prove a POST that gets a 503 is attempted only once.MinimumThroughput = 2, send failing calls and catch BrokenCircuitException. Check that WireMock's log stops growing while the breaker is open.Production registration, then xUnit v3 tests against WireMock.Net with shortened timings.
// ----- Program.cs (production) -----
builder.Services
.AddHttpClient<RatesClient>(c => c.BaseAddress = new Uri(builder.Configuration["Rates:BaseUrl"]!))
.AddStandardResilienceHandler(o =>
{
// Partner API is low volume: the default minimum of 100 requests would never trip.
o.CircuitBreaker.MinimumThroughput = 20;
o.Retry.DisableForUnsafeHttpMethods(); // never replay POST/PATCH blindly
});
// ----- Tests -----
#nullable enable
using System.Net;
using System.Net.Http.Json;
using Microsoft.Extensions.DependencyInjection;
using Polly.CircuitBreaker;
using Polly.Timeout;
using WireMock.RequestBuilders;
using WireMock.ResponseBuilders;
using WireMock.Server;
using Xunit;
namespace Pricing.Tests;
// Code under test: a typed client.
public sealed record Rate(string Currency, decimal Value);
public sealed class RatesClient(HttpClient http)
{
public Task<Rate?> GetAsync(string currency, CancellationToken ct) =>
http.GetFromJsonAsync<Rate>($"/rates/{currency}", ct);
public Task<HttpResponseMessage> PublishAsync(Rate rate, CancellationToken ct) =>
http.PostAsJsonAsync("/rates", rate, ct);
}
public sealed class RatesClientResilienceTests : IDisposable
{
private readonly WireMockServer _server = WireMockServer.Start(); // real HTTP on a random port
private RatesClient CreateClient(bool sensitiveBreaker = false)
{
var services = new ServiceCollection();
services.AddHttpClient<RatesClient>(c => c.BaseAddress = new Uri(_server.Url!))
.AddStandardResilienceHandler(o =>
{
// Same strategies as production, compressed timings so tests take milliseconds.
o.Retry.Delay = TimeSpan.FromMilliseconds(10);
o.Retry.DisableForUnsafeHttpMethods();
o.AttemptTimeout.Timeout = TimeSpan.FromMilliseconds(300);
o.TotalRequestTimeout.Timeout = TimeSpan.FromSeconds(2);
// Only the breaker test lowers the thresholds: with a minimum of 2 calls,
// the retry test's two 503s would open the breaker before the 200 arrives.
if (sensitiveBreaker)
{
o.CircuitBreaker.MinimumThroughput = 2;
o.CircuitBreaker.FailureRatio = 0.5;
}
});
return services.BuildServiceProvider().GetRequiredService<RatesClient>();
}
[Fact]
public async Task Transient_503s_are_retried_until_success()
{
// 503 → 503 → 200, driven by a WireMock scenario state machine.
_server.Given(Request.Create().WithPath("/rates/AUD").UsingGet())
.InScenario("flaky").WillSetStateTo("second")
.RespondWith(Response.Create().WithStatusCode(HttpStatusCode.ServiceUnavailable));
_server.Given(Request.Create().WithPath("/rates/AUD").UsingGet())
.InScenario("flaky").WhenStateIs("second").WillSetStateTo("third")
.RespondWith(Response.Create().WithStatusCode(HttpStatusCode.ServiceUnavailable));
_server.Given(Request.Create().WithPath("/rates/AUD").UsingGet())
.InScenario("flaky").WhenStateIs("third")
.RespondWith(Response.Create().WithBodyAsJson(new { currency = "AUD", value = 1.52m }));
var rate = await CreateClient().GetAsync("AUD", TestContext.Current.CancellationToken);
Assert.Equal(1.52m, rate!.Value);
Assert.Equal(3, _server.LogEntries.Count());
}
[Fact]
public async Task Post_is_not_retried()
{
_server.Given(Request.Create().WithPath("/rates").UsingPost())
.RespondWith(Response.Create().WithStatusCode(HttpStatusCode.ServiceUnavailable));
var response = await CreateClient().PublishAsync(new Rate("AUD", 1.5m), TestContext.Current.CancellationToken);
Assert.Equal(HttpStatusCode.ServiceUnavailable, response.StatusCode);
Assert.Single(_server.LogEntries); // a replay could have published twice
}
[Fact]
public async Task Slow_partner_hits_the_timeout()
{
// Each 300 ms attempt times out and is retried; after the last retry the caller sees the timeout.
_server.Given(Request.Create().WithPath("/rates/NZD").UsingGet())
.RespondWith(Response.Create().WithDelay(TimeSpan.FromSeconds(5)).WithStatusCode(200));
await Assert.ThrowsAsync<TimeoutRejectedException>(() =>
CreateClient().GetAsync("NZD", TestContext.Current.CancellationToken));
}
[Fact]
public async Task Breaker_opens_and_fails_fast()
{
_server.Given(Request.Create().WithPath("/rates/USD").UsingGet())
.RespondWith(Response.Create().WithStatusCode(HttpStatusCode.InternalServerError));
var client = CreateClient(sensitiveBreaker: true);
var ct = TestContext.Current.CancellationToken;
// Two failed attempts open the breaker; the next retry is rejected by it.
await Assert.ThrowsAsync<BrokenCircuitException>(() => client.GetAsync("USD", ct));
var callsWhenOpened = _server.LogEntries.Count();
// While open (5 s by default), calls fail without touching the network.
await Assert.ThrowsAsync<BrokenCircuitException>(() => client.GetAsync("USD", ct));
Assert.Equal(callsWhenOpened, _server.LogEntries.Count());
}
public void Dispose() => _server.Stop();
}
Retry.DisableForUnsafeHttpMethods(), or send an idempotency key the server deduplicates on.HttpClient.Timeout as well as the resilience timeouts. Why it is wrong: The client's 100-second default (or your value) wraps the whole pipeline and can fire first, with a confusing TaskCanceledException. Instead: Let the total request timeout own the overall budget, and leave HttpClient.Timeout larger or infinite.MinimumThroughput and SamplingDuration to real traffic.AddStandardResilienceHandler on top of an old Polly AddTransientHttpErrorPolicy. Why it is wrong: The retries multiply (4 × 4 = 16 attempts) and the timeouts conflict. Instead: Use one resilience handler per client.FakeTimeProvider.Resilience settings are a latency budget. Start from what the caller can afford, say 3 seconds, and work backwards: attempt timeout × attempts + back-off must fit inside the total. Then check the dependency can take the extra load from retries when it's already struggling. Retries amplify outages, and the breaker and jitter exist to stop that. I'd put the resilience metrics (retries, timeouts, breaker state) on the same dashboard as the dependency's latency, so you can see the policy working.
The standard handler covers about 90% of cases. I only build a custom pipeline for hedging, per-endpoint policies, or a fallback to cached data.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
AddStandardResilienceHandler |
Most outbound HTTP calls | Defaults may need tuning for low volume | You need per-endpoint behaviour |
AddStandardHedgingHandler |
Idempotent reads where p99 matters | Extra load on slow paths | Writes; a dependency already near capacity |
AddResilienceHandler (custom Polly) |
Fallbacks, unusual predicates, per-route policies | More code to test | The standard handler fits |
| No retries, timeout only | Non-idempotent calls with no idempotency key | Brief failures reach the user | Reads that could safely retry |
These are Gerard Meszaros's five test doubles:
I hand-roll a fake when the dependency holds state and many tests use it. Microsoft already ships two: FakeTimeProvider (Microsoft.Extensions.TimeProvider.Testing) and FakeLogger (Microsoft.Extensions.Diagnostics.Testing). One small class replaces dozens of fragile mock setups. The trade-off is that a fake is code you maintain. Mocks cost nothing to write, but they break whenever the implementation changes.
How to tell it (STAR)
**S:** During a payment provider incident our checkout charged some customers twice. **T:** I owned finding the cause and making sure it couldn't happen again. **A:** Correlating dependency calls in Application Insights showed our retry policy replaying POSTs that had timed out on our side but succeeded at the provider. I reproduced it with WireMock.Net, turned off retries for that client, then moved to the standard resilience handler with retries disabled for unsafe methods, and added the provider's idempotency key. I also added tests that prove a POST is sent exactly once. **R:** [n] affected orders were refunded within [time], and since then there have been [zero] duplicate charges across [number] later provider incidents.
Last updated 23 Nov 2026.