Developer knowledge network · moderated exchange

UnreliableCode-Community

Community für Entwicklerforschung, Reverse Engineering und Codierung

Knowledge indexLive
4Categories
919Threads
2.8KBeiträge
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
Vertreter: 57
Beitrittsdatum: Mar 2019
Beiträge: 18
Danke: 40
Vor 4 Wochen · 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
Vertreter: 103
Beitrittsdatum: Apr 2018
Beiträge: 40
Danke: 24
Vor 4 Wochen · Jul 26, 2026 6:19 PM
#2

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

channel_concurrency
Reactive & Pipeline
MEMBER
Vertreter: 156
Beitrittsdatum: Jan 2022
Beiträge: 10
Danke: 16
Vor 4 Wochen · Jul 27, 2026 12:54 AM
#3

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