Add Retries and a Circuit Breaker to HttpClient in .NET

November 10, 2026 · 5 min read

On this page

If your app calls another API, that call is going to fail at some point. Usually it isn’t your fault. The other service restarts, the network drops for a second, or one request just hangs for no reason.

Most of us respond by wrapping the call in a loop and trying three times. It works, until you notice that the loop retries instantly, retries things that will never succeed, and keeps hitting a service that is already struggling.

.NET has a ready-made fix for this. It takes about three lines, and that’s what this post is about.

Install the package

You need .NET 8 or later and this package:

dotnet add package Microsoft.Extensions.Http.Resilience

It’s built on Polly, so you get the same battle-tested ideas without having to wire them up yourself.

Turn it on

Add one call when you register your HttpClient:

using Microsoft.Extensions.Http.Resilience;

var builder = WebApplication.CreateBuilder(args);

builder.Services
    .AddHttpClient("catalog", c => c.BaseAddress = new Uri("https://catalog.example.com"))
    .AddStandardResilienceHandler();

var app = builder.Build();
app.Run();

That’s it. Every request through the catalog client now has retries, timeouts and a circuit breaker around it.

What you get

The handler wraps each request in five layers. A rate limiter keeps you from sending too many requests at once. A total timeout puts a ceiling on the whole call, retries included. Then come the retries themselves, which wait a bit longer each time. The circuit breaker steps in when too many calls fail and pauses traffic for a few seconds, so the other service gets a chance to recover. Last, each single attempt has its own timeout, so one slow call can’t eat your whole budget.

Only temporary problems are retried: network errors, timeouts, 5xx responses, 408 and 429. A 404 or a 400 isn’t retried, because asking again won’t change the answer.

The defaults are 3 retries with exponential backoff, 10 seconds per attempt and 30 seconds in total. I’d check Microsoft’s docs for the current numbers, since defaults can change between versions.

Using the client

Your calling code doesn’t change. Get the client from the factory and use it like before:

app.MapGet("/products", async (IHttpClientFactory factory, CancellationToken ct) =>
{
    var client = factory.CreateClient("catalog");
    var response = await client.GetAsync("/products", ct);

    response.EnsureSuccessStatusCode();
    return Results.Content(await response.Content.ReadAsStringAsync(ct), "application/json");
});

Pass the CancellationToken through. If the user closes the page, you don’t want retries carrying on in the background.

Changing the defaults

The defaults are fine to start with. If your service needs something different, you can adjust the options:

builder.Services
    .AddHttpClient("catalog", c => c.BaseAddress = new Uri("https://catalog.example.com"))
    .AddResilienceHandler("retry", (pipeline, context) =>
{
    var loggerFactory = context.ServiceProvider?.GetService<ILoggerFactory>();
    var logger = loggerFactory?.CreateLogger("EmailServiceResilience");


    // 1. RATE LIMITER (Outermost - Control request flow)
    pipeline.AddRateLimiter(new HttpRateLimiterStrategyOptions
    {
        // Define the RateLimiter algorithm
        DefaultRateLimiterOptions = new ConcurrencyLimiterOptions
        {
            PermitLimit = 10,        // Maximum 10 concurrent HTTP requests active at once
            QueueLimit = 5,          // Up to 5 additional requests can wait in queue
            QueueProcessingOrder = QueueProcessingOrder.OldestFirst
        },
        OnRejected = args =>
        {
            logger.LogWarning("[RateLimiter] Request rejected! Concurrency/Queue limit exceeded.");
            return ValueTask.CompletedTask;
        }
    });

    // 2. TOTAL REQUEST TIMEOUT (Global cap across all retries)
    pipeline.AddTimeout(new HttpTimeoutStrategyOptions
    {
        Timeout = TimeSpan.FromSeconds(30),
        OnTimeout = args =>
        {
            logger.LogError("[TotalTimeout] Entire operation exceeded global deadline of {Timeout}s.",
                args.Timeout.TotalSeconds);
            return ValueTask.CompletedTask;
        }
    });

    // 3. RETRY (Recover from transient failures)
    pipeline.AddRetry(new HttpRetryStrategyOptions
    {
        MaxRetryAttempts = 3,
        Delay = TimeSpan.FromSeconds(2),
        UseJitter = true,
        BackoffType = DelayBackoffType.Exponential,
        OnRetry = args =>
        {
            // Log as Warning (not Error), because a retry means we are still attempting to recover
            logger?.LogWarning(
                "Retry attempt {Attempt}. Delay: {Delay}ms. Cause: {Reason}",
                args.AttemptNumber + 1,
                args.RetryDelay.TotalMilliseconds,
                args.Outcome.Exception?.Message ?? args.Outcome.Result?.StatusCode.ToString());

            return ValueTask.CompletedTask;
        }
    });

    // 4. CIRCUIT BREAKER (Evaluates EACH individual attempt inside the retry loop)
    pipeline.AddCircuitBreaker(new HttpCircuitBreakerStrategyOptions
    {
        FailureRatio = 0.5,
        MinimumThroughput = 3,
        SamplingDuration = TimeSpan.FromSeconds(30),
        BreakDuration = TimeSpan.FromSeconds(10),
        OnOpened = args =>
        {
            logger.LogCritical("[CircuitBreaker] Circuit TRIPPED OPEN for {BreakDuration}s due to high failure rate.",
                args.BreakDuration.TotalSeconds);
            return ValueTask.CompletedTask;
        },
        OnClosed = args =>
        {
            logger.LogInformation("[CircuitBreaker] Circuit CLOSED. Service recovered.");
            return ValueTask.CompletedTask;
        },
        OnHalfOpened = args =>
        {
            logger.LogInformation("[CircuitBreaker] Circuit HALF-OPEN. Testing service health with next request...");
            return ValueTask.CompletedTask;
        }
    });

    // 5. ATTEMPT TIMEOUT (Innermost - Stops a single hanging network attempt after 10s)
    pipeline.AddTimeout(new HttpTimeoutStrategyOptions
    {
        Timeout = TimeSpan.FromSeconds(10),
        OnTimeout = args =>
        {
            logger.LogWarning("[AttemptTimeout] Single HTTP request attempt timed out after {Timeout}s.",
                args.Timeout.TotalSeconds);
            return ValueTask.CompletedTask;
        }
    });
});

Keep the numbers sensible relative to each other. The total timeout has to be longer than a single attempt. If the values contradict each other, the app throws a validation error on startup, which is better than finding out in production.

Be careful with POST requests

This one matters more than the rest.

A GET is safe to repeat. A POST that creates an order isn’t. If the first attempt actually went through but the response got lost, the retry creates a second order, and the customer is charged twice.

Unless the endpoint can handle duplicates, switch retries off for requests that change data:

.AddStandardResilienceHandler(options =>
{
    options.Retry.DisableForUnsafeHttpMethods();
});

If you do need to retry writes, ask the API owner to support an idempotency key, so a repeated request is recognised and ignored.

Video And Source Code

I also covered the retry pattern in a video, if you’d rather watch it:

Also, the entire source can be downloaed using : https://github.com/rahulpandey15/TodoAPI.git

Wrapping up

Install the package, add AddStandardResilienceHandler(), and turn off retries for anything that writes data unless it’s safe to repeat. That covers most apps.

If you’re setting this up on a real project and want a second pair of eyes, you can request a one-to-one session and we’ll go through it together.