IC Improve Code Recipes

Recipe 5.6 · C#

Retry with Backoff (and Polly)

Problem

Some failures are transient: a deadlock victim, a dropped connection, a 503 from an overloaded API, a timeout during a failover. Trying again a moment later usually works. Without a retry, a nightly job fails for a two-second network blip. With a naive retry loop, a hundred clients hammer a recovering server in lockstep and keep it down.

The way it's often written

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

C#
// Not this: fixed delay, retries everything, blocks a thread,
// and throws away the original exception.
for (int i = 0; i < 5; i++)
{
    try
    {
        return CallService();
    }
    catch (Exception)
    {
        Thread.Sleep(1000);
    }
}
throw new Exception("Service failed after 5 tries");

The improved recipe

A small asynchronous helper with exponential backoff, jitter, a transient-error test and logging. When you need more (timeouts, circuit breakers, rate limiting), use Polly (Polly.Core).

C#
using System;
using System.Data.Common;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;

namespace ImproveCode.Errors;

public static class Retry
{
    public static async Task<T> ExecuteAsync<T>(
        Func<CancellationToken, Task<T>> operation,
        Func<Exception, bool> isTransient,
        int maxAttempts = 3,
        TimeSpan? baseDelay = null,
        ILogger? logger = null,
        CancellationToken ct = default)
    {
        ArgumentNullException.ThrowIfNull(operation);
        ArgumentNullException.ThrowIfNull(isTransient);
        ArgumentOutOfRangeException.ThrowIfLessThan(maxAttempts, 1);

        TimeSpan first = baseDelay ?? TimeSpan.FromMilliseconds(200);

        for (int attempt = 1; ; attempt++)
        {
            try
            {
                return await operation(ct);
            }
            catch (Exception ex) when (
                attempt < maxAttempts
                && !ct.IsCancellationRequested
                && isTransient(ex))
            {
                TimeSpan delay = Backoff(first, attempt);
                logger?.LogWarning(ex,
                    "Transient failure, attempt {Attempt} of " +
                    "{MaxAttempts}; retrying in {DelayMs} ms",
                    attempt, maxAttempts, (int)delay.TotalMilliseconds);
                await Task.Delay(delay, ct);
            }
        }
    }

    // 200 ms, 400 ms, 800 ms ... plus up to 100% jitter, max 30 s.
    private static TimeSpan Backoff(TimeSpan first, int attempt)
    {
        double ms = first.TotalMilliseconds * Math.Pow(2, attempt - 1);
        ms += Random.Shared.NextDouble() * ms;
        return TimeSpan.FromMilliseconds(Math.Min(ms, 30_000));
    }
}

public static class TransientErrors
{
    public static bool IsTransient(Exception ex) => ex switch
    {
        TimeoutException => true,
        HttpRequestException { StatusCode: null } => true, // network
        HttpRequestException { StatusCode: var code } =>
            code is HttpStatusCode.RequestTimeout
                or HttpStatusCode.TooManyRequests
                or HttpStatusCode.BadGateway
                or HttpStatusCode.ServiceUnavailable
                or HttpStatusCode.GatewayTimeout,
        DbException { IsTransient: true } => true,
        _ => false
    };
}

The same policy with Polly, plus an overall timeout per attempt:

C#
using System;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Polly;
using Polly.Retry;

namespace ImproveCode.Errors;

public static class ResiliencePipelines
{
    public static ResiliencePipeline CreateDefault(ILogger logger) =>
        new ResiliencePipelineBuilder()
            .AddRetry(new RetryStrategyOptions
            {
                ShouldHandle = new PredicateBuilder()
                    .Handle<TimeoutException>()
                    .Handle<HttpRequestException>(
                        TransientErrors.IsTransient),
                MaxRetryAttempts = 3,
                Delay = TimeSpan.FromMilliseconds(200),
                BackoffType = DelayBackoffType.Exponential,
                UseJitter = true,
                OnRetry = args =>
                {
                    logger.LogWarning(args.Outcome.Exception,
                        "Retry {Attempt} in {DelayMs} ms",
                        args.AttemptNumber + 1,
                        (int)args.RetryDelay.TotalMilliseconds);
                    return ValueTask.CompletedTask;
                }
            })
            .AddTimeout(TimeSpan.FromSeconds(10))
            .Build();
}

Usage:

C#
string json = await Retry.ExecuteAsync(
    token => http.GetStringAsync("https://api.example.com/rates", token),
    TransientErrors.IsTransient,
    maxAttempts: 4,
    logger: logger,
    ct: ct);

string again = await pipeline.ExecuteAsync(
    async token => await http.GetStringAsync(url, token), ct);

How it works

Each failed attempt waits twice as long as the one before, so a struggling server gets more room with every round. Jitter adds a random amount on top so that many clients that failed at the same moment don't all retry at the same moment. The cap keeps a misconfigured attempt count from producing hour-long waits.

The exception filter is the important part. The catch only runs when another attempt is allowed and the error is transient. On the last attempt, or for a non-transient error such as a 400 or a NullReferenceException, the filter returns false, the exception propagates untouched and the caller sees the real failure with its original stack trace. There is no "failed after 5 tries" wrapper that hides the cause.

TransientErrors is the policy for what deserves a retry. Timeouts, network failures with no HTTP status, and the standard "try again later" status codes do. A 400, 401 or 404 never succeeds on retry. DbException.IsTransient (added in .NET 6) lets ADO.NET providers that support it flag deadlocks and failover errors; check whether your provider sets it, and if not, test for its specific error numbers (for SQL Server, 1205 for a deadlock victim and the Azure SQL transient codes such as 40613).

Polly does the same with a declarative pipeline and adds strategies you shouldn't hand-roll: timeouts, circuit breakers that stop calling a service that is clearly down, hedging and rate limiting. Build the pipeline once and reuse it; it is thread-safe.

Variations and pitfalls

  • Only retry operations that are safe to repeat. A GET is; a POST that charges a card is not, unless the API supports an idempotency key. A database write inside a transaction that rolled back is safe to retry as a whole unit.
  • Keep total retry time well inside the caller's own timeout. Three retries of a 30-second call inside a 30-second HTTP request is a timeout with extra steps.
  • Retry at one layer only. If the HTTP client, the service and the job runner each retry three times, one failure becomes 27 calls.
  • For HttpClient, prefer Microsoft.Extensions.Http.Resilience and its AddStandardResilienceHandler(), which wires a Polly pipeline into IHttpClientFactory (Chapter 13).
  • Microsoft.Data.SqlClient also has built-in connection retry (ConnectRetryCount in the connection string) for the connection itself, not for commands.
  • Never use Thread.Sleep in a retry loop on a server. Task.Delay frees the thread while waiting and honors cancellation.