HttpClient retry policy with Polly
How to implement a retry policy with Polly in HttpClient
Required packages
In order to implement a retry policy with Polly in HttpClient, you need to install the Polly
package from NuGet.
Retry policy
The following code snippet shows how to implement a retry policy using Polly's built-in Decorrelated Jitter Backoff V2. The method takes 2 parameters: the median first retry delay (TimeSpan.FromMilliseconds(100)) and the retry count (5).
var exponentialBackoffRetryPolicy =
HttpPolicyExtensions.HandleTransientHttpError()
.WaitAndRetryAsync(
Backoff.DecorrelatedJitterBackoffV2(TimeSpan.FromMilliseconds(100), 5),
onRetryAsync: (result, _) =>
{
// You can log the retry here
return Task.CompletedTask;
});
Applying the retry policy
The retry policy can be applied to a class SomeApiClient
into which HttpClient
instance is injected during the registration.
It will apply to all calls made by the HttpClient
instance.
services.AddHttpClient<ISomeApiClient, SomeApiClient>()
.AddPolicyHandler(exponentialBackoffRetryPolicy);