Quantcast
Viewing all articles
Browse latest Browse all 29

Enable Http Transient Failure Retries with logging

To enable transient retries in dotnet core, put the following into the startup process. In this case, it went into a WorkerService, so the code is in the Program.cs file.

services.AddHttpClient("AnyClientName")
    .AddTransientHttpErrorPolicy(x =>
        x.WaitAndRetryAsync(
            Backoff.DecorrelatedJitterBackoffV2(medianFirstRetryDelay: TimeSpan.FromSeconds(1),
            retryCount: 5), onRetryAsync: async (outcome, span, retryAttempt, context) => {
                Log.Logger.Warning("Delaying for {delay}ms, then making retry {retry}.", 
                    span.TotalMilliseconds, retryAttempt);
            })
    );

The above code will try for 5 times using a backoff logic that adds some random time to it so that the backoff logic will not add another problem with an api. This also logs when it does a retry. The above code is using Serilog, so your logging logic may be different.

The NuGet packages installed to enable this are:
Polly.Contrib.WaitAndRetry
Microsoft.Extensions.Http.Polly
Serilog.Extensions.Hosting
Serilog

Here is a link that explains the retry backoff logic:
https://github.com/Polly-Contrib/Polly.Contrib.WaitAndRetry


Viewing all articles
Browse latest Browse all 29

Trending Articles