A production playbook for SQL connection pool exhaustion in .NET: the error, how the SqlClient pool works, distinguishing leaked connections from long-held connections and genuine concurrency, the counters and queries to check, the fix and prevention.
The message means a request waited the Connect Timeout (15 s by default) for a free connection and the pool was at Max Pool Size (100 by default, per connection string, per process). There are three causes: leaked connections that are never disposed, connections held too long (slow queries, blocking, or a transaction held open across an HTTP call), and more concurrency than the pool. I check the SQL side (sys.dm_exec_sessions grouped by host and status: lots of sleeping sessions with open transactions means leaks or long holds; blocking chains mean slow work) and the app side (SqlClient pool counters and a dump for undisposed SqlConnections). A restart buys time; the fix is await using, shorter transactions and faster queries. Raising Max Pool Size alone usually moves the bottleneck to SQL Server.
"That message is very specific: the request didn't fail talking to SQL Server, it failed waiting for a connection from the client-side pool. Microsoft.Data.SqlClient keeps one pool per unique connection string per process, with a default maximum of 100. When all 100 are checked out, the next
Openwaits up to the connect timeout, 15 seconds by default, and then throws. So the question is: why are 100 connections checked out?There are three answers. One, a leak: code opens a connection or creates a DbContext manually and doesn't dispose it on some path, so the connection only goes back when the GC finalises it, which may be never. Two, connections are held too long: queries got slow, there's blocking in SQL, or someone opened a transaction and then called an HTTP API inside it. Three, genuine concurrency: 300 concurrent requests each needing a connection against a pool of 100. To tell them apart I look at SQL Server:
sys.dm_exec_sessionsfor my app's host name. Many sessions that are sleeping but haveopen_transaction_count > 0, or that were last active minutes ago, mean leaks or long holds. Many running or suspended sessions with blocking means the database is slow. On the app side, the SqlClient counters show active, idle and waiting connections, and a dump withdumpheap -type SqlConnectionshows how many exist andgcrootshows who's holding them.In the first minutes, restarting or recycling instances clears leaked connections and buys time, and if this started after a release I roll back. The mistake I see is setting
Max Pool Size=1000. With twenty pods that's twenty thousand potential connections to a database whose tier allows a fraction of that, and if the cause was slow queries you've just made them slower."
| Step | What I do | Tool or command |
|---|---|---|
| 1. Symptom | InvalidOperationException with the pool timeout message; request failures spike |
App Insights exceptions, logs |
| 2. First five minutes | Roll back if a release lines up; recycle instances to free leaked connections; check SQL for blocking | Deployment history, App Service restart, sp_WhoIsActive or DMVs |
| 3. Data to collect | Sessions per host on SQL; pool counters in the app; a dump if a leak is suspected | DMVs, dotnet-counters, dotnet-dump |
| 4. Rule out | Slow database (running sessions, waits) vs leak (sleeping sessions) vs concurrency (request rate vs pool size) | DMVs, Query Store, request metrics |
| 5. Root cause | The code path that doesn't dispose, or holds a connection across slow work | gcroot, code review of the endpoint |
| 6. Fix | await using, DI-scoped DbContext, short transactions, query tuning |
Code change |
| 7. Prevention | Analysers, pool dashboard and alert, load test | CA2000, Azure Monitor |
| Leak | Held too long | Too much concurrency | |
|---|---|---|---|
| SQL sessions for the app | Many sleeping, old last_request_end_time |
Many running/suspended, or sleeping with open transactions | Count ≈ pods × Max Pool Size, all busy briefly |
| Grows with time | Yes, until restart | With load and query time | With traffic only |
| After restart | Fixed for a while | Comes back at the same load | Comes back at the same load |
| Typical fix | Dispose properly | Shorter transactions, faster queries, no HTTP inside transactions | Limit concurrency, cache, or raise the pool and the database tier |
In a typical case a background report endpoint creates new SqlConnection and returns early on a validation path without disposing it. Each call leaks one connection; at 30 report calls a minute the pool of 100 is exhausted after about an hour on each instance, and every endpoint on that instance starts failing after a 15-second wait. The DMV shows 100 sleeping sessions per host; the fix is one await using and the error disappears, with active connections per instance settling at 8–12.
Checks that the candidate understands how the SqlClient pool works, can distinguish leaks, long holds and concurrency with evidence from both the app and SQL Server, and fixes the cause instead of raising the pool size.
Green flags
sys.dm_exec_sessions to separate sleeping (leaks, long holds) from running (slow DB)Red flags
using/await using returns the connectionprocess
└── pool group (per exact connection string)
└── pool (per identity when using Windows auth)
├── idle connections ── Open() takes one
├── active connections ── Dispose()/Close() returns it
└── waiters ── wait up to Connect Timeout, then throw
Min Pool Size=0, Max Pool Size=100, Connect Timeout=15, Pooling=true.Dispose() or Close() returns the physical connection to the pool, and the next open runs sp_reset_connection to reset session state.EF Core opens and closes the connection around each query or SaveChanges unless you open it yourself or start a transaction, in which case it stays open until you close or commit.
An undisposed SqlConnection stays checked out until the object becomes unreachable and is finalised. Under steady load, the GC may not collect it for a long time, so leaked connections accumulate faster than they're reclaimed. DbContext created with new and not disposed has the same problem whenever it has opened a connection.
Anything slow inside a transaction keeps a connection checked out: an HTTP call, a message publish, a long LINQ-to-objects loop, or waiting on a lock. If the HTTP call takes 5 s and you do 30 per second, you need 150 connections just for that. Transactions also hold locks, so other requests block and hold their connections too: the two causes feed each other.
Total possible connections = instances × pools per instance × Max Pool Size. Azure SQL tiers cap concurrent sessions and workers; the vCore and DTU limits differ by tier, so check the current resource limits page for your tier rather than assuming. If 20 pods each can open 100, that's 2,000 connections, which can exceed worker limits long before CPU looks busy, and then SQL starts rejecting work.
sys.dm_exec_sessions (status, open_transaction_count, last_request_end_time, host_name, program_name), sys.dm_exec_requests for waits and blocking, Query Store for queries that slowed down.Microsoft.Data.SqlClient.EventSource) such as active, free and pooled connections; recent versions also publish System.Diagnostics.Metrics. Set Application Name in the connection string so sessions are easy to find.SqlConnection and doesn't dispose it; call it 101 times against a local SQL Server container and watch call 101 wait 15 s and throw.Application Name.dumpheap -type Microsoft.Data.SqlClient.SqlConnection -stat.await using and repeat; then add a 5 s Task.Delay inside a transaction and see exhaustion from long holds instead.dotnet-counters monitor --counters Microsoft.Data.SqlClient.EventSource while you load the endpoint.Two classic leaks and long holds, and the fixed versions.
// Before: an early return skips Close(), and an HTTP call runs inside a transaction.
public async Task<IResult> ExportAsync(int customerId)
{
var conn = new SqlConnection(_connectionString);
await conn.OpenAsync();
if (customerId <= 0) return Results.BadRequest(); // leaked connection
// ...
conn.Close();
return Results.Ok();
}
public async Task PlaceOrderAsync(Order order)
{
await using var tx = await _db.Database.BeginTransactionAsync();
_db.Orders.Add(order);
await _db.SaveChangesAsync();
await _payments.ChargeAsync(order); // 2-5 s HTTP call holding a connection and locks
await tx.CommitAsync();
}
// After: deterministic disposal, short transactions, slow work outside them.
namespace Orders.Data;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
public sealed class ExportService(string connectionString)
{
public async Task<int> CountOrdersAsync(int customerId, CancellationToken ct)
{
if (customerId <= 0) throw new ArgumentOutOfRangeException(nameof(customerId)); // validate before opening
await using var conn = new SqlConnection(connectionString); // always returned to the pool
await conn.OpenAsync(ct);
await using var cmd = new SqlCommand("SELECT COUNT(*) FROM dbo.Orders WHERE CustomerId = @id", conn);
cmd.Parameters.AddWithValue("@id", customerId);
return (int)(await cmd.ExecuteScalarAsync(ct))!;
}
}
public sealed class OrderService(OrdersDbContext db, IPaymentsClient payments)
{
public async Task PlaceOrderAsync(Order order, CancellationToken ct)
{
order.Status = OrderStatus.PendingPayment;
db.Orders.Add(order);
await db.SaveChangesAsync(ct); // short implicit transaction; connection returned
var result = await payments.ChargeAsync(order.Id, order.Total, ct); // no connection held here
order.Status = result.Succeeded ? OrderStatus.Paid : OrderStatus.PaymentFailed;
await db.SaveChangesAsync(ct); // second short transaction
}
}
-- Who holds connections, and are they working or idle?
SELECT s.host_name, s.program_name, s.status,
COUNT(*) AS sessions,
SUM(CASE WHEN s.open_transaction_count > 0 THEN 1 ELSE 0 END) AS with_open_tran,
MIN(s.last_request_end_time) AS oldest_activity
FROM sys.dm_exec_sessions AS s
WHERE s.is_user_process = 1
GROUP BY s.host_name, s.program_name, s.status
ORDER BY sessions DESC;
-- Blocking chains right now
SELECT r.session_id, r.blocking_session_id, r.wait_type, r.wait_time, t.text
FROM sys.dm_exec_requests AS r
CROSS APPLY sys.dm_exec_sql_text(r.sql_handle) AS t
WHERE r.blocking_session_id <> 0;
Max Pool Size to 1000 as the fix. Why it is wrong: It multiplies across instances, can exceed the database's session and worker limits, and makes slow-query problems worse. Instead: Find why connections are held; size the pool from measured concurrency.SqlConnection or DbContext without using. Why it is wrong: Any early return or exception leaks a connection until finalisation. Instead: await using, or let DI own the DbContext lifetime.Application Name. Why it is wrong: You can't tell which service owns which sessions. Instead: Set it per service in the connection string.Pool exhaustion is a symptom, and its message misleads people into tuning the pool. The senior move is to treat the pool as a gauge: if connections are held, ask what they're doing. Most real cases are long holds rather than raw leaks, often a transaction stretched across an HTTP call, and those are design issues that the outbox pattern and short transactions fix.
The other senior consideration is the fleet-wide connection budget. Autoscaling adds instances and therefore pools; a scale-out during an incident can push total connections past what the database tier allows and make the outage worse. Check the current resource limits for your Azure SQL tier (they differ between DTU and vCore tiers and by size) and write the budget down.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Recycle instances | Leak confirmed, need time | Brief capacity dip | As the fix |
| Raise Max Pool Size | Measured concurrency genuinely exceeds 100 and the database has headroom | More sessions on SQL | When sessions are sleeping (leak) or blocked (slow DB) |
| Set Min Pool Size | Cold-start latency after idle periods matters | Idle sessions held on SQL | As a fix for exhaustion: it changes the floor, not the ceiling |
| Shorten transactions / outbox | Transactions span external calls | Refactor, eventual consistency | Never skip it when HTTP runs inside a transaction |
| Limit concurrency to the DB | Bursty endpoints overwhelm the pool | Queueing or 429s | When latency must stay low for all requests |
The boundary is the use case: one request or message handler loads what it needs, changes the aggregate, and calls SaveChanges once, which EF Core already runs in a transaction. The DbContext is scoped to that request or message. I add an explicit transaction only when several saves or ExecuteUpdate calls must commit together, wrapped in the execution strategy when retries are on.
I never keep a transaction open across a remote call: it holds locks for the other service's latency, and the other side cannot roll back anyway. When the use case must also publish an event, I write it to an outbox table in the same transaction and relay it afterwards.
The trade-off: short local transactions and eventual consistency between services, instead of the false comfort of distributed transactions.
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.
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 portal API started failing on every endpoint about an hour after each restart, with the 'obtaining a connection from the pool' timeout. **T:** I had to keep the portal usable and find the leak. **A:** I staggered restarts to buy time and turned off the new report endpoint. On SQL Server, the session DMV showed a hundred sleeping sessions per instance, so it was a leak, not slow queries. A dump and a quick code review found an early return that skipped closing the connection. I fixed it with `await using`, enabled the CA2000 analyser as an error and added a pool-waits alert. **R:** Active connections per instance dropped from 100 to [about 10], the errors stopped completely, and the analyser has since blocked [three] similar leaks in pull requests.
Last updated 23 Nov 2026.