Why Using 'new HttpClient()' in C# Can Exhaust Sockets in Production
Repeatedly instantiating HttpClient with a 'using' statement in C# causes socket exhaustion because disposed sockets enter a TIME_WAIT state for up to 240 seconds, depleting available ports under high load. A single Windows machine offers roughly 16,000 ephemeral ports, meaning an app handling 100 requests per second can hit exhaustion in under three minutes. Microsoft introduced IHttpClientFactory in .NET Core 2.1 to address this by pooling and reusing HttpMessageHandler instances while supporting proper DNS rotation. Developers can register named or typed clients via dependency injection, allowing pre-configured, reusable HttpClient instances across services. Connection handlers are recycled every two minutes by default, though this interval is configurable with caution around long-lived DNS caching issues.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.


Discussion (0)
Log in to join the discussion and vote.
Log in