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

📚 Interview question

How does connection pooling work for outbound HTTP and SQL calls in .NET? Explain how HttpClient and SocketsHttpHandler pool connections, why PooledConnectionLifetime matters, how SQL Server connection pooling works in Microsoft.Data.SqlClient, and what pool exhaustion looks like.

Covers HTTP connection pooling in SocketsHttpHandler (lifetimes, per-server limits, HTTP/2), IHttpClientFactory, SqlClient connection pooling (Max Pool Size, pool keys, leaks) and the symptoms of pool exhaustion.

Mid-Level Theory Intermediate api-performance connection-pooling httpclient performance sockets sqlclient

🎯 Key points

  • SocketsHttpHandler keeps a pool per scheme+host+port; reusing one handler avoids TCP and TLS handshakes per call
  • PooledConnectionLifetime (e.g. 2–5 min) recycles connections so DNS changes are seen; the default is infinite
  • Long-lived static/singleton HttpClient or IHttpClientFactory (handler lifetime 2 min by default), never new HttpClient per call
  • MaxConnectionsPerServer is unlimited by default; HTTP/2 multiplexes ~100 streams on one connection unless EnableMultipleHttp2Connections
  • SqlClient pools per exact connection string (+ identity); Max Pool Size defaults to 100 and Connect Timeout to 15 s
  • Exhaustion symptom: 'Timeout expired… all pooled connections were in use and max pool size was reached', usually a leak or slow queries, not a too-small pool
  • Watch http.client.open_connections and http.client.request.time_in_queue; SqlClient event counters for pooled and active connections

⏱ 30-second 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.

🗣 Full answer (senior)

How I would answer this in an interview

"A new outbound connection costs at least one round trip for TCP, one or two more for TLS, and for SQL Server a login and session setup. Across Azure regions that is tens of milliseconds and real CPU, so both the HTTP stack and SqlClient keep pools of open connections.

For HTTP, the pool lives in SocketsHttpHandler, keyed by scheme, host and port. HttpClient is just a thin wrapper, so the rule is to reuse the handler: either one static or singleton HttpClient with PooledConnectionLifetime set to a few minutes, or IHttpClientFactory, which pools handlers and rotates them every two minutes by default. Creating new HttpClient() per request gives you a fresh pool every time, so you pay the handshakes on every call and leave sockets in TIME_WAIT. The opposite mistake is a singleton client with no lifetime, which never notices that DNS moved to a new IP during a failover. Per-server limits matter too: HTTP/1.1 uses one request per connection, while HTTP/2 multiplexes, but SocketsHttpHandler uses a single HTTP/2 connection per server and queues beyond the server's stream limit, typically 100, unless you set EnableMultipleHttp2Connections.

SqlClient pools per exact connection string and identity. Open borrows a connection, Dispose returns it and resets the session. The default maximum is 100. When all 100 are busy, the next Open waits up to the connect timeout, 15 seconds, then throws the famous 'max pool size was reached'. The mistake I see is raising Max Pool Size to 500. Exhaustion nearly always means connections are leaked, held across slow work, or queries got slow; a bigger pool just pushes more concurrent load onto the database. Pools hide latency until they're empty, so I watch the queue, not the pool size."


HTTP pooling settings

Setting Default What to do
PooledConnectionLifetime Infinite 2–5 minutes for a singleton client
PooledConnectionIdleTimeout 1 minute Usually fine
MaxConnectionsPerServer int.MaxValue Cap it to protect a fragile downstream
EnableMultipleHttp2Connections false true for high-volume HTTP/2 or gRPC to one host
IHttpClientFactory handler lifetime 2 minutes Keep, or SetHandlerLifetime

SQL pooling facts

Fact Detail
Pool key Exact connection string + Windows/Entra identity
Max Pool Size 100 by default
Min Pool Size 0 by default
Connect Timeout 15 s, how long Open waits for a pooled connection
Reset sp_reset_connection on reuse; some settings (isolation level in older versions) can leak

Production example

A payments API built its connection string per request with a different Application Name, creating hundreds of tiny pools, and hit "max pool size" during an end-of-month spike. Using one connection string and fixing a repository that held connections open during an HTTP call to a fraud service dropped peak pooled connections from 100 (exhausted) to 18, and p95 from 4.2 s back to 140 ms.

🔍 What the interviewer is checking

Checks that the candidate understands how .NET pools HTTP and SQL connections, the settings that matter, and how to tell a real capacity problem from a leak.

