IHttpClientFactory: Stop Creating HttpClient Per Request
new HttpClient() per request looks stateless and is the opposite. Each instance owns a handler that owns sockets. Dispose the client and the socket sits in TIME_WAIT. Under a burst — a fan-out to a partner API, a loop over tenants — the process runs out of ephemeral ports. The exception is a connection failure, which sends people looking at the remote service. The remote service is fine. The caller used up its own ports.
A single static HttpClient for the life of the process avoids that, and then hits the other bug. The handler caches DNS. When the dependency moves behind a new address, your process keeps calling the old one until it restarts. That shows up after a failover, not in the first week.
The factory is the middle path. IHttpClientFactory pools handlers and recycles them on a timer, so sockets are reused and DNS is picked up again. The HttpClient guidelines are the same story from the other end: do not create a client per request, do not hold a handler forever.
What TIME_WAIT actually is
TCP does not drop a connection the instant you dispose it. The side that closes first holds the tuple in TIME_WAIT so a delayed packet cannot land on a new occupant of the same port. That wait is minutes. A request path that does using var client = new HttpClient() on every inbound call creates a connection, uses it once, and parks the local port. Under a burst you get SocketException ("only one usage of each socket address") or a generic connection failure that is really "no local port left."
netstat (or Get-NetTCPConnection on Windows, ss -tan state time-wait on Linux) showing a forest of TIME_WAIT to the same remote IP is the fingerprint. The remote IP is healthy. Your process is the one that closed every connection. Reusing one handler lets HTTP keep-alive hold the socket in ESTABLISHED and reuse it. That is the point of not constructing per request.
DNS is why "just make it static" is incomplete
HttpClient is a facade. HttpMessageHandler / SocketsHttpHandler is what holds the connection pool and the DNS result. A handler created at process start will, by default, keep using the addresses it already resolved. Azure App Service, Container Apps, Kubernetes Services, and anyone else who rotates backends behind a stable hostname will look like an outage from your process and like a clean deploy from theirs.
You can set PooledConnectionLifetime on a SocketsHttpHandler you own and keep a static client. That is a valid pattern in a console app without DI. In an ASP.NET Core service you already have DI. Let the factory own the handler lifetime instead of wrapping a static field in a comment that says "TODO: rotate DNS."
The default handler lifetime in the factory is two minutes. That is the DNS refresh interval. After the lifetime elapses, the factory lets that handler drain and builds a new one, which resolves again. Existing in-flight requests finish on the old handler. New requests get the new one.
Named client, typed client, same factory
Register it once.
builder.Services.AddHttpClient("payments", client =>
{
client.BaseAddress = new Uri(builder.Configuration["Payments:BaseUrl"]!);
client.Timeout = TimeSpan.FromSeconds(10);
});
public sealed class PaymentClient(IHttpClientFactory factory)
{
public Task<HttpResponseMessage> GetAsync(string id, CancellationToken cancellationToken)
{
var client = factory.CreateClient("payments");
return client.GetAsync($"charges/{id}", cancellationToken);
}
}
CreateClient is cheap. It returns a lightweight HttpClient wrapper over a pooled handler. Create, send, read the content, move on.
A typed client is the same pool with a class the rest of the code can inject via AddHttpClient<PaymentClient>(...). Typed clients are still typically transient. The handler is pooled. Do not add PaymentClient as a singleton yourself "to save allocations" — you then hold one HttpClient whose handler the factory wanted to rotate.
Do not dispose the client you get from CreateClient. Disposal can return the handler to the pool in a way the factory did not ask for, and you will see odd reuse bugs or ObjectDisposedException on a handler that other requests still need. using around a factory client is the per-request anti-pattern wearing a DI costume.
Pass the request CancellationToken into GetAsync / SendAsync. A factory-managed client that ignores cancel still holds a pooled connection until Timeout. That pressure is the same one described in pass the CancellationToken.
Timeout, retry, and the two-minute knob
Set Timeout on the client to something your callers can survive. The default is 100 seconds, which will pin a queued work item long after the user is gone. Ten seconds plus a bounded retry at the call site is easier to operate than one silent 100-second hang. Timeout is a client-wide maximum; it is not a per-try budget unless you use a resilience handler that times each attempt separately.
Retries belong on a policy (Polly, or the standard resilience handler on the same AddHttpClient registration), and they must not retry a non-idempotent POST unless you send an idempotency key. A retried payment without a key is a second charge. The socket fix does not make the HTTP method safe. The key design is in idempotency keys for write APIs.
Handler lifetime (AddHttpClient(...).SetHandlerLifetime(...)) is not a retry knob. Shorten it only if a failover must be visible faster than two minutes and you have measured the extra connection setup. Lengthen it only if you have a reason the docs do not. Five seconds will churn sockets almost as badly as constructing clients. One day will hide DNS again.
Set BaseAddress and static headers in the registration. Mutating DefaultRequestHeaders on a client that might be shared is a race. Set per-request headers on HttpRequestMessage.
When not to use the factory
A one-shot console that makes three calls and exits can using var client = new HttpClient(). A library that cannot assume DI should take HttpClient as a constructor argument, not new it up. If you already have a singleton SocketsHttpHandler with PooledConnectionLifetime in a worker with no DI, leave it. Do not add a factory and still write new HttpClient() in a helper. One leftover constructor is enough.
What to look at when it still fails
SocketExceptionor "only one usage of each socket address": something is still constructingHttpClientby hand. Search fornew HttpClient. Search forHttpClientHandlertoo.- Calls stuck on the old IP after a deploy of the dependency: the handler lifetime has not elapsed, or a static client is still in the process. Restart is a workaround. The factory (or
PooledConnectionLifetime) is the fix. ObjectDisposedExceptionon send: you disposed a factory client, or you disposed a typed client'sHttpClientin ausing. Stop disposing it.- Timeouts that are really the server taking 30 seconds: the client timeout is doing its job. Fix the dependency or stop calling it on the user path.
- A named client that ignores
BaseAddress:GetAsync("https://...")with an absolute URL does not useBaseAddress. Relative URLs do. Mixing them looks like "the factory lost my config." - Exhaustion only in Azure App Service or Container Apps: the limit is still in the process. One named client per dependency, created through the factory, is the whole pattern.
Grep first. Then look at TIME_WAIT. Then look at handler lifetime. The remote API is the last place, not the first.
Keep reading
Data Protection Keys: The Cookie the Other Instance Could Not Read
Cookie auth, antiforgery, and TempData encrypt with the Data Protection key ring. The default ring is local. A second instance, a slot swap, or a recycled container mints a ring the first one never had.
Fixing NuGet Error: Unable to Load the Service Index for Source
A step-by-step guide to diagnosing and resolving NuGet package source errors in Visual Studio and dotnet CLI.
IOptionsSnapshot: The Snapshot Your Singleton Froze
IOptionsSnapshot is scoped. Inject it into a singleton and Production will not throw. You get one snapshot, minted at first resolve, that ignores every reload.
EF Core ExecuteUpdate: SaveChanges Never Ran, and Neither Did Your Interceptor
ExecuteUpdate sends SQL now. It skips SaveChanges, the tracker, and your audit interceptor. Stamp columns in the SET, or the tracked entity lies.
Pass the CancellationToken or the Work Continues After the Client Left
ASP.NET Core binds CancellationToken to the aborted request. Forward it to EF Core and HttpClient, and do not turn a client disconnect into a 500.
Azure Functions vs Azure Container Apps: Choosing the Right Serverless Model
A detailed comparison of Azure Functions and Azure Container Apps — pricing, cold starts, scaling, runtime support, and a decision flowchart for picking the right one.
Newsletter
New posts, straight to your inbox
One email when a new post goes up. Double opt-in, unsubscribe anytime. Not a daily digest.
Comments
- No comments yet. Be the first.