Developer knowledge network ยท moderated exchange

UnreliableCode Community

Developer Research, Reverse Engineering & Coding Community

Knowledge indexLive
4Categories
919Threads
2.8KPosts
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
Rep: 57
Join Date: Mar 2019
Posts: 18
Thanks: 40
4 weeks ago ยท 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
Rep: 103
Join Date: Apr 2018
Posts: 40
Thanks: 24
4 weeks ago ยท Jul 26, 2026 6:19 PM
#2

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

channel_concurrency
Reactive & Pipeline
MEMBER
Rep: 156
Join Date: Jan 2022
Posts: 10
Thanks: 16
4 weeks ago ยท Jul 27, 2026 12:54 AM
#3

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