Developer knowledge network · moderated exchange

UnreliableCode қауымдастығы

Әзірлеушілерді зерттеу, кері инженерия және кодтау қауымдастығы

Knowledge indexТірі
4Categories
919Threads
2.8KЖазбалар
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
Өкіл: 57
Қосылу күні: Mar 2019
Хабарламалар: 18
Рахмет: 40
4 апта бұрын · 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
Өкіл: 103
Қосылу күні: Apr 2018
Хабарламалар: 40
Рахмет: 24
4 апта бұрын · Jul 26, 2026 6:19 PM
#2

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

channel_concurrency
Reactive & Pipeline
MEMBER
Өкіл: 156
Қосылу күні: Jan 2022
Хабарламалар: 10
Рахмет: 16
4 апта бұрын · Jul 27, 2026 12:54 AM
#3

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