Polly Retry Policies and Error handling in C# .NET

Polly Retry Policies and Error handling in C# .NET

resilient http call retries Polly Polly Retry Policies and Error handling in C NET

Today in this article, we shall see how to implement Polly Retry Policies and Error handling in C# .NET

We will cover the below aspects in today’s article,

Polly is an advanced .NET library that provides resiliency and fault-handling capabilities.

This library integrates IHttpClientFactory and provides effective transient-fault handling and resiliency through policies such as.

  • Retry,
  • Circuit Breaker,
  • Timeout,
  • Bulkhead Isolation, and
  • Fallback.

If you have a requirement, for adding a resilient request then the client request can retry by attempting to send the request a few more times.

Such retries generally resolve the issues in the case of transient errors giving the desired result for the request. Additionally, other policies like Circuit Breaker or timeout policies can be applied.

Errors are expected – Transient Fault Handling

A transient error or transient fault is the most common type of error which occurs and is most of the time-resolved on its own.

Example: connection to the database server being dropped, hardware or network failure, GatewayTimeout or shared resources not available due to high load, etc.

Such transient errors are more common in the shared environment like Cloud environment.

Resilient HTTPClient using Polly can be easily created, in fact, we need do to a simple configuration considering the policy, whether we want to apply for a retry mechanism, etc.

Getting started

Create any .NET 5 or 6 or MVC Applications,

Resiliency HTTPClient resilient http call retries exponential backoff polly Polly Retry Policies and Error handling in C NET

Once you create a Regular API, Please create a Named or Type HTTP Client which is already discussed below article,

Please add below Nuget packages to the application,

Install Polly Nuget package

PM> Install-Package Microsoft.Extensions.Http.Polly -Version 5.0.1

OR

Using Visual Studio Nuget package manager,

resilient http call retries Install Package MicrosoftExtensionsHttp Polly Polly Retry Policies and Error handling in C NET

Next please add the below policy for the HTTP retries with exponential backoff as below,

services.AddHttpClient<IAccountClient, AccountClient()
             .ConfigurePrimaryHttpMessageHandler(() =>
             {
                 return new HttpClientHandler()
                 {
                     UseDefaultCredentials = true,
                     Credentials = new NetworkCredential(Configuration.GetValue<string>("UserName"),
                                                        Configuration.GetValue<string>("Password")),
                 };
             })
             .AddPolicyHandler(GetRetryPolicy());

In the above example, I have used the typed HttpClient example.

Define Retry Policies

The AddPolicyHandler() method, adds policies to the objects.

In our example, we have added Polly’s policy for HTTP Retries with exponential backoff.

static IAsyncPolicy<HttpResponseMessage> GetRetryPolicy()
{
        return HttpPolicyExtensions
        .HandleTransientHttpError()
        .WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2,
                                                                    retryAttempt)));
}

In the above example, the policy is configured to try 3 times with an exponential retry, starting at 2 seconds.

Polly usage can be used for more possible errors HTTPStatus status.

Polly – Error Handling in .NET

HandleTransientHttpError() takes care of the below types of HTTPS errors out of the box.

  • Network failures (as System.Net.Http.HttpRequestException)

  • HTTP 5XX status codes (server errors) HttpStatusCode.InternalServerError – 500
    • HttpStatusCode.BadGateway – 502
    • HttpStatusCode.ServiceUnavailable – 503
    • HttpStatusCode.GatewayTimeout – 504

  • HTTP 408 status code (request timeout)

How to use Additional HTTP Status Code

Apart from the above-discussed transient error, if you need to consider more HTTP status for the retry mechanism, then please do the same using the below approach discussed.

Updated Retry policy considering additional HTTP Status code can be added using,

OrResult(msg => msg.StatusCode == System.Net.HttpStatusCode.NotFound) etc.

return HttpPolicyExtensions
 .HandleTransientHttpError()
 .OrResult(msg => msg.StatusCode == System.Net.HttpStatusCode.NotFound)
 .WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2,
 retryAttempt)));

References:

Do you have any comments or ideas or any better suggestions to share?

Please sound off your comments below.

Happy Coding !!



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.



Leave a Comment

Your email address will not be published. Required fields are marked *