Polly: A Resilience and Fault-Handling Library for .NET

 

Polly: A Resilience and Fault-Handling Library for .NET

Introduction

In modern software development, applications must be resilient to failures, such as network timeouts, transient errors, and service disruptions. Polly is a powerful .NET library that helps developers implement resilience strategies, including retries, circuit breakers, timeouts, and more.

What is Polly?

Polly is an open-source .NET library that provides policies for handling transient faults and improving system reliability. It allows developers to define robust error-handling strategies in a declarative and flexible way.

Key Features of Polly

  • Retry Policies – Automatically retry failed operations.
  • Circuit Breaker – Temporarily stop execution when failures exceed a threshold.
  • Timeouts – Limit execution time to avoid long waits.
  • Fallback – Provide an alternative response when an operation fails.
  • Bulkhead Isolation – Limit concurrent requests to prevent overload.
  • Cache – Store responses to avoid repeated expensive operations.
  • Integration with .NET Core & HttpClientFactory – Works seamlessly with modern .NET applications.

Installing Polly

To use Polly in a .NET project, install the NuGet package:

dotnet add package Polly

For HTTP client resilience, use:

dotnet add package Microsoft.Extensions.Http.Polly

How to Use Polly

1. Retry Policy

The following example retries an HTTP request three times before failing:

using Polly;
using Polly.Retry;
using System;
using System.Net.Http;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        var retryPolicy = Policy
            .Handle<HttpRequestException>()
            .WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(retryAttempt));

        var httpClient = new HttpClient();
        
        await retryPolicy.ExecuteAsync(async () =>
        {
            var response = await httpClient.GetAsync("https://example.com");
            response.EnsureSuccessStatusCode();
            Console.WriteLine("Request successful!");
        });
    }
}

2. Circuit Breaker Pattern

A circuit breaker prevents repeated execution when failures occur. This example opens the circuit after two consecutive failures and waits 30 seconds before retrying:

var circuitBreakerPolicy = Policy
    .Handle<HttpRequestException>()
    .CircuitBreakerAsync(2, TimeSpan.FromSeconds(30));

await circuitBreakerPolicy.ExecuteAsync(async () =>
{
    var response = await httpClient.GetAsync("https://example.com");
    response.EnsureSuccessStatusCode();
});

3. Timeout Policy

To limit execution time and prevent long waits:

var timeoutPolicy = Policy.TimeoutAsync<HttpResponseMessage>(10); // 10 seconds timeout

await timeoutPolicy.ExecuteAsync(async () =>
{
    var response = await httpClient.GetAsync("https://example.com");
});

Polly with HttpClientFactory

Polly integrates with HttpClientFactory in .NET Core, allowing centralized resilience policies for HTTP requests:

services.AddHttpClient("MyClient")
    .AddPolicyHandler(Policy.TimeoutAsync<HttpResponseMessage>(5))
    .AddPolicyHandler(Policy.Handle<HttpRequestException>()
        .RetryAsync(3));

Conclusion

Polly is a must-have library for any .NET developer building resilient applications. By implementing retries, circuit breakers, timeouts, and fallbacks, developers can handle failures gracefully and improve system stability.

Comments