DEV Community

Juarez Júnior
Juarez Júnior

Posted on

Call Resilience with Polly

Polly is a library that helps add resilience to external calls in your application, providing mechanisms like retry, circuit breaker, fallback, and other resilience patterns. This is useful when your application needs to handle temporary failures in external services or networks. In this example, we will demonstrate how to implement a simple retry policy using Polly.

Libraries:

To use the Polly library, install the following NuGet package in your project:

Install-Package Polly
Enter fullscreen mode Exit fullscreen mode

Example Code:

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

class Program
{
    static async Task Main(string[] args)
    {
        // Defining a retry policy that retries 3 times with a 2-second interval between attempts
        var retryPolicy = Policy
            .Handle<HttpRequestException>()
            .WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(2), 
                (exception, timeSpan, retryCount, context) =>
                {
                    Console.WriteLine($"Attempt {retryCount} failed. Retrying in {timeSpan.TotalSeconds} seconds...");
                });

        // Making an HTTP call with retry
        HttpClient httpClient = new HttpClient();
        var url = "https://example-api.com/fail";

        try
        {
            await retryPolicy.ExecuteAsync(async () =>
            {
                Console.WriteLine("Making request...");
                var response = await httpClient.GetAsync(url);
                response.EnsureSuccessStatusCode();
                Console.WriteLine("Request succeeded!");
            });
        }
        catch (Exception ex)
        {
            Console.WriteLine($"All retry attempts failed: {ex.Message}");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Code Explanation:

In this example, we use Polly to define a retry policy that retries three times, waiting two seconds between each attempt, when an HttpRequestException occurs. The WaitAndRetryAsync function handles the retry logic and executes the HTTP call until it succeeds or the maximum number of retries is reached. If all retries fail, the exception is caught and displayed in the console.

Conclusion:

Polly is a powerful library for improving application resilience, providing a set of fault-handling patterns like retry, circuit breaker, and fallback. It allows your application to better handle temporary network or service failures, increasing robustness and reliability.

Source code: GitHub

Top comments (0)