close
close

c# – connection pooling problem with Httpclient – Stack Overflow

c# – connection pooling problem with Httpclient – Stack Overflow

I am facing a SNAT port exhaustion issue in my web API written in .Net6 and hosted on an Azure web app when making calls to another API. We are using a custom library developed by another team within our company to handle HTTP calls, which allows us to centrally manage features like retry, circuit breaker, timeout, etc. Below is the code we are using. I would like to confirm if TCP connections are being reused, if connection pooling is being used, and if connections are being properly disposed during HTTP calls.

public class PolyHttpClient : IPolyHttpClient
{
    protected readonly HttpClient _httpClient;
    public PolyHttpClient()
    {
        HttpClientHandler clientHandler = new HttpClientHandler();

        if (clientHandler.SupportsAutomaticDecompression)
        {
            clientHandler.AutomaticDecompression = DecompressionMethods.GZip |
                                         DecompressionMethods.Deflate;
        }
        clientHandler.AllowAutoRedirect = _serviceSetting.AllowAutoRedirect.Value;
        clientHandler.UseCookies = false;
         _httpClient = new HttpClient(clientHandler)
        {
            BaseAddress = new System.Uri(serviceSetting.ServiceUrl),
            // provide max request timeout, it will be handled by cancellation token
            Timeout = Timeout.InfiniteTimeSpan
        };
    } 
    public virtual async Task<HttpResponseMessage> SendAsync(HttpRequestMessage requestMessage, CancellationToken cancellationToken)
    {
        response = await _httpClient.SendAsync(clonedRequest, additionalRequestOptions.HttpCompletionOptionType, cancellationTokenToUse);
        return  response;
    }
}