Socket exhaustion occurs when repeatedly creating and disposing HttpClient instances leaves sockets unavailable, eventually preventing an application from making outgoing HTTP requests. section 33.1 section 33.5
A common failure pattern
A request handler creates a new HttpClient for every request and disposes it afterward. Closing each connection leaves its socket in TIME_WAIT for 240 seconds; enough repeated requests can exhaust available sockets. section 33.1
A single long-lived HttpClient avoids this exhaustion by reusing its connection, but it may continue using an old server address after DNS records change. section 33.1 section 33.5
IHttpClientFactory separates HttpClient lifetime from the underlying HttpClientHandler pipeline. It pools handlers, reuses connections, and periodically rotates handlers to address socket exhaustion and DNS changes. section 33.2.1 section 33.5
A practical application can use the factory in three ways:
- Register the factory with AddHttpClient() and create clients through IHttpClientFactory.CreateClient(). section 33.2.1
- Use named clients when several centrally configured HTTP clients are needed. section 33.5
- Use typed clients to hide HTTP mechanics behind a service. section 33.5
Figure 33.2 Disposing of HttpClient can lead to socket exhaustion. Each new connection requires the operating system to assign a new socket, and closing a socket doesn’t make it available until the TIME_WAIT period of 240 seconds has elapsed. Eventually you can run out of sockets, at which point you can’t make any outgoing HTTP requests.
Visualizes how disposed clients accumulate sockets during TIME_WAIT until outgoing requests can no longer be established. section 33.1
