0Pricing
C# Academy · Lesson

Retry Policies

Retry transient failures with backoff.

Retry Policies is a free C# Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the C# Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

What Is Polly?

Polly is a .NET resilience library that helps your apps cope with transient failures, slow responses and overloaded dependencies. It provides strategies like retry, circuit breaker, timeout, fallback and rate limiting.

This course uses Polly v8 (the Polly.Core API).

dotnet add package Polly.Core

Why Retry?

Many failures are transient: a brief network blip, a momentary timeout, a service restarting. Retrying the operation a moment later often succeeds without bothering the user.

Retry should target transient errors only, never permanent ones like a 404.

A Basic Retry Strategy

In Polly v8 you build a ResiliencePipeline with a RetryStrategyOptions. By default a thrown exception triggers a retry.

using Polly;
using Polly.Retry;

var pipeline = new ResiliencePipelineBuilder()
    .AddRetry(new RetryStrategyOptions
    {
        MaxRetryAttempts = 3
    })
    .Build();

Executing Through The Pipeline

Wrap the risky call with ExecuteAsync. Polly runs it, and if it throws, retries up to the configured count.

await pipeline.ExecuteAsync(async token =>
{
    await httpClient.GetAsync("https://api.example.com/data", token);
});

Deciding What To Retry

Use ShouldHandle with a predicate builder to retry only specific exceptions or results, avoiding retries on permanent errors.

new RetryStrategyOptions<HttpResponseMessage>
{
    ShouldHandle = new PredicateBuilder<HttpResponseMessage>()
        .Handle<HttpRequestException>()
        .HandleResult(r => r.StatusCode == HttpStatusCode.ServiceUnavailable),
    MaxRetryAttempts = 3
};

Constant vs Exponential Backoff

Retrying instantly can hammer a struggling service. Backoff spaces out attempts. Polly supports Constant, Linear and Exponential backoff via the BackoffType setting.

Exponential Backoff

Exponential backoff doubles the delay each attempt (for example 2s, 4s, 8s). Set BackoffType.Exponential with a base Delay.

new RetryStrategyOptions
{
    MaxRetryAttempts = 4,
    BackoffType = DelayBackoffType.Exponential,
    Delay = TimeSpan.FromSeconds(2)
};

Adding Jitter

If many clients retry on the same schedule they create synchronized spikes (the "thundering herd"). Jitter adds randomness to delays. Enable UseJitter = true.

new RetryStrategyOptions
{
    MaxRetryAttempts = 4,
    BackoffType = DelayBackoffType.Exponential,
    Delay = TimeSpan.FromSeconds(1),
    UseJitter = true
};

Reacting On Each Retry

The OnRetry callback lets you log attempts or emit metrics. It receives the attempt number and the failure that triggered it.

new RetryStrategyOptions
{
    MaxRetryAttempts = 3,
    OnRetry = args =>
    {
        Console.WriteLine($"Retry {args.AttemptNumber} after {args.RetryDelay}");
        return default;
    }
};

Limiting Total Retry Time

Unbounded retries can keep a user waiting too long. Combine retry with a timeout strategy (covered later) or cap attempts so the operation fails fast when recovery is unlikely.

Retry For HttpClient

For HTTP calls, register a resilience handler on the HttpClient so retries apply to every request automatically.

builder.Services.AddHttpClient("api")
    .AddResilienceHandler("retry", pipeline =>
    {
        pipeline.AddRetry(new HttpRetryStrategyOptions
        {
            MaxRetryAttempts = 3,
            BackoffType = DelayBackoffType.Exponential
        });
    });

Quick Check

Test your retry knowledge.

Recap

Retry policies handle transient failures by reattempting an operation. In Polly v8 you build a pipeline with AddRetry, scope it with ShouldHandle, and space attempts using BackoffType.Exponential plus UseJitter. Use OnRetry to observe attempts, and register a resilience handler to protect every HttpClient call.

Frequently asked questions

Is the “Retry Policies” lesson free?

Yes — the full text of “Retry Policies” is free to read here on the web, and the C# Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the C# Academy course, upgrade to CoddyKit PRO.

What will I learn in “Retry Policies”?

Retry transient failures with backoff. You practise C# Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start C# Academy?

No prior experience is required. C# Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Retry Policies” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this C# Academy lesson?

Yes. Every C# Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Retry Policies
  2. Circuit Breaker Pattern
  3. Timeout and Fallback Policies
  4. Resilience Pipelines
← Back to C# Academy