I would like to understand how to implement an optimistic timeout policy with Polly by using the HttpClientFactory
.
In the examples on the net, the timeout policy is used when calling asynchronous methods to be able to pass the cancellation token. But if I set the timeout policy from configure services, as indicated in the guide), how do I manage the cancellation token?
In example code, from guide linked, I see this:
var timeoutPolicy = Policy.TimeoutAsync<HttpResponseMessage>(10); // Timeout for an individual try
serviceCollection.AddHttpClient("GitHub", client =>
{
client.BaseAddress = new Uri("https://api.github.com/");
client.DefaultRequestHeaders.Add("Accept", "application/vnd.github.v3+json");
client.Timeout = TimeSpan.FromSeconds(60); // Overall timeout across all tries
})
.AddPolicyHandler(retryPolicy)
.AddPolicyHandler(timeoutPolicy);
You should chain the retry and timeout policy into a combined policy.
You have two options:
Wrap
methodtimeoutPolicy
is the inner policy so it applied for each and every attempt separatelyretryPolicy
is the outer policy, so it's overarching the timeout policyPolicyWrap
classOrdering does matter
You should be aware that the following two combined policies are very different:
Pushing this idea forward you can avoid to set the
Timeout
property of HttpClient by defining a global timeout as well:UPDATE #1 Optimistic timeout
Polly's Timeout does support both optimistic and pessimistic timeouts. In other words Polly can try to cancel those to-be-wrapped methods that does anticipate a
CancellationToken
(optimistic) as well those methods that doesn't (pessimistic). The default is the former.In case of optimistic you have two options:
If you register your named/typed client during the startup then you can only use the first option. Since the
policy.ExecuteAsync
will be called on your behalf (implicitly).If you register a typed client and you define the policy inside that client then you are making an explicit call of the
ExecuteAsync
where you can decide which version to use.