Green flags

  • Explains TCP/TLS cost and per-host pools in SocketsHttpHandler
  • Knows PooledConnectionLifetime and the DNS problem
  • Knows SqlClient pools per connection string, default 100, and the timeout message
  • Treats exhaustion as a leak or slow-call symptom and names the metrics to check

Red flags

  • new HttpClient() in a using per call
  • "Increase Max Pool Size" as the first fix
  • Doesn't know where to see pool usage

📚 Learn in depth

1. Why pools exist

without pooling, every call:
  TCP SYN/SYN-ACK/ACK      1 RTT
  TLS 1.3 handshake        1 RTT (TLS 1.2: 2 RTT)
  request/response         1 RTT + server time
  close -> TIME_WAIT ~60-120 s on the client socket

with pooling:
  request/response         1 RTT + server time

At 20 ms RTT and 500 requests per second, per-call connections cost 20–40 ms each and burn thousands of ephemeral ports in TIME_WAIT, which leads to SocketException under load.

2. Inside SocketsHttpHandler

HttpClient --> SocketsHttpHandler
                 |-- HttpConnectionPoolManager
                       |-- pool[https://payments:443]
                       |     |-- idle connections (HTTP/1.1)
                       |     |-- active connections
                       |     |-- request queue (waits for a free connection)
                       |-- pool[https://catalogue:443]
  • HTTP/1.1: one in-flight request per connection; new connections are opened up to MaxConnectionsPerServer, then requests queue.
  • HTTP/2: many streams on one connection, up to the server's SETTINGS_MAX_CONCURRENT_STREAMS (Kestrel's default is 100). Beyond that, requests queue unless EnableMultipleHttp2Connections = true.
  • PooledConnectionLifetime stops a connection from being reused after the given age, so new connections resolve DNS again. Without it, a singleton client keeps talking to an old IP after a blue/green swap.

3. IHttpClientFactory

The factory caches HttpMessageHandler chains per named or typed client and rotates them after the handler lifetime (2 minutes). Old handlers are disposed once no client uses them. It also gives you a place for DelegatingHandlers and resilience (AddStandardResilienceHandler). Typed clients are transient; don't capture them in singletons, or you defeat the rotation.

4. SqlClient pooling

  • One pool per distinct connection string (character for character) and identity. Building the string dynamically fragments pools.
  • SqlConnection.Open() takes an idle connection or creates one if under Max Pool Size; otherwise it waits up to Connect Timeout.
  • Dispose()/Close() returns it; the next user triggers sp_reset_connection.
  • EF Core opens and closes connections per operation unless you open one explicitly or are in a transaction, so a long transaction holds a connection for its whole duration.
  • Leaks: missing using, DataReader not disposed, connections held while awaiting another slow service.

5. Seeing pool pressure

# HttpClient metrics (.NET 8+)
dotnet-counters monitor -n Payments.Api --counters System.Net.Http
#   http.client.open_connections, http.client.active_requests,
#   http.client.request.time_in_queue  <- the queue is the signal

# SqlClient event counters
dotnet-counters monitor -n Payments.Api --counters Microsoft.Data.SqlClient.EventSource
#   active-hard-connections, number-of-pooled-connections, number-of-active-connections

On the database side, sys.dm_exec_sessions grouped by program_name and host_name shows how many connections each app holds and whether they are sleeping with open transactions.

Try it yourself

  1. Write a loop that does new HttpClient() per call for 5,000 calls and watch netstat -an | grep TIME_WAIT grow; then reuse one client.
  2. Set Max Pool Size=5 in a test connection string, run 20 parallel queries with WAITFOR DELAY '00:00:05', and observe the pool timeout.
  3. Watch http.client.request.time_in_queue with dotnet-counters while capping MaxConnectionsPerServer = 2.
  4. Change a hostname's DNS record in a test and see that a client without PooledConnectionLifetime keeps the old IP.
  5. Query sys.dm_exec_sessions to count your app's connections during a load test.

💻 Code

Correct client registration and SQL usage that returns connections promptly:

// Program.cs
using System.Net;
using Microsoft.Data.SqlClient;

var builder = WebApplication.CreateBuilder(args);

// Typed client through IHttpClientFactory: handlers pooled and rotated for you.
builder.Services.AddHttpClient<FraudClient>(c =>
    {
        c.BaseAddress = new Uri("https://fraud.internal");
        c.Timeout = TimeSpan.FromSeconds(5);
    })
    .ConfigurePrimaryHttpMessageHandler(() => new SocketsHttpHandler
    {
        PooledConnectionLifetime = TimeSpan.FromMinutes(3), // see DNS changes
        MaxConnectionsPerServer = 50,                        // protect the downstream
        EnableMultipleHttp2Connections = true
    })
    .SetHandlerLifetime(Timeout.InfiniteTimeSpan);           // lifetime handled by PooledConnectionLifetime

// One connection string from configuration: one pool.
builder.Services.AddSingleton(_ =>
    new SqlConnectionStringBuilder(builder.Configuration.GetConnectionString("Payments"))
    { MaxPoolSize = 100, ConnectTimeout = 15 }.ConnectionString);

var app = builder.Build();
app.MapGet("/payments/{id:int}/risk", async (int id, PaymentRepository repo, FraudClient fraud, CancellationToken ct) =>
{
    var payment = await repo.GetAsync(id, ct);     // connection returned before the HTTP call
    return payment is null ? Results.NotFound() : Results.Ok(await fraud.ScoreAsync(payment, ct));
});
app.Run();

public sealed record Payment(int Id, decimal Amount);

public sealed class FraudClient(HttpClient http)
{
    public async Task<int> ScoreAsync(Payment p, CancellationToken ct) =>
        await http.GetFromJsonAsync<int>($"/score?amount={p.Amount}", ct);
}

public sealed class PaymentRepository(string connectionString)
{
    public async Task<Payment?> GetAsync(int id, CancellationToken ct)
    {
        await using var conn = new SqlConnection(connectionString); // borrowed from the pool
        await conn.OpenAsync(ct);
        await using var cmd = new SqlCommand("SELECT Id, Amount FROM dbo.Payments WHERE Id = @id", conn);
        cmd.Parameters.AddWithValue("@id", id);
        await using var reader = await cmd.ExecuteReaderAsync(ct);
        return await reader.ReadAsync(ct) ? new Payment(reader.GetInt32(0), reader.GetDecimal(1)) : null;
    } // disposed here: back in the pool before any slow downstream call
}

(PaymentRepository would be registered with AddScoped in a real app.)

⚠ Common mistakes

  • Mistake: Optimising without measuring, e.g. raising Max Pool Size because "pools are slow". Why it is wrong: you don't know whether the pool is the bottleneck or a symptom. Instead: look at time_in_queue, pooled vs active connections and query durations first.
  • Mistake: Micro-optimising connection settings for a service that makes a handful of calls a minute. Why it is wrong: defaults are fine at low volume. Instead: tune only the hot downstream paths shown by telemetry.
  • Mistake: new HttpClient() per request, wrapped in using. Why it is wrong: each call opens a new pool, pays TCP+TLS and leaves sockets in TIME_WAIT. Instead: IHttpClientFactory or a long-lived client.
  • Mistake: A static HttpClient with no PooledConnectionLifetime. Why it is wrong: it never re-resolves DNS, so failovers and slot swaps are missed. Instead: set a lifetime of a few minutes.
  • Mistake: Raising Max Pool Size to 1,000 to fix exhaustion. Why it is wrong: it hides leaks and moves the overload to SQL Server (worker threads, locks). Instead: fix leaks, shorten connection hold time, and tune slow queries.
  • Mistake: Building connection strings per request or per tenant with small differences. Why it is wrong: every variant creates its own pool. Instead: one canonical string per database.
  • Mistake: Holding a SQL connection or transaction open while awaiting a slow HTTP call. Why it is wrong: pooled connections are tied up for the slowest dependency's latency. Instead: read, release, then call out.
  • Mistake: Capturing a typed client in a singleton. Why it is wrong: its handler is never rotated. Instead: inject IHttpClientFactory into singletons and create clients on demand.

🏛 Senior insight: trade-offs

Pools are a latency optimisation and a back-pressure mechanism at the same time. A senior uses the pool limit deliberately: capping MaxConnectionsPerServer or Max Pool Size protects a downstream that can't handle more concurrency, and the queue that forms is the signal that something upstream is too slow. Tuning starts from the metrics (time_in_queue, active vs pooled connections) and ends with a load test that proves the queue is gone at the target throughput.

Option When it fits Cost When not to
IHttpClientFactory typed clients Most ASP.NET Core apps DI registration Console tools with one call
Singleton client + PooledConnectionLifetime Libraries, high-volume single host You manage handlers yourself When you need per-client handler pipelines
Raise Max Pool Size Proven high legitimate concurrency, DB has headroom More load on SQL As a fix for leaks or slow queries
Cap MaxConnectionsPerServer Fragile downstream Requests queue When the queue would breach your SLO

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions TIME_WAIT or socket exhaustion Why: Checks they can diagnose socket exhaustion and too-many-open-files at the OS level.
    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.

  2. When: Candidate confuses DbContext pooling with connection pooling Why: Checks they know DbContext pooling is a separate layer from SqlClient connection pooling and what it resets.
    How to answer

    DbContext pooling keeps a pool of context instances and hands one out per scope instead of constructing a new one, saving the setup cost and allocations of each context. AddDbContextPool<T>() registers a scoped lease; AddPooledDbContextFactory<T>() registers a singleton factory for background work. When a lease ends, EF Core resets its own state: the change tracker, tracking options, the current transaction. It does not reset your fields, so a TenantId property set in one request can leak into the next. Pooled contexts must have a single constructor taking DbContextOptions and can't inject scoped services. For per-request values I wrap the pooled factory in a scoped factory that sets them on every lease. The trade-off: the gain is real but small per request, worth it at high throughput, and it adds a class of state bugs.

  3. When: Candidate talks about pooling in general Why: Checks their judgement on when object pooling helps and when it slows things down.
    How to answer

    Object Pool keeps reusable objects so callers rent and return them instead of allocating. In .NET it helps when objects are expensive to create or are large (connections, big buffers, arrays over 85 KB that land on the LOH), or when churn is extreme.

    • ObjectPool<T> (Microsoft.Extensions.ObjectPool): a policy creates and resets objects, IResettable exists from .NET 8, and it retains ProcessorCount * 2 objects by default.
    • ArrayPool<T>.Shared: Rent can return a bigger array than you asked for, and you must never touch it after Return.
    • AddDbContextPool resets EF state but not your own fields. Connection pooling is automatic per connection string.

    Pooling can be slower: a gen0 allocation is a pointer bump, while a pool adds synchronisation, reset cost and long-lived objects. Bad resets leak data between users. Prove the benefit with BenchmarkDotNet and dotnet-counters before adopting a pool.

🛠 Real-world problems: how you handle them

SQL pool exhaustion caused by holding connections across an HTTP call
Situation
A payments API on Azure App Service in Australia East, [6] instances, Azure SQL S3. End-of-month batch traffic is about [4×] normal. A downstream fraud-scoring service slowed from 80 ms to 1.5 s.
Signals
Application Insights shows `InvalidOperationException: Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool` on many endpoints, including ones that don't call the fraud service. p95 rises from 140 ms to 15 s (the connect timeout). Azure SQL DTU is only 35%.
Investigation
dotnet-counters on one instance with `Microsoft.Data.SqlClient.EventSource`: number-of-active-connections pinned at 100 per pool. `sys.dm_exec_sessions` shows ~600 sessions from the app, most 'sleeping' with open transactions. A dotnet-dump of a stuck instance (`dumpasync`) shows many requests awaiting `FraudClient.ScoreAsync` inside a repository method that opened a transaction first. Application Insights dependency timings confirm the fraud call duration matches connection hold time.
Resolution
Immediate: reduced the fraud client timeout to 2 s with a fallback score, which freed connections within minutes. Real fix: restructured the handler to read the payment, release the connection, call the fraud service, then open a short transaction for the write. Removed a per-request `Application Name` that fragmented pools.
Prevention
Alert on `time_in_queue` style metrics and on 'max pool size' exceptions; code review checklist item 'no outbound I/O inside a DB transaction'; a k6 load test with a slowed fraud stub in the pipeline; an ADR on connection and transaction scope.

How to tell it (STAR)

**S:** At [company], our payments API started timing out across almost every endpoint during the end-of-month peak, even though the database was only at a third of its capacity. **T:** As [the on-call senior engineer], I had to restore service and find out why the connection pool was exhausted. **A:** I used dotnet-counters to confirm all 100 pooled connections were active, and `sys.dm_exec_sessions` showed hundreds of sleeping sessions with open transactions. A dump showed requests awaiting the fraud service inside a transaction, and that service had slowed to 1.5 seconds. I cut the fraud timeout with a safe fallback to stop the bleeding, then reordered the handler so we release the connection before calling out, and unified the connection string. **R:** Peak pooled connections fell from 100 to [18], p95 returned to [140 ms], and we added a load test with a slow downstream so it couldn't come back unnoticed.

↩ Usually asked after

More in API Performance

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me