📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

How do you configure and test retries, timeouts and circuit breakers for an HttpClient in .NET 10?

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.

Mid-Level Coding Intermediate circuit-breaker httpclient polly resilience testing wiremock-net

🎯 Key points

  • AddStandardResilienceHandler (Polly v8): rate limiter → total timeout 30 s → retry → circuit breaker → attempt timeout 10 s
  • Retry defaults: 3 retries, exponential back-off with jitter from 2 s; retries 408, 429, 5xx, HttpRequestException, timeouts; honours Retry-After
  • Circuit breaker defaults: 10% failure ratio over 30 s, minimum 100 requests, break 5 s; throws BrokenCircuitException
  • Attempt timeout bounds one try; total timeout bounds the whole call including back-off
  • No blind retries on POST/PATCH: Retry.DisableForUnsafeHttpMethods() or an idempotency key
  • AddResilienceHandler(name, builder => ...) for a custom Polly pipeline when the defaults don't fit
  • Test with WireMock.Net: scenario 503, 503, 200; WithDelay for timeouts; shrink delays and thresholds in the test

⏱ 30-second answer

Add Microsoft.Extensions.Http.Resilience and call AddStandardResilienceHandler() on the HttpClient registration. It builds a Polly v8 pipeline. From outside in:

  • a rate limiter,
  • a total timeout (30 s),
  • a retry (3 retries, exponential back-off with jitter from 2 s, honours Retry-After),
  • a circuit breaker (opens at a 10% failure ratio over 30 s, once there have been at least 100 requests, for 5 s),
  • an attempt timeout (10 s) for each try.

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.

🗣 Full answer (senior)

How I would answer this in an interview

"In .NET 10 I don't hand-roll Polly policies any more. I add Microsoft.Extensions.Http.Resilience and call AddStandardResilienceHandler() on the typed client. That puts five Polly v8 strategies in a DelegatingHandler. 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, HttpRequestException and timeouts, and it honours Retry-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 BrokenCircuitException straight 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 call DisableForUnsafeHttpMethods(), or send an idempotency key the server deduplicates on. When the defaults don't fit, AddResilienceHandler lets 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. WithDelay tests 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."


The standard pipeline and its defaults

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.

Which calls to retry

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

Production example

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.

🔍 What the interviewer is checking

Checks whether the candidate understands the resilience pipeline (ordering, defaults, idempotency) and tests it rather than trusting configuration.

Green flags

  • Knows AddStandardResilienceHandler and the order of its strategies, and can explain attempt versus total timeout.
  • Quotes or roughly knows the defaults and tunes the breaker for low-volume APIs.
  • Refuses blind retries on POST and mentions idempotency keys or DisableForUnsafeHttpMethods.
  • Tests with WireMock.Net scenarios and delays using compressed timings.

Red flags

  • Hand-rolled retry loops with Thread.Sleep or fixed delays.
  • Retries everything, including 400s and POSTs.
  • No tests, or tests that mock HttpClient instead of running the real handler chain.

📚 Learn in depth

1. Where the pipeline sits

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.

2. Retry internals

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.

3. Circuit breaker internals

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.

4. Customising

  • Tune the standard handler: AddStandardResilienceHandler(o => { o.Retry.MaxRetryAttempts = 2; ... }), or bind a configuration section such as Resilience:Rates.
  • Build your own pipeline: AddResilienceHandler("rates", b => b.AddTimeout(...).AddRetry(new HttpRetryStrategyOptions { ... })).
  • Hedging for reads: AddStandardHedgingHandler() sends a second request when the first is slow, which helps p99 latency but doubles load on slow paths.
  • Telemetry: the resilience library emits metrics and logs for each retry, timeout and breaker state change. Send them to Application Insights through OpenTelemetry, so you can see the breaker opening during an incident.

5. Testing strategy

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.

Try it yourself

  1. Register a typed client with the standard handler and log o.Retry, o.CircuitBreaker and both timeouts at start-up to see the defaults.
  2. Write a WireMock.Net scenario that returns 503 twice, then 200, and assert three log entries.
  3. Add DisableForUnsafeHttpMethods() and prove a POST that gets a 503 is attempted only once.
  4. Set MinimumThroughput = 2, send failing calls and catch BrokenCircuitException. Check that WireMock's log stops growing while the breaker is open.
  5. Export the resilience metrics with OpenTelemetry and watch them in the Aspire dashboard while the tests run.

💻 Code

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();
}

⚠ Common mistakes

  • Mistake: Retrying POST or PATCH by default. Why it is wrong: If the first attempt reached the server and only the response was lost, the retry repeats the side effect (a double charge or a duplicate order). Instead: Call Retry.DisableForUnsafeHttpMethods(), or send an idempotency key the server deduplicates on.
  • Mistake: Setting 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.
  • Mistake: Keeping the breaker's minimum throughput of 100 for a low-volume API. Why it is wrong: With a few requests a minute it never opens, so callers keep waiting on a dead dependency. Instead: Size MinimumThroughput and SamplingDuration to real traffic.
  • Mistake: Stacking 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.
  • Mistake: Testing with production timings. Why it is wrong: Back-off of 2, 4 and 8 seconds makes the suite slow, so people stop running the tests. Instead: Compress the delays and thresholds in the test registration, or use FakeTimeProvider.
  • Mistake: Not testing the configuration at all. Why it is wrong: A wrong predicate or ordering only shows up during an outage. Instead: Write WireMock.Net tests for the retry, the no-retry on POST, the timeout and the breaker.
  • Mistake: Retrying 4xx responses such as 400 or 404. Why it is wrong: They won't succeed on retry and they just add load. Instead: Keep the default transient predicate (408, 429, 5xx, network errors and timeouts).

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate suggests mocking HttpClient instead of using WireMock.Net. Why: Checks they know which test double fits HTTP dependencies.
    How to answer

    These are Gerard Meszaros's five test doubles:

    • A dummy only fills a parameter and is never used.
    • A stub returns canned answers so the code takes a particular path.
    • A fake is a simplified implementation that really works, such as an in-memory repository. You check its state, not the calls made on it.
    • A mock is set up with expected calls and then verifies the interaction. A spy records calls so you can assert on them afterwards.

    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.

🛠 Real-world problems: how you handle them

Retries on a payment POST created duplicate charges during a partner outage
Situation
A checkout service [scale, e.g. n orders per day] called a payment provider through an HttpClient with a copy-pasted retry policy that retried every 5xx and timeout, POST included.
Signals
Customer complaints about double charges, a spike in duplicate provider transaction ids for one order id, and Application Insights showing repeated POST /payments dependency calls with timeouts on the first attempt during the provider's [date] incident.
Investigation
Correlated the dependency telemetry by operation id: the first POST timed out on our side after the provider had already accepted it, then the retry sent a second charge. Reviewed the pipeline registration and found no method filter and no idempotency key. Reproduced it with WireMock.Net: a delayed 200 longer than the attempt timeout produced two POSTs.
Resolution
Immediate: turned off retries for the payments client and refunded the duplicates. Long term: moved to AddStandardResilienceHandler with Retry.DisableForUnsafeHttpMethods(), added the provider's idempotency key header (order id plus attempt), and set the timeouts from a latency budget.
Prevention
WireMock.Net tests asserting a POST is sent exactly once on 503 and on timeout; a code-review checklist item for retries on unsafe methods; alerts on duplicate provider transaction ids; and an ADR on idempotency for outbound writes.

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.

↩ Usually asked after

More in .NET Testing Tools

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me