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:

  • Retry

  • Circuit Breaker

  • Timeout

  • Fallback

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:

  • API call fails due to network issue → retry

  • Database connection times out → retry

  • External service returns error → retry

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:

  • Improves application reliability

  • Handles temporary failures automatically

  • Reduces manual error handling code

  • Enhances user experience

  • Works well in microservices architecture

Step 1: Install Polly Package

First, you need to install the Polly NuGet package.

Bash
dotnet add package Polly

Or using Package Manager:

PowerShell
Install-Package Polly

Step 2: Create a Simple Retry Policy

Now let’s create a basic retry policy.

C#
using Polly;

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

Explanation:

  • Handle() → retry for any exception

  • Retry(3) → retry 3 times if it fails

Step 3: Execute Code with Retry Policy

Now use the retry policy to execute your code.

C#
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.

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

Explanation:

  • WaitAndRetry → waits before retrying

  • 3 → number of retries

  • TimeSpan → delay between retries

Step 5: Use Exponential Backoff (Best Practice)

Exponential backoff increases delay after each retry.

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

Example delays:

  • 1st retry → 2 seconds

  • 2nd retry → 4 seconds

  • 3rd retry → 8 seconds

This reduces load on the system.

Step 6: Logging Retry Attempts

You can log each retry attempt.

C#
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.

C#
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.

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

This avoids unnecessary retries.

Step 9: Async Retry Policy

For async code, use async version.

C#
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

  • Use exponential backoff for better performance

  • Retry only transient faults

  • Avoid infinite retries

  • Combine with circuit breaker for better resilience

  • Log retry attempts for monitoring

Common Mistakes to Avoid

  • Retrying permanent failures

  • Too many retries causing delays

  • No logging for retries

  • Using retry without delay

Real-World Use Cases

  • Calling external APIs

  • Database connection retries

  • Microservices communication

  • Cloud-based applications

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.