Covers diagnosing outbound connection exhaustion: per-call HttpClient, unbounded MaxConnectionsPerServer, request queueing, and Azure SNAT port exhaustion, using dotnet-counters, App Service diagnostics and netstat, and fixing it with connection reuse, NAT Gateway and private endpoints.
Intermittent connect timeouts to many destinations with low CPU points to the outbound path running out of something: sockets, pool slots or Azure SNAT ports. On App Service, outbound connections to public IPs are translated through a limited pool of SNAT ports (128 preallocated per instance); code that opens a new connection per call, or bursts thousands of concurrent calls, exhausts them.
I confirm it with the App Service SNAT Port Exhaustion detector, dotnet-counters (http.client.open_connections, http.client.request.time_in_queue) and socket counts from ss or netstat, and find the code in a dump or trace. The fix is connection reuse (IHttpClientFactory), bounded concurrency, private endpoints for Azure services, and a NAT Gateway when volume is legitimately high. Scaling out only buys time.
"The shape of the symptom matters. If calls to many different hosts time out at connect time, CPU and memory are fine, it gets worse at peak and a restart fixes it for a while, I suspect outbound connection exhaustion rather than a slow dependency. In Azure that often means SNAT port exhaustion: when an App Service instance talks to a public IP, its connection is translated to a shared outbound address and port, and each instance only gets a small preallocated set of SNAT ports, 128 on App Service. Each connection to the same destination IP and port needs its own, and a closed connection keeps its port for a while. So code that opens a new connection per request burns through them quickly.
For example, at [company] our [checkout API] started timing out on calls to the [payment provider] during [a sale], with CPU at [30%]. I opened the SNAT Port Exhaustion detector in App Service diagnostics, which showed failed SNAT allocations at exactly those times. dotnet-counters on an instance showed
http.client.open_connectionsclimbing into the hundreds and requests queuing, and a dump showed a legacy class doingnew HttpClient()per call. The quick mitigation was scaling out to spread connections. The fix was moving that client toIHttpClientFactory, putting Azure SQL and Storage behind private endpoints so they no longer used SNAT, and adding a NAT Gateway for the remaining internet traffic. [Failed outbound calls went from about 4% at peak to zero.]The mistake I see is raising timeouts or adding retries. Retries on an exhausted pool open even more connections and make it worse. When the network layer is starving, reuse connections before you add capacity."
| Signal | Tool | Points to |
|---|---|---|
| Failed SNAT allocations | App Service "Diagnose and solve problems" → SNAT Port Exhaustion; Load Balancer SNAT metrics | Too many outbound connections to public IPs |
http.client.request.time_in_queue rising |
dotnet-counters System.Net.Http |
Pool limit (MaxConnectionsPerServer) or HTTP/2 stream limit reached |
http.client.open_connections very high, churning |
dotnet-counters | Connections not reused |
| Thousands of TIME_WAIT sockets | ss -tan state time-wait / netstat (Kudu console) |
Per-call connections |
Many stacks in HttpClient construction or connect |
dotnet-dump, dotnet-trace | The offending code |
| Fix | Effect |
|---|---|
IHttpClientFactory or a long-lived client with PooledConnectionLifetime |
Reuse connections, far fewer ports |
Bound concurrency (Parallel.ForEachAsync, SemaphoreSlim, MaxConnectionsPerServer) |
No bursts of thousands of connections |
| Private endpoints / service endpoints for Azure SQL, Storage, Key Vault | That traffic doesn't use SNAT |
| VNet integration + NAT Gateway | 64,512 SNAT ports per public IP, up to 16 IPs |
| Scale out | Temporary relief: more instances, more ports |
In a [checkout] service, moving one client to IHttpClientFactory, putting Azure SQL and Storage on private endpoints and adding a NAT Gateway dropped peak open outbound connections per instance from about 900 to 60, and failed payment calls at peak from 4% to 0.
Checks that the candidate can recognise outbound connection exhaustion from its symptoms, knows Azure SNAT behaviour, uses the right diagnostic tools and fixes the cause rather than adding capacity or retries.
Green flags
HttpClient or unbounded fan-out as the root causeRed flags
instance (private IP) --tcp--> [Azure load balancer SNAT] --public IP:port--> payments.example.com:443
|
+-- pool of SNAT ports per instance (128 preallocated on App Service)
Each connection to a given destination IP:port needs a unique SNAT port. After a connection closes, the port isn't immediately reusable for the same destination. Opening connections faster than they age out drains the pool, and new connects wait and then fail.
TCP's TIME_WAIT state is kept by the side that closes the connection first, usually the client (here, your instance or the SNAT translation in front of it). It lasts 2 × MSL, typically 60 seconds on Linux and up to 120 seconds or more on Windows. Its purpose is to make sure late packets from the old connection aren't mistaken for a new connection with the same four-tuple (source IP:port, destination IP:port). While a four-tuple is in TIME_WAIT, it can't be reused for the same destination.
So port usage is roughly:
ports in use ≈ open connections + (connections closed per second × hold time)
reused pool: 20 open + ~0 closed/s ≈ 20 ports
per-call: ~5 open + 50 closed/s × 60 s ≈ 3,000 ports (pool is 128)
SNAT adds its own idle and reuse timers on the translated port. The result is the same: connection churn, not concurrency, is what exhausts the pool. Reusing keep-alive connections makes the closed-per-second term almost zero.
new HttpClient() creates a new SocketsHttpHandler and pool, so every call opens a new TCP connection, completes the TLS handshake, then closes it.time_in_queue rising, open_connections flat at a limit): you hit MaxConnectionsPerServer or HTTP/2's ~100 concurrent streams. Requests wait, latency rises, but connects don't fail.Both often have the same root cause: unbounded concurrency or no reuse.
dotnet-counters monitor -n MyApi --counters System.Net.Http,System.Net.Sockets on an instance (via Kudu/SSH or a sidecar) for open connections, queue time and outgoing connection rates.ss -tan | awk '{print $1}' | sort | uniq -c to count connection states; TIME_WAIT in the thousands is a red flag.dotnet-dump collect and dumpheap -stat -type SocketsHttpHandler: many instances means per-call construction. dotnet-trace with the System.Net.Http provider shows connection establishment events.IHttpClientFactory; for singletons, one HttpClient with SocketsHttpHandler.PooledConnectionLifetime of a few minutes..Result/.Wait(), so responses are read and connections returned promptly.Parallel.ForEachAsync DOP or MaxConnectionsPerServer, so a burst queues instead of opening hundreds of sockets.new HttpClient() per call to a public URL, and open the SNAT detector.IHttpClientFactory and compare http.client.open_connections in dotnet-counters.ss before and after the change, and check them against the formula above.MaxConnectionsPerServer = 4, push 100 concurrent requests and watch time_in_queue rise without errors.dumpheap -stat to count HttpClient and SocketsHttpHandler instances.Before: the cause. After: reuse, bounded concurrency and resilience:
// BEFORE: a new pool and connection per call; under load this exhausts sockets/SNAT ports.
public sealed class LegacyPaymentGateway
{
public async Task<string> ChargeAsync(ChargeRequest req, CancellationToken ct)
{
using var http = new HttpClient(); // new SocketsHttpHandler every call
var res = await http.PostAsJsonAsync("https://payments.example.com/charges", req, ct);
return await res.Content.ReadAsStringAsync(ct);
}
}
// AFTER: Program.cs
using System.Net;
using Microsoft.Extensions.Http.Resilience;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddHttpClient<PaymentGateway>(c =>
{
c.BaseAddress = new Uri("https://payments.example.com");
c.Timeout = TimeSpan.FromSeconds(10);
})
.ConfigurePrimaryHttpMessageHandler(() => new SocketsHttpHandler
{
PooledConnectionLifetime = TimeSpan.FromMinutes(5), // reuse, but still see DNS changes
MaxConnectionsPerServer = 50 // bursts queue instead of opening hundreds of sockets
})
.AddStandardResilienceHandler(); // jittered retries + circuit breaker
var app = builder.Build();
app.MapPost("/checkout", async (ChargeRequest req, PaymentGateway gateway, CancellationToken ct) =>
Results.Ok(await gateway.ChargeAsync(req, ct)));
app.Run();
public sealed record ChargeRequest(string OrderId, decimal Amount, string Currency);
public sealed record ChargeResult(string ChargeId, string Status);
public sealed class PaymentGateway(HttpClient http)
{
public async Task<ChargeResult?> ChargeAsync(ChargeRequest req, CancellationToken ct)
{
using var res = await http.PostAsJsonAsync("/charges", req, ct);
res.EnsureSuccessStatusCode();
return await res.Content.ReadFromJsonAsync<ChargeResult>(ct);
}
}
# Evidence on an instance (Kudu SSH / container shell)
dotnet-counters monitor -n Checkout.Api --counters System.Net.Http
ss -tan state time-wait | wc -l
new HttpClient() inside a using per call. Why it is wrong: new pool, new TCP and TLS handshake, then TIME_WAIT every time; at 50 calls/s that's thousands of ports in the hold window per instance. Instead: IHttpClientFactory or a long-lived client..Result, .Wait()) in request handlers. Why it is wrong: blocked threads stretch request times, ThreadPool starvation delays reading responses, so connections are held longer and more are opened to meet demand. Instead: async all the way so connections return to the pool promptly.PooledConnectionLifetime to a few seconds "to be safe with DNS". Why it is wrong: it recreates connections constantly, which is almost as bad as per-call clients for SNAT. Instead: minutes, not seconds.Connection exhaustion is a classic "looks like the dependency, is actually us" incident. A senior reads the shape of the symptom (many destinations, connect-time failures, low CPU) and goes to the network layer quickly, uses platform diagnostics as well as process counters, and fixes the cause in code before buying capacity. The architectural follow-up is to keep Azure-internal traffic private and give internet egress a NAT Gateway with known IPs, which also helps partners who allow-list your addresses.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Connection reuse | Always | Code change | Never skip it |
| Private endpoints | Azure PaaS dependencies | Private DNS, per-endpoint cost | Public third-party APIs |
| NAT Gateway | High legitimate internet egress, stable IPs needed | Hourly and data charges | When reuse alone fixes it |
| Scale out | Immediate mitigation | More instances | As the permanent fix |
Opening a connection is expensive: a TCP handshake, a TLS handshake, and for SQL a login, so .NET keeps connections in pools and reuses them.
SocketsHttpHandler keeps a pool per host. Reuse it through a long-lived HttpClient or IHttpClientFactory, and set PooledConnectionLifetime so connections are recycled and DNS changes are noticed.Microsoft.Data.SqlClient pools per exact connection string, up to Max Pool Size = 100 by default. Open takes a pooled connection; Dispose returns it.Pool exhaustion shows up as requests queuing for a connection: HTTP time_in_queue rising, or SQL's "max pool size was reached" timeout. The fix is almost always a leak or slow calls, not a bigger pool: a bigger pool just moves the queue to the database or the downstream service.
Two different limits produce similar errors:
EMFILE, "Too many open files"): the process hit its ulimit -n. Something is leaking files or sockets.EADDRNOTAVAIL, "Cannot assign requested address"): too many outbound connections to the same destination, usually closed sockets stuck in TIME_WAIT for 60 s.The classic .NET cause is new HttpClient() per request. Fix it with a shared HttpClient using SocketsHttpHandler { PooledConnectionLifetime = ... }, or IHttpClientFactory. Diagnose with ls /proc/<pid>/fd | wc -l, lsof -p, ss -s and ss -tan state time-wait.
The .NET diagnostics tools all talk to the runtime over its diagnostics IPC channel, so they work on Windows, Linux and in containers without a debugger.
I start with counters because they are cheap, then pick the heavier tool the symptom points to. The trade-off is overhead and data sensitivity: a full dump contains every secret in memory.
How to tell it (STAR)
**S:** At [company], during [a sale], about 4% of our payment calls started failing while CPU sat at 30% and the provider said everything was fine. **T:** As [the on-call senior engineer], I had to stop the failures and find the cause. **A:** The shape of the errors, connect timeouts to several hosts, pointed at our outbound path. The App Service SNAT detector showed failed allocations, dotnet-counters showed hundreds of open connections, and a dump found a legacy class creating an HttpClient per call. I scaled out and cut retries to stop the bleeding, then moved the client to IHttpClientFactory, put SQL and Storage on private endpoints and added a NAT Gateway. **R:** Peak connections per instance fell from about 900 to [60], failed payment calls went to [zero], and we added a load test and an analyser rule so it can't creep back.
Last updated 23 Nov 2026.