Best practices with HttpClient and Retry Policies with Polly in .NET Core 2, Part 2
Introduction
Because we chose the implementation strategy with the client typed, we will be able to implement and easily set our Retry Policies and Circuit Breakers in one place rather than in the implementation of our services that consume each HttpClient. Our services will then be completely agnostic of policies.
Requirements
We are using
Polly
to build policies. We will need to donwload this Nuget package:
PM> Install-Package Polly.Extensions.Http
Building our policies
Create a configuration pour our policies
To build our policies we will need two configurables values:
-
RetryCount
: number of retries before breaking our app with a CircuitBreaker Policy, needed also in our RetryPolicy too.
-
BreakDuration
: number of seconds that the application will be broken by the CircuitBreaker.
Here we are! let’s see how we are using configuration that we defined before to build our policy. We also need a logger, we will use
ILogger
to log retries with the http status code, the retry count and the duration before the next retry. The
OnHttpRetry
method will execute the logging. We need to compute at each retry the duration before the next retry: each retry takes more time to occur because we want to maximize the probability the remote source to recover by itsself with the time, then the method
ComputeDuration
will compute the retry count number by an exposant of 2, plus a random duration between 0 and 100 millisecond called “Jitter” in order to limit retries on the server at the same for performance reasons.
Let’s use here the configuration as well to define after n times the
Circuit Breaker
will operate with its configurable duration. The break will occur after (
RetryCount
+ 1)th retry, it means after (if we chose 3 as
RetryCount
) the 4th retry consecutive failed retry will generate a break. The event method
OnHttpBreak
is fired when the break occurs and logs a warning to indicate the http call won’t work during a certain
BreakDuration
and will generate a application failure for the current execution context with the
BrokenCircuitException
. We also implement another event method named
OnHttpReset
that will log a message when the break ends.
You know now how to make resilient http calls in your application. I showed you how to use correctly HttpClient and how to apply on it Policies with the right way. Hope this tutorial will help you 🙂
Like this:
Like
Loading...
Related posts
Written by
anthonygiretti
Anthony is a specialist in Web technologies (14 years of experience), in particular Microsoft .NET and learns the Cloud Azure platform.
He has received twice the Microsoft MVP award and he is also certified Microsoft MCSD and Azure Fundamentals.