Mames
Mames

Reputation: 85

Adding Polly Retry policy globally

I know you can register an IAsyncPolicy<HttpResponseMessage> to a particular instance of an HttpClient injected into a service, but is there a way to configure this globally, to all HttpClients wired up via microsofts dependency injection?

For example, you can wire up the HttpClient injected into MyService via:

services.AddHttpClient<MyService>(
    .AddPolicyHandler(
        HttpPolicyExtensions
            .HandleTransientHttpError()
            .WaitAndRetryAsync(3, retryAttempt =>
                TimeSpan.FromSeconds(Math.Pow(2, retryAttempt))));

But I would like to add this policy handler to all HttpClients. The class that I would like to add retries to is 3rd party and marked as internal, so I cannot directly access it.

Upvotes: 1

Views: 2962

Answers (1)

Peter Csala
Peter Csala

Reputation: 22829

In short: With a custom HttpClientFactory you can but should not aim for this.

In order to use retry against an endpoint all these prerequisites should be met:

  • The potentially introduced observable impact is acceptable
  • The operation can be redone without any irreversible side effect
  • The introduced complexity is negligible compared to the promised reliability

If we are talking about a REST API then implementing all CRUD operations in an idempotent is feasible but quite challenging to do it in a right way. So, most of the time you want to apply retry logic against only your retrieve calls, not against your data manipulation calls.

Also be aware that retries can make things even worse. If the downstream system is overloaded then sending new requests will not help the self-healing. Most probably it needs some "air" to go back to normal state from degraded. That's where Circuit Breaker might be helpful to avoid flooding downstream systems when it is already having hard time.

You can combine Retry and Circuit Breaker policies via escalation

  • where CB is the inner policy
  • and Retry is the outer.

Upvotes: 1

Related Questions