📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

Under load, your ASP.NET Core API on Azure App Service starts failing calls to an external payment API and to other services with intermittent connection timeouts and SocketExceptions, while CPU and memory look fine. How do you diagnose connection or SNAT port exhaustion, and how do you fix it?

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.

Senior Debugging Advanced api-performance connection-pooling debugging httpclient performance snat

🎯 Key points

  • Symptoms: intermittent connect timeouts and SocketException to many destinations, low CPU, worse at peak, fine after restart
  • Azure SNAT: each outbound connection to a public IP:port takes a SNAT port from a small per-instance pool (App Service preallocates 128); opening a new connection per request instead of reusing pooled keep-alive connections is what drains it
  • Closed connections hold their port for a while (TIME_WAIT on the client, idle timeout on the SNAT mapping), so connection churn rate, not concurrent connections, sets port usage
  • Evidence: App Service SNAT Port Exhaustion detector (successful vs failed SNAT allocations), Load Balancer SNAT connection count metrics, dependency failure rate by target in Application Insights
  • dotnet-counters System.Net.Http: http.client.open_connections and http.client.request.time_in_queue; ss/netstat for TIME_WAIT counts; dumpheap for HttpClient/SocketsHttpHandler instances
  • Root causes: new HttpClient per call, sync-over-async or blocking that stretches connection hold time, PooledConnectionLifetime too short, unbounded concurrency bursts
  • Fix: reuse connections (IHttpClientFactory), async all the way, bound concurrency, private endpoints for Azure PaaS, VNet integration + NAT Gateway (64,512 ports per public IP)
  • Verify with a load test at peak rate and keep alerts on SNAT failures and connection metrics

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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_connections climbing into the hundreds and requests queuing, and a dump showed a legacy class doing new HttpClient() per call. The quick mitigation was scaling out to spread connections. The fix was moving that client to IHttpClientFactory, 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."


Diagnosis map

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

Fixes

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

Production example

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.

🔍 What the interviewer is checking

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

  • Reads low CPU + connect timeouts to many hosts as a network-layer problem
  • Knows SNAT ports, the App Service detector and dotnet-counters HTTP metrics
  • Finds per-call HttpClient or unbounded fan-out as the root cause
  • Proposes reuse, private endpoints and NAT Gateway, and verifies with a load test

Red flags

  • Raises timeouts or adds retries as the fix
  • Blames the downstream without evidence
  • Only scales out

📚 Learn in depth

1. How outbound traffic leaves App Service

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.

2. TIME_WAIT and why churn, not concurrency, drains ports

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.

3. Why per-call clients burn ports

  • new HttpClient() creates a new SocketsHttpHandler and pool, so every call opens a new TCP connection, completes the TLS handshake, then closes it.
  • The closed socket sits in TIME_WAIT, and the SNAT mapping lingers too.
  • A reused pool of, say, 20 keep-alive connections serves the same traffic with 20 ports.

