❔ HttpClient does not respect CancellationToken

App & Deployment Details
Applications X and Y are DotnetCore 6.0 applications.
X runs on K8s and Y on VMs on the cloud.

Context of the problem
I have two applications, X and Y. Y is a dumb app and it's job is to fetch data from various datasources. Y has certain REST styled endpoints. X has a logic to call the said endpoints of application Y. All calls are async and the use case needs the Http Post call to adhere to the cancellationToken.

Problem
The cancellationToken is set in this fashion
using var cts = CancellationTokenSource.CreateLinkedTokenSource(token);
  cts.CancelAfter(certainValue);


and used in the following manner
response = await _client.SendAsync(request, cancellationToken);


we also have logging on top of the httpClient call and it looks like so
var stopWatch = Stopwatch.StartNew();
try
{
  response = await PostAsync(request, cancellationToken);
}
catch
{
  ElapsedTime = stopWatch.ElapsedInMilliseconds();
}


Observations
  1. The CancellationToken value is always set to 20s. From the ElapsedTime that is logged, we observed that the call does not timeout ~20s but in 1/10th of cases is >20s and has no pattern
  2. The 20s timeout was changed to 30s and similar behaviour was observed.
  3. Found this SO article describing the same problem
Solutions Tried
  1. Used the Polly.Timout but still observing the same issue
Stack Overflow
I'm trying to set a default timeout for my HttpClient calls to 5 seconds.

I've done this via CancellationTokenSource.

Here's the pertinent bit of code:

var cancellationToken = new
GitHub
Polly is a .NET resilience and transient-fault-handling library that allows developers to express policies such as Retry, Circuit Breaker, Timeout, Bulkhead Isolation, and Fallback in a fluent and ...
Was this page helpful?