C#C
C#2y ago
devhl

Slow HttpClient responses

I have a program which polls an API. It usually works great, but lately, I've been seeing many HttpClient requests take up to 30 seconds despite my timeouts. Here is how I configured the client. And here is the library where these methods to configure Polly reside https://github.com/devhl-labs/CocApi/blob/47f7e1ec097fdfd7f50e60436d7a0fe96d87f721/src/CocApi.Test/Program.cs#L62

options.AddCocApiHttpClients(
    builder: builder => builder
        .AddRetryPolicy(context.Configuration.GetValue<int>("CocApi:Rest:HttpClient:Retries")) // 1
        .AddTimeoutPolicy(TimeSpan.FromMilliseconds(context.Configuration.GetValue<long>("CocApi:Rest:HttpClient:Timeout"))) // 1.5 seconds
        .AddCircuitBreakerPolicy(
            context.Configuration.GetValue<int>("CocApi:Rest:HttpClient:HandledEventsAllowedBeforeBreaking"), // 20
            TimeSpan.FromSeconds(context.Configuration.GetValue<int>("CocApi:Rest:HttpClient:DurationOfBreak"))) // 30 seconds
        .ConfigurePrimaryHttpMessageHandler(sp => new HttpClientHandler
        {
            // this property is important if you query the api very fast
            MaxConnectionsPerServer = context.Configuration.GetValue<int>("CocApi:Rest:HttpClient:MaxConnectionsPerServer"), // 100
            CookieContainer = sp.GetRequiredService<CookieContainer>().Value
        })
);


And here is the request itself. After the request, I log the difference between the current DateTime and the requestedAtLocalVar, which is showing me up to 30 seconds. It normally shows less than a second.
DateTime requestedAtLocalVar = DateTime.UtcNow;

using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false))
{
    string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);

    ....
Was this page helpful?