IC Improve Code Recipes

Recipe 13.2 · C#

Timeouts, Retries and Circuit Breakers

Problem

The partner API is usually fast, but a few times a day it takes 40 seconds or returns a 503. Your pages hang for the full 100-second default timeout. When it goes down completely, every request waits, threads pile up, and your own site falls over with it.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

C#
// Not to copy: retries everything, blocks threads, hammers a dead server
for (int attempt = 1; attempt <= 3; attempt++)
{
    try
    {
        return client.GetStringAsync(url).Result;
    }
    catch (Exception)
    {
        Thread.Sleep(5000);
    }
}
throw new Exception("Service unavailable");

This retries a 400 Bad Request that will never succeed, sleeps a thread for 15 seconds per request, and keeps calling a server that is already down. Multiply it by a few hundred concurrent users and the retry loop is the outage.

The improved recipe

Microsoft.Extensions.Http.Resilience adds a standard pipeline to any HttpClient registered with the factory. It is built on Polly, and its defaults are sensible. Tune the numbers to your partner.

C#
using System;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Http.Resilience;
using Polly;

namespace ImproveCode.Http;

public static class ResilientCustomerApi
{
    public static IHttpClientBuilder AddResilientCustomerApi(
        this IServiceCollection services, IConfiguration configuration)
    {
        IHttpClientBuilder builder = services.AddCustomerApi(configuration);

        builder.AddStandardResilienceHandler(options =>
        {
            // Whole operation, including all retries.
            options.TotalRequestTimeout.Timeout = TimeSpan.FromSeconds(20);

            // Each individual attempt.
            options.AttemptTimeout.Timeout = TimeSpan.FromSeconds(5);

            options.Retry.MaxRetryAttempts = 3;
            options.Retry.Delay = TimeSpan.FromMilliseconds(500);
            options.Retry.BackoffType = DelayBackoffType.Exponential;
            options.Retry.UseJitter = true;
            options.Retry.DisableForUnsafeHttpMethods();

            options.CircuitBreaker.SamplingDuration =
                TimeSpan.FromSeconds(30);
            options.CircuitBreaker.FailureRatio = 0.5;
            options.CircuitBreaker.MinimumThroughput = 20;
            options.CircuitBreaker.BreakDuration =
                TimeSpan.FromSeconds(15);
        });

        return builder;
    }
}

For a service where a repeated call could do harm, such as a payment or a shipment booking, build a pipeline with a timeout and a circuit breaker but no retry:

C#
using System;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Http.Resilience;
using Polly;

namespace ImproveCode.Http;

public static class NoRetryResilience
{
    public static IHttpClientBuilder AddTimeoutAndBreakerOnly(
        this IHttpClientBuilder builder, TimeSpan timeout)
    {
        builder.AddResilienceHandler("timeout-breaker", pipeline =>
        {
            pipeline.AddTimeout(timeout);
            pipeline.AddCircuitBreaker(
                new HttpCircuitBreakerStrategyOptions
                {
                    SamplingDuration = TimeSpan.FromSeconds(60),
                    FailureRatio = 0.5,
                    MinimumThroughput = 10,
                    BreakDuration = TimeSpan.FromSeconds(30),
                });
        });

        return builder;
    }
}

How it works

The standard handler chains five strategies, from outside to inside: a rate limiter, the total request timeout, retry, the circuit breaker, and the per-attempt timeout. Each request passes through all five on the way out.

The two timeouts do different jobs. The attempt timeout cuts off one slow call so a retry can try again, perhaps on a healthier server behind the load balancer. The total timeout caps what the caller waits, retries included. HttpClient.Timeout from Recipe 13.1 still applies outside the pipeline, so keep it longer than the total timeout, or the client gives up before the pipeline does.

The retry strategy only retries what is worth retrying: network failures, timeouts, 408, 429 and 5xx responses. A 400 or 404 passes straight through. Exponential backoff with jitter spreads the retries out, so a thousand clients that failed at the same moment do not all retry at the same moment. A Retry-After header from the server is honored. DisableForUnsafeHttpMethods turns retries off for POST, PUT, PATCH and DELETE, because a request that timed out may still have succeeded on the server.

The circuit breaker watches the failure ratio over the sampling window. When at least MinimumThroughput calls have been made and half of them failed, it opens: for the next 15 seconds, calls fail immediately with a BrokenCircuitException instead of waiting. Your threads are freed, the struggling partner gets a break, and after the break duration a trial call decides whether to close the circuit again.

Variations and pitfalls

  • Package version. DisableForUnsafeHttpMethods is not in the earliest releases of the package. I compiled these listings against version 9.10.0. Pick the newest version whose dependencies match your target framework.
  • Sampling duration must be at least twice the attempt timeout. The options are validated at start-up, and an invalid combination throws. Change both together.
  • Apply defaults to every client. services.ConfigureHttpClientDefaults(b => b.AddStandardResilienceHandler()); gives every factory client the standard pipeline. Override it per client where needed.
  • Idempotency keys. If a partner supports an Idempotency-Key header, send a fresh GUID per logical operation and you can safely retry POST requests. Without it, don't.
  • Polly directly. For resilience around non-HTTP work, such as a database call or a file share, use the Polly.Core package and its ResiliencePipelineBuilder. Chapter 5 covers a simple retry with backoff for those cases.
  • Log the breaker. Configure options.CircuitBreaker.OnOpened to log a warning. An open circuit is the first sign of a partner outage, and you want to know before your users tell you.

On .NET Framework

Microsoft.Extensions.Http.Resilience targets modern .NET and .NET Standard 2.0, and with the factory it can run on .NET Framework 4.6.2 and later. In older code without the factory, use Polly v7's Policy.Handle<HttpRequestException>().WaitAndRetryAsync(...) and wrap each call in it.