Polly Httpclient Resilience In Dotnet

Few weeks ago I explained [how to use the new HttpClientFactory. This freed ourselves from managing the confusing lifecycle of a HttpClient and at the same time allowed us to setup commmon options like base address for all HttpClient injections in our classes. Today we will see how we can setup timeout and retry policies for the HttpClient in in ASP NET Core using Polly.

We are now able to inject IMyApiClient in our services or controllers, and once we call .Get(), we will be hitting GET http://localhost:5100 using a HttpClient managed by the framework. Now apart from the lifecycle management, another major benefits from the abstraction is the ability to make the client more resilient by introduce Polly.

HttpPolicyExtensions.HandleTransientHttpError() returns a PolicyBuilder<HttpResponseMessage> provided by the Polly.Extensions.Http library. It setups a policy builder which handles 5.x.x and 408 error responses.
We then add other type of messages to handle by using OrResult(T -> bool) where we add handling of 404 error responses. And lastly, we also handle timeout exceptions by using Or<Ttype> passing in the TimeoutRejectedException from Polly. Once the conditions are setup, we can apply the policy WaitAndRetryAsync where we retry for five times and wait in an exponential manner between each retry.

And this concludes today’s post, all calls from IMyApiClient.Get() will now be subject to the timeout and retry policies!

Conclusion

Today we saw how to implement timeout and retry policies for HttpClient in ASP NET Core using Polly. We started by defining a HttpClient service which would be used throughout our application. Next we moved on to install the Polly extensions for ASP NET Core and finished by implementing the timeout and retry policies. Hope you like this post, see you next time!