Search code examples
c#.netdependency-injectionpollyretry-logic

How to filter specific endpoint for retry policy using Polly


How to filter specific endpoint for retry policy using Polly

All client requests MyServiceHttpClient will retry. How disable retry policy specific api?

services.AddHttpClient<MyServiceHttpClient>(client =>
{
    /* configuration */
})
.AddPolicyHandler((serviceProvider, request) => 
    HttpPolicyExtensions.HandleTransientHttpError()
        .WaitAndRetryAsync(3, 
            sleepDurationProvider: retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), 
            onRetry: (outcome, timespan, retryAttempt, context) =>
            {
                serviceProvider.GetService<ILogger<MyServiceHttpClient>>()
                    .LogWarning("Delaying for {delay}ms, then making retry {retry}.", timespan.TotalMilliseconds, retryAttempt);
            }
            ));

Solution

  • You can try using no-op policy:

    builder.Services.AddHttpClient<MyServiceHttpClient>(client =>
        {
            /* configuration */
        })
        .AddPolicyHandler((serviceProvider, request) =>
            request.RequestUri.PathAndQuery.StartsWith("/api/") // your predicate
                ? Policy.NoOpAsync<HttpResponseMessage>() // <- no op for matching predicate
                : HttpPolicyExtensions.HandleTransientHttpError()
                    .WaitAndRetryAsync(3,
                        sleepDurationProvider: retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)),
                        onRetry: (outcome, timespan, retryAttempt, context) =>
                        {
                            serviceProvider.GetService<ILogger<MyServiceHttpClient>>()
                                .LogWarning("Delaying for {delay}ms, then making retry {retry}.",
                                    timespan.TotalMilliseconds, retryAttempt);
                        }
                    ));
    

    Or another approach would be to repeat the HandleTransientHttpError logic but with adding corresponding filter.