Adding resilience to my http calls using Polly

As I am building out my MyReverie( project in GitHub, I wanted to add some resilience to my http calls. I had heard of the Polly framework that made doing this extremely easily.

Polly is an open source framework that provides resilience capabilities on transient errors that you can leverage in your own applications thus removing the burden of having to write this code out manually yourself. Types of capabilities include Retry, Circuit Breaker, Fallback among others.

If you were to try write this code yourself and for it to be done correctly can be a little tricky and error prone due to inconsistencies that may develop over time as these are cross cutting concerns it should be abstracted to a library to be reused – so why reinvent the wheel!

Type of resilience’s you may want to consider could be against network outages or systems being busy attending to other work, this is particularly important in larger microservice applications that rely heavily on intercommunication of services so instead of timing out or returning with an error wouldn’t you like it to retry and handle this scenario a little more elegantly and smarter.

For my purposes I wanted to simply add an ability that if the endpoint was for some reason unavailable that it would ‘Retry’ a certain number of times and not simply fail after the first attempt. It is a simple use case but it allowed me to easily become familiar with this framework.

To get Polly up and running is quite straight forward.

In my startup class I define the http client

services.AddHttpClient("api").AddTransientHttpErrorPolicy(p => p.RetryAsync(5));
This effectively means to retry the http call five time before returning with a failure response. I chose 5 as a reasonable amount of times to retry but you can choose whichever number you wish.

I need to of course add the Polly package(in my case I am using v2.2.0):


add then add the using statement

using Polly;

In my service class within my web project where I make my http calls to the API I inject ‘IHttpClientFactory’ using Dependancy Injection which comes out of the box with .Net Core as a constructor parameter.

IHttpClientFactory httpClientFactory

I then assign this parameter to a global variable ‘_httpClientFactory’ in the constructor as below

_httpClientFactory = httpClientFactory;

I initialize a new HttpClient object to the client I defined in the startup class by

HttpClient client = _httpClientFactory.CreateClient("api");

after which I make the http calls as you would normally do, but this time incorporating using Polly.

In my case it is:

await client.GetStringAsync(_appSettings.GoalsUrl);

Now if this http call fails it will try another four times before returning to the caller thus improving the resilience of my system in case of intermittent connectivity issues!.