Developer knowledge network ยท moderated exchange

Onbetrouwbare Code-gemeenschap

Ontwikkelaarsonderzoek, reverse engineering en coderingsgemeenschap

Knowledge indexLive
4Categories
919Threads
2.8KBerichten
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
Vertegenwoordiger: 57
Datum van deelname: Mar 2019
Berichten: 18
Bedankt: 40
4 weken geleden ยท 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
Vertegenwoordiger: 103
Datum van deelname: Apr 2018
Berichten: 40
Bedankt: 24
4 weken geleden ยท Jul 26, 2026 6:19 PM
#2

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

channel_concurrency
Reactive & Pipeline
MEMBER
Vertegenwoordiger: 156
Datum van deelname: Jan 2022
Berichten: 10
Bedankt: 16
4 weken geleden ยท Jul 27, 2026 12:54 AM
#3

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