4. Queueing vs exhaustion

  • Queueing (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.
  • Exhaustion (connect timeouts, SocketException, SNAT failures): no new connection can be made at all.

Both often have the same root cause: unbounded concurrency or no reuse.

5. Investigation steps

  1. App Service Diagnose and solve problems → SNAT Port Exhaustion and TCP Connections detectors; compare successful vs failed SNAT allocations over time and correlate with errors.
  2. Application Insights: dependency failure rate and exception types by target; failures across many unrelated targets at once point at your side.
  3. 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.
  4. ss -tan | awk '{print $1}' | sort | uniq -c to count connection states; TIME_WAIT in the thousands is a red flag.
  5. 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.

6. Fixes in depth

  • Reuse: typed clients via IHttpClientFactory; for singletons, one HttpClient with SocketsHttpHandler.PooledConnectionLifetime of a few minutes.
  • Async all the way: no .Result/.Wait(), so responses are read and connections returned promptly.
  • Bound: cap fan-out with Parallel.ForEachAsync DOP or MaxConnectionsPerServer, so a burst queues instead of opening hundreds of sockets.
  • Avoid SNAT: private endpoints for Azure SQL, Storage, Service Bus, Key Vault; traffic stays on the VNet.
  • More ports: VNet integration with a NAT Gateway (64,512 ports per public IP, up to 16 public IPs) and stable outbound IPs for partner allow-lists.
  • Retries: use jittered retries with a circuit breaker at one layer; aggressive retries on connect failures make exhaustion worse.

Try it yourself

  1. In a test App Service, run a load test against an endpoint that does new HttpClient() per call to a public URL, and open the SNAT detector.
  2. Repeat with IHttpClientFactory and compare http.client.open_connections in dotnet-counters.
  3. Count TIME_WAIT sockets with ss before and after the change, and check them against the formula above.
  4. Set MaxConnectionsPerServer = 4, push 100 concurrent requests and watch time_in_queue rise without errors.
  5. Take a dump and use dumpheap -stat to count HttpClient and SocketsHttpHandler instances.

💻 Code

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

⚠ Common mistakes

  • Mistake: Optimising without measuring, e.g. raising timeouts because "the payment provider is slow". Why it is wrong: the provider may be fine; your instance can't open connections, and a longer timeout just holds requests, threads and memory longer, so queues build further upstream. Instead: check the SNAT detector (failed vs successful allocations), connection counters and socket states first.
  • Mistake: Micro-optimising serialisation or handler code while connections churn. Why it is wrong: the bottleneck is the network layer, not CPU, so CPU profiles look healthy and send you the wrong way. Instead: fix connection reuse first, then profile.
  • Mistake: Adding aggressive retries on connect failures. Why it is wrong: each retry needs another connection and SNAT port; with several services retrying at each layer (gateway, BFF, service) one failed call can become dozens of connection attempts, turning a partial outage into a full one. Instead: retry at one layer only, with jitter, a retry budget and a circuit breaker, after fixing reuse.
  • Mistake: Treating scale-out as the fix. Why it is wrong: each instance gets its own ports, so it helps for a while, but autoscale rules driven by CPU won't trigger (CPU is low), and growth brings the problem back. Instead: reuse connections and remove SNAT from Azure-internal traffic; scale out only as a stopgap.
  • Mistake: 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.
  • Mistake: Blocking on async calls (.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.
  • Mistake: Setting 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.
  • Mistake: Reaching Azure SQL, Storage or Key Vault over public endpoints from App Service at high volume. Why it is wrong: that traffic shares the same SNAT pool as your third-party calls, so a chatty storage client can break payments. Instead: private endpoints or service endpoints, which bypass SNAT.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions connection pools or PooledConnectionLifetime Why: Checks their depth on HTTP and SQL connection pooling settings.
    How to answer

    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.

    • HTTP: 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.
    • SQL: 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.

  2. When: Candidate mentions TIME_WAIT or 'Too many open files' Why: Checks they can diagnose socket and file descriptor exhaustion at the OS level on Linux.
    How to answer

    Two different limits produce similar errors:

    1. Descriptor exhaustion (EMFILE, "Too many open files"): the process hit its ulimit -n. Something is leaking files or sockets.
    2. Ephemeral port exhaustion (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.

  3. When: Candidate names dotnet-counters, dotnet-trace or dotnet-dump Why: Checks they know what each diagnostics tool tells you and when to reach for it.
    How to answer

    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.

    • dotnet-counters shows live metrics (CPU, GC heap size, allocation rate, ThreadPool queue length, exceptions) with almost no overhead. It tells you what kind of problem you have.
    • dotnet-trace records an EventPipe trace with CPU samples and runtime events; it tells you where time goes.
    • dotnet-gcdump captures the managed heap graph (types, sizes and references). Comparing snapshots shows what is growing; the reference paths show what keeps it alive. dotnet-dump captures the whole process for SOS analysis of hangs and native memory.
    • dotnet-monitor wraps all of this as an HTTP API or sidecar with triggers, which is how you use them in Kubernetes or Container Apps.

    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.

🛠 Real-world problems: how you handle them

SNAT port exhaustion during a sale breaks payment calls
Situation
A checkout API on Azure App Service (Premium v3, [4] instances, Australia East) calling a [third-party payment provider], Azure SQL and Blob Storage over public endpoints. A [mid-year sale] raised traffic to [6×] normal.
Signals
Application Insights showed ~4% of payment calls failing with `SocketException` and `TaskCanceledException` at connect time, plus some SQL connection timeouts. CPU at 30%, memory flat. The provider's status page was green. Restarting an instance helped for about ten minutes.
Investigation
The App Service SNAT Port Exhaustion detector showed failed SNAT allocations matching the error spikes. dotnet-counters via Kudu SSH showed `http.client.open_connections` around 900 and climbing. `ss` showed thousands of TIME_WAIT sockets to the provider's IPs. A dotnet-dump with `dumpheap -stat` found hundreds of `SocketsHttpHandler` instances, traced to a legacy gateway class creating `HttpClient` per call.
Resolution
Immediate: scaled out to [10] instances and reduced retry counts to stop the amplification. Fix: moved the gateway to `IHttpClientFactory` with `PooledConnectionLifetime` and `MaxConnectionsPerServer`, added private endpoints for Azure SQL and Storage, and VNet integration with a NAT Gateway for internet egress.
Prevention
Alerts on SNAT failures and `http.client.open_connections`; a banned-API analyser rule for `new HttpClient()` outside the composition root; a k6 load test at [6×] traffic before sales; an ADR on egress via NAT Gateway and private endpoints.

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.

More in API Performance

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me