How to Use AddStandardResilienceHandler with IHttpClientFactory in C# and .NET

Calling an external REST API with HttpClient without timeouts or transient-fault handling works fine on localhost—until a downstream payment or webhook provider stalls for 90 seconds, exhausts your thread pool, or throws sporadic 503 responses under load. Writing custom DelegatingHandler retry loops by hand is error-prone (and often omits jitter or circuit breakers). With Microsoft.Extensions.Http.Resilience, a single .AddStandardResilienceHandler() call on IHttpClientFactory wires up a battle-tested Polly v8 resilience pipeline.

Editorial illustration of AddStandardResilienceHandler pipeline in .NET IHttpClientFactory

Editorial illustration: AddStandardResilienceHandler() wraps outbound HttpClient calls with rate limiting, total timeout, retries, circuit breaker, and per-attempt timeout.

Summary

  • AddStandardResilienceHandler() (in the Microsoft.Extensions.Http.Resilience NuGet package, built on Polly v8 for .NET 8 and newer) attaches a five-layer resilience pipeline to IHttpClientFactory clients: Rate Limiter, Total Request Timeout, Retry (with exponential backoff and jitter), Circuit Breaker, and Attempt Timeout.
  • Per Microsoft Learn’s HTTP resilience guide, add only one resilience handler per HttpClient—never stack multiple .AddStandardResilienceHandler() calls on top of each other.
  • If you configure global defaults via ConfigureHttpClientDefaults() and need a different pipeline (such as AddStandardHedgingHandler()) on one named client, call .RemoveAllResilienceHandlers() first.
  • Be cautious with retries on POST/PATCH mutations: only retry non-idempotent requests if the remote API supports idempotency keys, or customize Retry.DisableForUnsafeHttpMethods().

Prerequisites: NuGet Package & .NET Runtime

  • NuGet Package (Microsoft.Extensions.Http.Resilience): Install Microsoft.Extensions.Http.Resilience in .NET 8, .NET 9, .NET 10, or .NET 11 projects (ASP.NET Core Web APIs, Worker Services, or console apps using Generic Host).
  • C# & IDE: Works cleanly with typed clients and primary constructors (C# 12+) in Visual Studio 2022/2026 or VS Code with the .NET SDK.

Practical example: Configuring a typed HttpClient with resilience

First, add the typed client and .AddStandardResilienceHandler() in Program.cs:

using Microsoft.Extensions.Http.Resilience;

var builder = WebApplication.CreateBuilder(args);

builder.Services
    .AddHttpClient<IPaymentsGateway, PaymentsGateway>(client =>
    {
        client.BaseAddress = new Uri("https://api.payments.example/");
    })
    .AddStandardResilienceHandler(options =>
    {
        // Cap each individual attempt and the overall operation
        options.AttemptTimeout.Timeout = TimeSpan.FromSeconds(5);
        options.TotalRequestTimeout.Timeout = TimeSpan.FromSeconds(20);

        // Customize retry count if needed
        options.Retry.MaxRetryAttempts = 3;
    });

Inside PaymentsGateway, inject HttpClient normally—you do not write any retry loops in your business service:

public interface IPaymentsGateway
{
    Task<string?> GetStatusAsync(string referenceId, CancellationToken ct);
}

public sealed class PaymentsGateway(HttpClient httpClient) : IPaymentsGateway
{
    public async Task<string?> GetStatusAsync(string referenceId, CancellationToken ct)
    {
        using var response = await httpClient.GetAsync($"v1/status/{Uri.EscapeDataString(referenceId)}", ct);
        response.EnsureSuccessStatusCode();
        return await response.Content.ReadAsStringAsync(ct);
    }
}

Replacing global defaults cleanly (RemoveAllResilienceHandlers)

As highlighted in Microsoft Learn’s HTTP resilience patterns, if your project registers a default resilience handler for all clients via ConfigureHttpClientDefaults(...) and one specific client needs hedging or custom strategies instead, remove the inherited handlers first:

builder.Services.ConfigureHttpClientDefaults(http =>
{
    http.AddStandardResilienceHandler();
});

builder.Services
    .AddHttpClient("fast-read")
    .RemoveAllResilienceHandlers()
    .AddStandardHedgingHandler();

Calling RemoveAllResilienceHandlers() prevents accidentally stacking two nested retry/timeout pipelines on the "fast-read" client.

When NOT to retry blindly

  1. Non-idempotent POST payments or order creations: If the server processed a POST request and timed out just before returning 200 OK, retrying without an Idempotency-Key header can charge a customer twice! Either pass an idempotency key or disable retries on unsafe HTTP methods (DisableForUnsafeHttpMethods()).
  2. 4xx client errors (400, 401, 403, 404): Transient fault handlers intentionally do not retry permanent client errors (except 408 Request Timeout and 429 Too Many Requests), because retrying bad credentials or malformed JSON only wastes quota.

For related .NET service patterns, see testing time-dependent C# code with TimeProvider and FakeTimeProvider and using Keyed Services in .NET Dependency Injection.

Common mistakes

  • Setting HttpClient.Timeout shorter than TotalRequestTimeout. When using AddStandardResilienceHandler(), let TotalRequestTimeout and AttemptTimeout govern timeouts cleanly—a tiny HttpClient.Timeout can cancel the outer operation prematurely before retries finish.
  • Stacking .AddStandardResilienceHandler() twice (for example, once in ConfigureHttpClientDefaults and again on a named client without RemoveAllResilienceHandlers()). That multiplies retry counts exponentially (3 × 3 = 9+ attempts!).
  • Retrying POST calls that lack idempotency protection on external billing or email APIs.
  • Instantiating new HttpClient() manually inside a using block instead of using IHttpClientFactory. IHttpClientFactory manages HttpMessageHandler pooling, DNS refresh, and resilience pipelines automatically.

Why this matters

External HTTP calls are the #1 source of cascading latency in microservices and web APIs. Using AddStandardResilienceHandler() gives every outbound client sensible timeouts, jittered backoff, and circuit breaking out of the box without maintaining custom retry code.

My Take

Add Microsoft.Extensions.Http.Resilience and .AddStandardResilienceHandler() to every IHttpClientFactory registration calling third-party APIs—tuning AttemptTimeout and TotalRequestTimeout to match your SLA, and disabling retries on unsafe POST endpoints unless the API honors idempotency keys.

Conclusion

Install Microsoft.Extensions.Http.Resilience, register .AddStandardResilienceHandler() once per IHttpClientFactory client (calling .RemoveAllResilienceHandlers() before overriding global defaults), tune AttemptTimeout and TotalRequestTimeout, and protect POST retries with idempotency keys or DisableForUnsafeHttpMethods().

Sources