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.
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.
"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.HttpClientis just a thin wrapper, so the rule is to reuse the handler: either one static or singletonHttpClientwithPooledConnectionLifetimeset to a few minutes, orIHttpClientFactory, which pools handlers and rotates them every two minutes by default. Creatingnew 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, butSocketsHttpHandleruses a single HTTP/2 connection per server and queues beyond the server's stream limit, typically 100, unless you setEnableMultipleHttp2Connections.SqlClient pools per exact connection string and identity.
Openborrows a connection,Disposereturns it and resets the session. The default maximum is 100. When all 100 are busy, the nextOpenwaits 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."
| 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 |
| 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 |
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.
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
Red flags
new HttpClient() in a using per callwithout 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.
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]
MaxConnectionsPerServer, then requests queue.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.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.
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.using, DataReader not disposed, connections held while awaiting another slow service.# 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.
new HttpClient() per call for 5,000 calls and watch netstat -an | grep TIME_WAIT grow; then reuse one client.Max Pool Size=5 in a test connection string, run 20 parallel queries with WAITFOR DELAY '00:00:05', and observe the pool timeout.http.client.request.time_in_queue with dotnet-counters while capping MaxConnectionsPerServer = 2.PooledConnectionLifetime keeps the old IP.sys.dm_exec_sessions to count your app's connections during a load test.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.)
time_in_queue, pooled vs active connections and query durations first.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.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.IHttpClientFactory into singletons and create clients on demand.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 |
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.
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.
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.
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.
Last updated 23 Nov 2026.