Caution when creating new instances of the HttpClient class
Posted: (EET/GMT+2)
When working with HTTP APIs in .NET, it's tempting to create a new HttpClient instance for every request. After all, it looks simple enough:
using HttpClientclient = new HttpClient())
{
string result = await client.GetStringAsync("https://example.com/");
Console.WriteLine(result);
}
However, this pattern can cause serious problems in production. Each HttpClient instance opens a new underlying TCP connection, and if you create many of them rapidly, those connections can stay in the TIME_WAIT state for a long time. The result is socket exhaustion: your application can suddenly stop making outbound requests.
The recommended solution is to reuse a single HttpClient instance throughout the lifetime of your application. It's thread-safe for concurrent requests and designed for reuse. A good pattern is to create it as a static or singleton instance:
private static readonly HttpClient client = new HttpClient();
The main rule is simple: do not dispose a HttpClient isntance too often. Instead, reuse one whenever possible.
This is one of those subtle .NET gotchas that can remain invisible for years, until you start scaling up traffic. Reusing a HttpClient is an easy win for stability and performance.