Urgent.News

What's breaking now, across thousands of outlets.

World

HttpClientFactory: Why new HttpClient() Is Killing Your App

Hey there, fellow C# developers! ๐Ÿ‘‹ Let me tell you a horror story. You're building a nice web service, everything works great in development, and then... production hits. Suddenly your app is throwing SocketException errors left and right. What happened? You probably did this: // DON'T DO THIS! using ( var client = new HttpClient ()) { var response = await client . GetAsync (โ€ฆ

C# developers often create an HttpClient instance with a using statement, but this leads to Socket Exhaustion. The problem occurs because disposing of HttpClient doesn't close sockets immediately; they enter a TIME_WAIT state for several minutes. A single Windows machine has only ~16,000 ephemeral ports, so under load, all sockets can be exhausted in just a few minutes. .NET Core 2.1 introduced IHttpClientFactory to solve this issue by pooling and reusing HttpMessageHandler instances, allowing proper DNS rotation.

To use it, addHttpClient() in Program.cs or Startup.cs, then create services with IHttpClientFactory. For pre-configured clients, use named clients by adding client = {BaseAddress, DefaultRequestHeaders, Timeout}. For typed clients, inject a fully configured HttpClient directly into your service. Additionally, you can customize handler lifetime, but be cautious with long lifetimes as IP changes can cause issues.

The best approach is to stop creating HttpClient instances manually and use IHttpClientFactory to manage connection pooling, avoiding socket exhaustion errors.

Written by urgent.news from Dev.to's reporting โ€” not their text. Machine-written โ€” may contain errors; check the original before relying on it.

Read the original at dev.to โ†’

More in World

Woman pleads guilty to selling baby for RM17,300 in Kedah

A 24-YEAR-OLD woman pleaded guilty in the Sessions Court here today to a charge of transferring control of a baby boy in exchange for RM17,300 last month. The accused, S.

  • 24-year-old S. Kelsey pleads guilty to selling baby for RM17,300
  • Charged under Section 48(1) of Child Act 2001, facing up to 20 years
  • Also guilty of possessing another woman's identity card in Sungai Petani

More from Tuesday 1 September โ†’