🔥 Your .NET API is Slowly Dying (And You Don't Even Know It)
Last month, our production system started timing out randomly. No errors. No warnings. Just... slow death.
After 3 sleepless nights and diving through 60+ microservices, I found the culprit:
var client = new HttpClient(); // This single line
Here's what was happening:
Every HTTP call was creating a NEW TCP socket. Under load, we exhausted the system's connection pool. Requests started queuing. Response times went from 200ms to 30+ seconds.
The Silent Killer:
• ✅ Your code compiles fine
• ✅ Your tests pass
• ✅ It works in dev/staging
• ❌ It crashes in production under real load
The Fix That Saved Our SLA:
// In Startup.cs
services.AddHttpClient("MyService", client => {
client.Timeout = TimeSpan.FromSeconds(120);
})
.ConfigurePrimaryHttpMessageHandler(() => new SocketsHttpHandler {
PooledConnectionLifetime = TimeSpan.FromMinutes(2),
PooledConnectionIdleTimeout = TimeSpan.FromMinutes(5),
MaxConnectionsPerServer = 20,
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
});
// In your service
public class MyService {
private readonly IHttpClientFactory _clientFactory;
public MyService(IHttpClientFactory clientFactory) {
_clientFactory = clientFactory;
}
public async Task<string> GetDataAsync() {
var client = _clientFactory.CreateClient("MyService");
// Use the client
}
}
The Results:
📊 95% reduction in connection failures
⚡ 40% improvement in throughput
💰 Prevented potential revenue loss from timeouts
The Lesson:
IHttpClientFactory isn't just a "best practice" - it's a production survival tool.
Microsoft documented this in 2018, but I still see this anti-pattern EVERYWHERE.
Have you been bitten by socket exhaustion?
Share your battle story in comments 👇
#performance #dotnet #csharp #softwareengineering #productionissues #microservices #debugging #azure #performanceoptimization #lessonslearned #techleadership
Top comments (0)