Introduction

When building modern .NET applications, especially microservices or APIs that depend on external services (like APIs, databases, or third-party systems), failures are very common. These failures are often temporary, such as network issues, timeouts, or service overload. These are called transient faults.

Instead of failing immediately, a smart application should retry the operation after a short delay. This improves reliability and user experience.

This is where Polly comes in. Polly is a powerful .NET resilience and transient-fault-handling library that helps you implement retry policies, circuit breakers, timeouts, and more.

In this article, we will learn how to implement a Polly retry policy in .NET step by step using simple language and practical examples.

What is Polly in .NET?

Polly is a .NET library that allows developers to handle failures gracefully. It provides different resilience strategies like:

For this article, we will focus on the Retry Policy, which is the most commonly used feature.

What is a Retry Policy?

A retry policy means trying the same operation again if it fails due to a temporary issue.

For example:

Instead of showing an error immediately, the system retries automatically.

Why Use Polly Retry Policy?

Using Polly retry policy in .NET applications provides many benefits:

Step 1: Install Polly Package

First, you need to install the Polly NuGet package.

dotnet add package Polly

Or using Package Manager:

Install-Package Polly

Step 2: Create a Simple Retry Policy

Now let’s create a basic retry policy.

using Polly;

var retryPolicy = Policy
    .Handle<Exception>()
    .Retry(3);

Explanation:

Step 3: Execute Code with Retry Policy

Now use the retry policy to execute your code.

retryPolicy.Execute(() =>
{
    Console.WriteLine("Trying operation...");
    throw new Exception("Temporary failure");
});

This will retry the operation 3 times before finally throwing an exception.

Step 4: Add Wait Time Between Retries

Retrying immediately is not always good. It’s better to wait before retrying.

var retryPolicy = Policy
    .Handle<Exception>()
    .WaitAndRetry(3, retryAttempt => TimeSpan.FromSeconds(2));

Explanation:

Step 5: Use Exponential Backoff (Best Practice)

Exponential backoff increases delay after each retry.

var retryPolicy = Policy
    .Handle<Exception>()
    .WaitAndRetry(3, retryAttempt =>
        TimeSpan.FromSeconds(Math.Pow(2, retryAttempt))
    );

Example delays:

This reduces load on the system.

Step 6: Logging Retry Attempts

You can log each retry attempt.

var retryPolicy = Policy
    .Handle<Exception>()
    .WaitAndRetry(3,
        retryAttempt => TimeSpan.FromSeconds(2),
        (exception, timeSpan, retryCount, context) =>
        {
            Console.WriteLine($"Retry {retryCount} after {timeSpan.TotalSeconds}s due to {exception.Message}");
        });

This helps in debugging and monitoring.

Step 7: Using Polly with HttpClient (Real-World Example)

In ASP.NET Core, Polly is commonly used with HttpClient.

builder.Services.AddHttpClient("MyClient")
    .AddPolicyHandler(Policy
        .Handle<HttpRequestException>()
        .WaitAndRetryAsync(3, retryAttempt =>
            TimeSpan.FromSeconds(2)));

Now every HTTP call using this client will automatically retry.

Step 8: Handling Specific Exceptions

You should not retry all exceptions. Handle only specific ones.

var retryPolicy = Policy
    .Handle<HttpRequestException>()
    .Or<TimeoutException>()
    .Retry(3);

This avoids unnecessary retries.

Step 9: Async Retry Policy

For async code, use async version.

var retryPolicy = Policy
    .Handle<HttpRequestException>()
    .WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(2));

await retryPolicy.ExecuteAsync(async () =>
{
    await Task.Delay(100);
    throw new HttpRequestException("Temporary API failure");
});

Best Practices for Polly Retry Policy

Common Mistakes to Avoid

Real-World Use Cases

Summary

Polly retry policy in .NET is a powerful way to handle transient faults and improve application reliability. By retrying failed operations with proper delay and strategy, you can make your applications more resilient and user-friendly. Using features like WaitAndRetry, exponential backoff, and HttpClient integration, Polly helps you build production-ready .NET applications with minimal effort.