HttpClient retry policy with Polly
How to implement a retry policy with Polly in HttpClient
Required packages
To implement a retry policy with Polly in HttpClient, install the following NuGet packages:
Microsoft.Extensions.Http.Polly— integrates Polly withIHttpClientFactoryand providesHttpPolicyExtensions.Polly.Contrib.WaitAndRetry— provides theBackoff.DecorrelatedJitterBackoffV2helper used below.
Retry policy
The following code snippet shows how to implement a retry policy using Polly's built-in Decorrelated Jitter Backoff V2. Unlike a fixed delay, jittered backoff randomizes each retry interval, which helps avoid many clients retrying in sync and overwhelming a downstream service that's already struggling (a "retry storm"). 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 typed client, such as SomeApiClient, which has an HttpClient instance injected into it during registration.
It will apply to all calls made through that HttpClient instance.
services.AddHttpClient<ISomeApiClient, SomeApiClient>()
.AddPolicyHandler(exponentialBackoffRetryPolicy);