Search code examples
asp.net-corehttpclienttcpclienthttpclientfactory

How is the mechanism of releasing TCP port in HTTPClientFactory?


In my current version of a project, the HttpClinet has been used for creating requests. But in request's peak time most of our TCP ports get in waited status, Their status remains about 2 minutes event after task completion. I read some articles about IHttpClientFactory.

But I'm not sure how this solution can solve our problems. Any ideas will be appreciated.


Solution

  • There are tonnes of articles out there which would tell you why you should not dispose HttpClient (which would result in what you mentioned, and end-up with socket exhaustion issue), but rather to use IHttpClientFactory to manage the life-cycle of of HttpClient-related services.

    This is because each time you make a request with HttpClient, and dispose it after usage, would cause the socket to be in a TIME_WAIT state, and imagine if you make few thousands of requests in few seconds, you will run out of sockets. The IHttpClientFactory is a contract to better manage your Http services, and to re-use sockets from the connection pool without you having to manage it.

    As a start, go through this, I think it provides sufficient info. about what you want to achieve,

    https://learn.microsoft.com/en-us/dotnet/architecture/microservices/implement-resilient-applications/use-httpclientfactory-to-implement-resilient-http-requests

    One of the key point in the article above, to answer your question about how IHttpClientFactory can solve your issue,

    Each time you get an HttpClient object from the IHttpClientFactory, a new instance is returned. But each HttpClient uses an HttpMessageHandler that's pooled and reused by the IHttpClientFactory to reduce resource consumption, as long as the HttpMessageHandler's lifetime hasn't expired.

    Hope this helps!