Developer knowledge network ยท moderated exchange

Komunitas Kode Tidak Dapat Diandalkan

Riset Pengembang, Rekayasa Terbalik & Komunitas Pengkodean

Knowledge indexHidup
4Categories
919Threads
2.8KPostingan
Discussion

Why IHttpClientFactory is mandatory to prevent Socket Exhaustion and DNS Stale Caching in C# [StackOverflow Architecture Guide]

csharp_async_master
Async & Task Expert
MEMBER
Reputasi: 57
Tanggal Bergabung: Mar 2019
Postingan: 18
Terima kasih: 40
4 minggu yang lalu ยท Jul 26, 2026 2:49 PM
#1

Two major issues with standard HttpClient usage in .NET:

  1. Socket Exhaustion: Creating new HttpClient() per request leaves hundreds of sockets in TIME_WAIT state, starving OS network ports.
  2. Stale DNS: Storing a singleton static HttpClient caches DNS indefinitely, failing when IP addresses rotate during cloud deployments.

The Fix:
Register with services.AddHttpClient() and inject IHttpClientFactory:

CSHARP
public class WeatherService(HttpClient client)
{
    public async Task<string> GetForecastAsync() => await client.GetStringAsync("/forecast");
}

IHttpClientFactory pools the underlying HttpMessageHandler lifetimes (default 2 minutes), rotating connections to honor DNS TTL while pooling active sockets!

dotnet_runtime_architect
.NET Core Specialist
MEMBER
Reputasi: 103
Tanggal Bergabung: Apr 2018
Postingan: 40
Terima kasih: 24
4 minggu yang lalu ยท Jul 26, 2026 6:19 PM
#2

IHttpClientFactory completely resolved socket exhaustion crashes in our high-traffic microservices cluster.

channel_concurrency
Reactive & Pipeline
MEMBER
Reputasi: 156
Tanggal Bergabung: Jan 2022
Postingan: 10
Terima kasih: 16
4 minggu yang lalu ยท Jul 27, 2026 12:54 AM
#3

Also makes adding Polly retry policies, rate limiters, and circuit breakers trivial via .AddTransientHttpErrorPolicy().