Fixing HttpClient Socket Exhaustion and Stale DNS in C# .NET with IHttpClientFactory and SocketsHttpHandler
Your ASP.NET Core API passes every unit test and handles staging traffic without breaking a sweat. Two hours after a busy Monday launch, outbound calls to your payment gateway or internal microservice suddenly collapse with System.Net.Sockets.SocketException (10048): Only one usage of each socket address (protocol/network address/port) is normally permitted on Windows, or Cannot assign requested address on Linux containers. CPU sits at 15 percent, memory looks flat, and restarting the process buys you another forty minutes before the exact same outage returns.
Or you hit the opposite failure mode: someone fixed socket exhaustion two years ago by turning HttpClient into a static readonly singleton, and now every time a downstream Azure App Service, AWS ALB, or blue-green deployment rotates its IP address, your service keeps throwing HttpRequestException timeouts until someone manually restarts the container. Both failures come from misunderstanding how .NET manages TCP sockets and DNS lifetimes underneath HttpClient.
Why Disposing HttpClient Per Request Exhausts Ephemeral Ports
Every C# developer is taught early on: if a class implements IDisposable, wrap it in a using block. HttpClient implements IDisposable, so it looks completely natural to write using var client = new HttpClient(); inside a controller action or loop. That single line is one of the highest-impact performance traps in .NET.
When your code disposes an HttpClient instance, it also disposes its underlying HttpMessageHandler and closes the active TCP connection. Closing a TCP socket does not immediately return the local ephemeral port to the operating system. Under RFC 793, the OS places that socket into the TIME_WAIT state (typically 120 seconds on Windows by default, or 60 seconds on Linux) to guarantee stray delayed packets from the closed connection do not corrupt a new connection on the same port tuple. Windows allocates roughly 16,384 dynamic ephemeral ports by default (ports 49152 through 65535). At just 150 outbound HTTP calls per second, a per-request new HttpClient() fills the entire port table before the oldest TIME_WAIT sockets expire, and every new connection fails with SocketException 10048.
You can confirm socket exhaustion on a live Windows machine in five seconds with PowerShell, or monitor active connection pools in real time using dotnet-counters:
# Count TIME_WAIT sockets grouped by owning process ID on Windows
Get-NetTCPConnection -State TimeWait |
Group-Object -Property OwningProcess |
Sort-Object -Property Count -Descending |
Select-Object -First 5 Count, Name
# Live .NET HTTP connection pool and socket telemetry (replace 12345 with your PID)
dotnet-counters monitor --process-id 12345 --counters System.Net.Http,System.Net.Sockets
Watch the Current Http 1.1 Connections and Outgoing Connections Established counters while under load. If established connections climb linearly with every request and your OS TIME_WAIT count shoots past several thousand, you are leaking or churning handlers instead of reusing pooled connections. If you are also seeing managed heap growth alongside socket churn, review our walkthrough on troubleshooting memory leaks in C# .NET with dotnet-gcdump to rule out retained closures or event subscriptions on your HTTP callers.
Comparing the Four HttpClient Lifetime Patterns in Modern .NET
Modern .NET (since .NET Core 2.1, through .NET 8 and .NET 9) replaced the legacy OS-bound HTTP stacks with SocketsHttpHandler, giving you two officially supported ways to eliminate both socket exhaustion and stale DNS. Choosing between them depends on whether you want dependency-injected middleware pipelines or a lightweight singleton client. Microsoft breaks down both patterns in the official Microsoft Learn HttpClient guidelines for .NET.
| Pattern | Prevents Socket Exhaustion? | Handles DNS Changes? | Best Use Case |
|---|---|---|---|
using new HttpClient() per call |
No (causes TIME_WAIT pileup) |
Yes | Never use in services or loops |
Static HttpClient (default settings) |
Yes | No (PooledConnectionLifetime is infinite) |
Avoid in cloud/Kubernetes environments |
Static HttpClient + SocketsHttpHandler |
Yes | Yes (via PooledConnectionLifetime) |
Console apps, libraries, singleton workers, high-RPS services |
IHttpClientFactory (Typed/Named) |
Yes | Yes (rotates handler pool every 2 min by default) | ASP.NET Core apps using DI, resilience pipelines, and logging handlers |
Option A: Static or Singleton HttpClient with PooledConnectionLifetime
If you are writing a .NET worker service, class library, desktop tool, or high-throughput API that does not need per-client DI handler chains, a single long-lived HttpClient backed by SocketsHttpHandler is actually simpler and avoids subtle DI scoping bugs. The only property you must explicitly configure is PooledConnectionLifetime (its default is Timeout.InfiniteTimeSpan, which is why plain static clients hold stale DNS forever):
using System.Net.Http;
public sealed class BillingApiClient
{
private static readonly SocketsHttpHandler SharedHandler = new()
{
// Force pooled TCP connections to recycle every 10 minutes so DNS updates take effect
PooledConnectionLifetime = TimeSpan.FromMinutes(10),
PooledConnectionIdleTimeout = TimeSpan.FromMinutes(2),
MaxConnectionsPerServer = 64,
ConnectTimeout = TimeSpan.FromSeconds(5)
};
private static readonly HttpClient Client = new(SharedHandler, disposeHandler: false)
{
BaseAddress = new Uri("https://api.billing.internal/"),
Timeout = TimeSpan.FromSeconds(15)
};
public async Task<string> GetInvoiceStatusAsync(string invoiceId, CancellationToken ct)
{
using HttpResponseMessage response = await Client.GetAsync($"v1/invoices/{invoiceId}", ct);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync(ct);
}
}
Two details matter in production. First, PooledConnectionLifetime never aborts an in-flight HTTP request; it simply marks a connection ineligible for reuse once its age crosses the threshold, closing it cleanly after the active response finishes. Second, always pass a CancellationToken and set a sane ConnectTimeout so a hung downstream firewall does not stall worker threads indefinitely. For more detail on keeping async I/O non-blocking under high concurrency, see our guide on C# async/await best practices to avoid deadlocks and thread pool starvation.
Option B: Typed Clients with IHttpClientFactory in ASP.NET Core
When your ASP.NET Core application talks to several downstream APIs and needs centralized base addresses, custom headers, Polly resilience handlers, or structured request telemetry, register typed clients through IHttpClientFactory (from Microsoft.Extensions.Http). The factory decouples the lightweight HttpClient wrapper from the underlying HttpMessageHandler pool and rotates handler instances automatically, as covered in the Microsoft Learn IHttpClientFactory documentation:
// Program.cs
builder.Services.AddHttpClient<InventoryClient>(client =>
{
client.BaseAddress = new Uri("https://inventory.internal/");
client.Timeout = TimeSpan.FromSeconds(10);
})
.ConfigurePrimaryHttpMessageHandler(() => new SocketsHttpHandler
{
PooledConnectionLifetime = TimeSpan.FromMinutes(5),
PooledConnectionIdleTimeout = TimeSpan.FromMinutes(2)
})
// Because SocketsHttpHandler already handles DNS rotation, disable redundant factory handler cycling
.SetHandlerLifetime(Timeout.InfiniteTimeSpan);
Notice that last line: .SetHandlerLifetime(Timeout.InfiniteTimeSpan). This is one of the best modern .NET idioms, yet many teams miss it. By default, IHttpClientFactory discards and recreates the entire SocketsHttpHandler every two minutes to work around stale DNS. When you already set PooledConnectionLifetime directly on SocketsHttpHandler, rotating the handler itself every two minutes is unnecessary overhead and can even break DNS rotation if someone accidentally captures the typed client in a singleton.
Three IHttpClientFactory Pitfalls That Still Bite Experienced Teams
Switching to IHttpClientFactory fixes per-request socket exhaustion immediately, but it introduces three well-known traps you should audit in code review:
- Injecting a typed client into a Singleton service: Typed clients registered via
AddHttpClient<TClient>()are registered as Transient. If you injectInventoryClientinto aSingletonbackground service without settingPooledConnectionLifetimeonSocketsHttpHandler, that singleton holds the firstHttpClient(and its first handler) forever, bypassing the factory's 2-minute rotation completely and reintroducing stale DNS. Either injectIHttpClientFactorydirectly and callCreateClient()per operation, or pairSocketsHttpHandler.PooledConnectionLifetimewithSetHandlerLifetime(Timeout.InfiniteTimeSpan)as shown above. - Using stateful CookieContainer with pooled handlers: Because
IHttpClientFactoryshares the same underlyingHttpMessageHandleracross unrelated HTTP requests, enablingUseCookies = true(the default!) means session cookies from User A's outbound call can leak into User B's outbound call. If your service calls an upstream API that sets cookies per user, explicitly setUseCookies = falseon the primary handler and pass per-requestCookieheaders manually on eachHttpRequestMessage. - Mutating DefaultRequestHeaders on a shared HttpClient: Never write
client.DefaultRequestHeaders.Authorization = ...per request on a shared or singleton client;DefaultRequestHeadersis not thread-safe for concurrent mutation and causes intermittentInvalidOperationExceptioncrashes under load. Build anHttpRequestMessageper call, attach per-request headers torequest.Headers, and callclient.SendAsync(request, ct).
Adding Lightweight Latency Logging Without Breaking Pooling
If you use IHttpClientFactory, attach a custom DelegatingHandler to log outbound status codes, target hosts, and elapsed milliseconds in structured format so you can spot slow upstream endpoints before they trigger timeouts. Pair that handler with the patterns in our guide to structured logging and global exception handling in C# .NET so every failed HTTP call carries its correlation ID and exact latency:
public sealed class OutboundTimingHandler(ILogger<OutboundTimingHandler> logger) : DelegatingHandler
{
protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
long started = Stopwatch.GetTimestamp();
HttpResponseMessage response = await base.SendAsync(request, cancellationToken);
TimeSpan elapsed = Stopwatch.GetElapsedTime(started);
if (!response.IsSuccessStatusCode || elapsed > TimeSpan.FromMilliseconds(500))
{
logger.LogWarning(
"Outbound HTTP {Method} {Host}{Path} returned {StatusCode} in {ElapsedMs} ms",
request.Method, request.RequestUri?.Host, request.RequestUri?.AbsolutePath,
(int)response.StatusCode, Math.Round(elapsed.TotalMilliseconds, 1));
}
return response;
}
}
Finally, before shipping your fix to production, run a 60-second load test against a staging instance while watching both dotnet-counters and Get-NetTCPConnection -State TimeWait. A properly pooled client should settle at a small, flat plateau of active TCP connections (typically equal to your concurrent in-flight calls) with near-zero TIME_WAIT churn, and connections should rotate cleanly on schedule whenever your configured PooledConnectionLifetime expires.