Reputation: 3411
I am implementing Circuit Breaker pattern with HttpClientFactory and Polly using this tutorial and here's the code below that i wrote based on my understanding of the tutorial. RetryHttpRequest
class is the class where HttpClient is used.
services.AddHttpClient<IRetryHttpRequest, RetryHttpRequest>()
.SetHandlerLifetime(TimeSpan.FromSeconds(3))
.AddPolicyHandler(GetCircuitBreakerPolicy());
static IAsyncPolicy<HttpResponseMessage> GetCircuitBreakerPolicy()
{
return HttpPolicyExtensions
.HandleTransientHttpError()
.CircuitBreakerAsync(5, TimeSpan.FromSeconds(30));
}
For SetHandlerLifetime
, does the lifetime here mean per API request? So if I do retry for 3 times, each retry should take no more than 3 seconds. It is interesting that the default lifetime is 2 minutes which I think is too long.
How does SetHandlerLifetime(TimeSpan.FromSeconds(3))
and CircuitBreakerAsync(5, TimeSpan.FromSeconds(30))
related to each other and work with each other?
Upvotes: 0
Views: 1767
Reputation: 8156
SetHandlerLifetime(...)
is not to do with the timeout of individual calls. It is about how long HttpClient
s provided by HttpClientFactory reuse the same HttpClientHandler
, which provides a trade-off between optimising resources and reacting to external DNS changes.
For applying timeouts via HttpClientFactory, and combining that with retry policies, see Polly's documentation on applying timeout via HttpClientFactory.
Upvotes: 2