0

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));
        }
  1. 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.

  2. How does SetHandlerLifetime(TimeSpan.FromSeconds(3)) and CircuitBreakerAsync(5, TimeSpan.FromSeconds(30)) related to each other and work with each other?

superninja
  • 3,114
  • 7
  • 30
  • 63

1 Answers1

2

SetHandlerLifetime(...) is not to do with the timeout of individual calls. It is about how long HttpClients 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.

mountain traveller
  • 7,591
  • 33
  • 38