liveBook · Manning

Socket exhaustion

As explained in ASP.NET Core in Action, 3e

Socket exhaustion is a condition in which excessive undisposed or unavailable network sockets prevent an application from establishing further connections.

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.
CH33_F02_Lock3

Visualizes how disposed clients accumulate sockets during TIME_WAIT until outgoing requests can no longer be established. section 33.1

How ASP.NET Core in Action, 3e covers it

How deep it goes
Explains disposal, TIME_WAIT, handler pipelines, pooling, and DNS rotation, then demonstrates factory-based mitigation.
Examples
Uses per-request HttpClient disposal, a singleton client, and factory-created, named, or typed clients.
What it assumes
Assumes basic C# and HTTP API usage while introducing HttpClient handlers, connection reuse, and DNS behavior.
What you can do after
Operate/configure outbound HTTP calls with IHttpClientFactory instead of repeatedly disposing connection-owning handlers.
How it connects
Connects HttpClient, HttpClientHandler, IHttpClientFactory, HTTP APIs, DNS rotation, and TIME_WAIT.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of ASP.NET Core in Action, 3e. The section links point to the parts of the book it draws on.