
new HttpClient() in a using Block Is a Bug: IHttpClientFactory Explained
- كاتب موثّق
- .NET 10
محتويات المقال
HttpClient is created in a using declaration, exactly as you'd treat any disposable. It passes every test. On the first real traffic peak, calls to the provider start failing with socket errors, and netstat on the server lists thousands of connections to the provider in the TIME_WAIT state. A colleague's quick fix, one static client for the whole app, stops the errors. A month later the provider moves to new IP addresses, and the service keeps calling the old ones until it's restarted.
The common misconception
HttpClient implements IDisposable, so the correct, careful thing is to create one per request and dispose it when the request is done.
using, and analyzers will remind you when you don't. HttpClient also looks like a lightweight request object, with a base address, a few headers and a GetAsync method. And the per-call version works perfectly in development and at low traffic, so nothing contradicts the rule until production does.
HttpClient, disposing also throws away something expensive that was meant to be reused.
What actually happens
An HttpClient is a front for a connection pool
HttpClient has a handler, SocketsHttpHandler in .NET, and the handler owns a pool of open connections. Requests to the same server reuse a pooled connection, so the TCP and TLS handshakes happen once. When the client owns its handler, disposing the client disposes the handler and closes its connections. A new client per request means a new pool per request: a fresh connection, a fresh handshake, and a close, every time.
A closed connection keeps its port for a while
using var client = new HttpClient() left 1,000 sockets in TIME_WAIT. The same 1,000 requests through one shared client, or through IHttpClientFactory, left none, and used a single connection. At a high request rate, that leftover state is what leads to .
A client that lives forever never looks up DNS again
HttpClient resolves a host name only when it opens a connection, and it ignores the DNS record's time to live. A pooled connection can stay open indefinitely, so a static client keeps talking to the IP it resolved at startup. That's the second half of the hook: the static client fixed the ports and broke failover. The fix is SocketsHttpHandler.PooledConnectionLifetime, which closes connections after a set time so the next one resolves the name again.
What IHttpClientFactory pools and rotates
AddHttpClient registers IHttpClientFactory. The factory keeps one handler per client name, and every HttpClient it hands out wraps the pooled handler. Disposing such a client doesn't dispose the handler, so it doesn't close connections. Handlers are recycled after their lifetime, two minutes by default, so new connections pick up DNS changes. The catch: the factory controls only the clients it hasn't handed out yet. Its clients are meant to be short-lived, and a client kept for hours keeps its old handler.
The payment call, fixed
ChargeRequest and read a PaymentResult:
public sealed class PaymentGateway{ public async Task<PaymentResult?> ChargeAsync(ChargeRequest request) { // A new connection pool per call: a new TCP and TLS handshake, // and one more socket left in TIME_WAIT after disposal using var http = new HttpClient { BaseAddress = new Uri("https://payments.example.com") }; var response = await http.PostAsJsonAsync("/charges", request); response.EnsureSuccessStatusCode(); return await response.Content.ReadFromJsonAsync<PaymentResult>(); }}var builder = WebApplication.CreateBuilder(args);// Typed client: registered as transient, built on a pooled, rotated handlerbuilder.Services.AddHttpClient<PaymentGateway>(client => client.BaseAddress = new Uri("https://payments.example.com"));var app = builder.Build();app.MapPost("/checkout", (ChargeRequest request, PaymentGateway gateway) => gateway.ChargeAsync(request));app.Run();public sealed class PaymentGateway(HttpClient http){ public async Task<PaymentResult?> ChargeAsync(ChargeRequest request) { var response = await http.PostAsJsonAsync("/charges", request); response.EnsureSuccessStatusCode(); return await response.Content.ReadFromJsonAsync<PaymentResult>(); }}static class Http{ // Connections are replaced every 2 minutes, so DNS changes are picked up public static readonly HttpClient Shared = new(new SocketsHttpHandler { PooledConnectionLifetime = TimeSpan.FromMinutes(2) });}Five ways to hold an HttpClient
new HttpClient() per call | |||
static client, default handler | |||
static client with PooledConnectionLifetime | |||
IHttpClientFactory, named or typed | |||
How to apply it in your project
Search for new HttpClient Find every new HttpClient(in server code. Each one inside a method, a constructor of a short-lived service, or ausingis a candidate for a typed or named client.Register clients where the app starts Move base addresses, default headers and timeouts into AddHttpClientcalls inProgram.cs, one typed client per external API, so the configuration lives in one place.Check who holds the clients Look for typed clients injected into singletons, background services and middleware constructors. Switch those to IHttpClientFactory.CreateClientper operation, or to a handler withPooledConnectionLifetime.Watch the sockets under load During a load test, count connections in TIME_WAIT to each downstream host. A number that grows with the request count means something is still creating its own handlers.
Key takeaways
An HttpClientfronts a connection pool; disposing it per call throws the pool away and leaves a port in TIME_WAIT each time.A client that lives forever reuses connections indefinitely and never re-resolves DNS unless PooledConnectionLifetimeis set.IHttpClientFactorypools handlers and rotates them every two minutes by default; its clients are cheap, short-lived and safe to dispose.Typed clients are transient: don't capture them in singletons, or you're back to a client that never sees DNS changes.
التعليقات (0)