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

📚 Interview question

Your API starts throwing "Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached." Walk me through how you diagnose and fix SQL connection pool exhaustion: what you do in the first minutes, how you tell a leak from slow queries or too much concurrency, and how you stop it happening again.

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.

Mid-Level Debugging Intermediate connection-pool debugging ef-core microsoft-data-sqlclient production sql-server

🎯 Key points

  • The pool is per exact connection string per process (any difference in options makes a new pool), default Max Pool Size 100; the error means a request waited Connect Timeout (15 s) for a free connection
  • Three causes: leaked connections (not disposed), connections held too long (slow queries, transactions spanning HTTP calls), more concurrency than the pool
  • First minutes: recycle instances to clear leaked connections, roll back a recent change, check for blocking in SQL
  • Check SQL side: sys.dm_exec_sessions per host and Application Name, sleeping sessions with open transactions, blocking chains
  • Check app side: SqlClient pool counters (active, free, waiting) and dumps for SqlConnection objects not disposed
  • Fix leaks with using / await using and DbContext from DI; fix long holds by shortening transactions and tuning queries
  • Don't just raise Max Pool Size: session and worker limits vary by Azure SQL tier, and total connections = instances × pools × pool size
  • Prevent: CA2000 analyser, Application Name per service, pool counters on a dashboard, alert on pool waits, load test at peak

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 Open waits 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_sessions for my app's host name. Many sessions that are sleeping but have open_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 with dumpheap -type SqlConnection shows how many exist and gcroot shows 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."


The playbook, in order

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

Three causes, three signatures

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

Production example

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.

🔍 What the interviewer is checking

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

  • Explains the pool per connection string, Max Pool Size 100 and the connect timeout
  • Uses sys.dm_exec_sessions to separate sleeping (leaks, long holds) from running (slow DB)
  • Spots transactions held across HTTP calls
  • Thinks about total connections across all instances and the database tier's limits

Red flags

  • "Set Max Pool Size to 1000" or "turn off pooling"
  • Doesn't know using/await using returns the connection
  • Ignores the SQL Server side entirely

📚 Learn in depth

1. How the SqlClient pool works

process
└── 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
  • Key: the exact connection string. Two strings that differ by a space or option are two pools, which is one way to accidentally double your connections.
  • Defaults: Min Pool Size=0, Max Pool Size=100, Connect Timeout=15, Pooling=true.
  • Return: Dispose() or Close() returns the physical connection to the pool, and the next open runs sp_reset_connection to reset session state.
  • Idle pruning: idle connections are closed after a few minutes of inactivity.

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.

2. Why a leak eventually exhausts the pool

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.

3. Holding a connection across slow work

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.

4. The total connection budget

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.

5. Seeing it from both sides

  • SQL side: 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.
  • App side: SqlClient publishes event counters (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.

Try it yourself

  1. Write an endpoint that opens a 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.
  2. Run the session DMV query and see 100 sleeping sessions with your Application Name.
  3. Take a dump and run dumpheap -type Microsoft.Data.SqlClient.SqlConnection -stat.
  4. Fix it with await using and repeat; then add a 5 s Task.Delay inside a transaction and see exhaustion from long holds instead.
  5. Run dotnet-counters monitor --counters Microsoft.Data.SqlClient.EventSource while you load the endpoint.

💻 Code

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;

⚠ Common mistakes

  • Mistake: Raising 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.
  • Mistake: Creating 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.
  • Mistake: Making HTTP calls or publishing messages inside a database transaction. Why it is wrong: The connection and its locks are held for the whole call. Instead: Commit first, then call out; use the outbox pattern for consistency.
  • Mistake: Building connection strings dynamically with small differences. Why it is wrong: Each distinct string gets its own pool, so you get many small pools and more total connections. Instead: One canonical connection string per database.
  • Mistake: Turning pooling off to "fix" it. Why it is wrong: Every request pays a TCP, TLS and login handshake, often tens of milliseconds. Instead: Fix the leak or the long hold.
  • Mistake: Only looking at the app. Why it is wrong: Blocking or slow queries on the database are a common cause. Instead: Check sessions, waits and blocking on SQL Server too.
  • Mistake: Not setting Application Name. Why it is wrong: You can't tell which service owns which sessions. Instead: Set it per service in the connection string.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions transactions held open across calls Why: Checks transaction boundaries, DbContext lifetime and the outbox pattern
    How to answer

    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.

  2. When: Candidate compares it with socket exhaustion Why: Checks the related HttpClient and file descriptor exhaustion problem
    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 talks about pooling in general Why: Checks when pooling helps and the bugs pooled objects cause
    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

Pool exhaustion from an early return in a report endpoint
Situation
A customer portal API on [Azure App Service, four instances] against an Azure SQL [General Purpose] database, [about 250 requests/s]. A new reporting endpoint was released on [Monday].
Signals
About an hour after each instance started, all its requests began failing after exactly 15 seconds with the pool timeout message. App Insights showed exceptions on every endpoint, not just reports. The database's CPU was [20%]; Azure SQL showed sessions near the tier's limit.
Investigation
A session DMV query grouped by host showed [100] sleeping sessions per instance, all with the API's `Application Name`, many idle for 30+ minutes. No blocking chains. `dotnet-counters` with the SqlClient event source showed 100 active, 0 free. A dump showed [hundreds of] `SqlConnection` objects; `gcroot` and a code review led to the report endpoint returning early on a validation path before `Close()`.
Resolution
Immediate: recycled the instances on a staggered schedule every 45 minutes to clear leaked connections and disabled the reporting endpoint with a feature flag. Real fix: `await using` for the connection and validation before opening it, deployed that afternoon.
Prevention
Enabled CA2000 (dispose objects before losing scope) as a warning-as-error, added SqlClient pool counters and an alert on waiting requests, documented a fleet connection budget against the database tier's limits, and added a load test that runs the reporting endpoint for an hour.

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.

↩ Usually asked after

More in Debugging Production Issues

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me