An ASP.NET Core 10 energy-meter API on Npgsql starts throwing 'The connection pool has been exhausted' under load; how do you find the cause and fix it?
answer
- hold time, not open count
- Maximum Pool Size 100, Timeout 15 s
- Npgsql meter: used versus idle connections
- connection held across a slow outgoing call
- await using on every exit path
basics
~20 sAll pooled connections stayed busy longer than the open Timeout (15 s by default) while more requests queued. Measure used versus idle connections, fix code that holds connections too long or never disposes them, and only then size the pool.
solid answer
~50 sThe message means every connection in the data source's pool, `Maximum Pool Size` (100 by default), was in use and an `OpenAsync` waited the full `Timeout` (15 s) for one. First I decide leak or capacity using Npgsql's `Npgsql` meter: if `db.client.connection.count` with state `used` stays at `db.client.connection.max` even when traffic drops, connections are not being returned; if it tracks load, requests hold them too long. Then I look for the usual causes: a connection or reader without `await using` on an exception path, a connection opened at the top of a handler and held across an outgoing HTTP call, a streamed `IAsyncEnumerable` response reading from an open reader, or a long transaction. I fix hold time first; raising `Maximum Pool Size` or `Timeout` only delays the failure and can push the database past its own connection limit across instances.
code
json · 5 lines{
"ConnectionStrings": {
"Meters": "Host=db;Database=meters;Username=meter_api;Maximum Pool Size=50;Timeout=15"
}
}go deeper
Recognise the pool-exhausted message and know that a missing await using on a connection or reader is the most common cause.
Explain Maximum Pool Size and Timeout, and why hold time rather than the number of opens decides how many requests a pool serves.
Use the Npgsql meter to tell a leak from a capacity limit, trace the holding code path, and size pools against instance count and the server's limit.
Own the connection budget across services and instances, with alerts on pending requests before users see timeouts.
## What the exception means Npgsql throws an `NpgsqlException` (with an inner `TimeoutException`) whose message reads: "The connection pool has been exhausted, either raise 'Max Pool Size' (currently 100) or 'Timeout' (currently 15 seconds) in your connection string." Microsoft.Data.SqlClient reports the same situation as an `InvalidOperationException`: "Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool...". Both say one thing: **every physical connection in the pool was borrowed, and a caller waited the whole open timeout without one coming back.** The message suggests raising the limits, but that is rarely the fix. ## Leak or capacity? Npgsql publishes pool metrics on a meter named `Npgsql`, tagged with the data source's pool name: | Instrument | What it tells you | |---|---| | `db.client.connection.count`, state `used` / `idle` | how many connections are borrowed versus waiting in the pool | | `db.client.connection.max` | the pool's upper bound | | `db.client.connection.npgsql.pending_requests` | callers queued for a connection | | `db.client.connection.npgsql.timeouts` | opens that gave up after `Timeout` | Read them over time: - **used pinned at the max even at night**: connections are borrowed and never returned, which is a leak; - **used tracks traffic and hits the max at peak**: each request holds a connection too long, or the load genuinely needs more; - **pending requests climbing before timeouts appear**: the early warning to alert on. ## The usual causes in ASP.NET Core code 1. **No disposal on an exception path.** `var conn = await dataSource.OpenConnectionAsync();` followed by code that throws before `Close()` leaves the connection borrowed for good: `NpgsqlConnection` suppresses finalization, so the garbage collector never returns it to the pool. 2. **An undisposed reader on a data-source command.** A command from `dataSource.CreateCommand(sql)` returns its connection only when its reader closes. 3. **Holding across non-database work.** The handler opens a connection first, then waits on an outgoing call to a tariff service, then queries. The connection sits idle-but-borrowed for the whole call. 4. **Streaming responses.** Returning an `IAsyncEnumerable<T>` that reads from an open reader keeps the connection until the last row is serialized, so slow clients hold connections. 5. **Long transactions** started early and committed late. 6. **Unbounded background work**, such as a fire-and-forget loop opening a connection per meter. ## Fixing the hold time ```csharp // before: the connection is held across the HTTP call await using var conn = await dataSource.OpenConnectionAsync(); var tariff = await tariffs.GetFromJsonAsync<Tariff>($"/tariffs/{siteId}"); var usage = await LoadUsageAsync(conn, siteId); // after: borrow it only for the query var tariff = await tariffs.GetFromJsonAsync<Tariff>($"/tariffs/{siteId}"); Usage usage; await using (var conn = await dataSource.OpenConnectionAsync()) { usage = await LoadUsageAsync(conn, siteId); } ``` Every connection, command and reader goes inside `await using`, and buffering rows into a list before returning frees the connection before serialization starts. ## Sizing, last Only when the hold time is short does pool size matter. Remember the arithmetic: each app instance has its own pool per connection string, so four instances with `Maximum Pool Size=100` can open 400 connections, and the database server has its own limit. Raising `Timeout` makes users wait longer for the same failure; `Pooling=false` turns every query into a full login; calling `NpgsqlConnection.ClearAllPools()` in a catch block throws away healthy connections without returning the leaked ones. ## A triage order that works 1. Confirm it is the pool: the exception type and message, plus a rising `db.client.connection.npgsql.timeouts` count. 2. Compare `used` with `db.client.connection.max` across a quiet period to separate a leak from load. 3. Search the code for opens without `await using`, readers left open, and connections opened before outgoing calls. 4. Fix hold time, deploy, and watch `pending_requests` fall before touching any limit. 5. Only then size `Maximum Pool Size` per instance against the server's total connection budget.
- The pool metrics show used connections at the max only at peak, and no leak. What do you change first?Shorten how long each request holds a connection: open after outgoing calls and CPU work, buffer results before serializing, and keep transactions tight. Then measure again. Only if hold time is already minimal do you raise `Maximum Pool Size`, checking that instances times pool size stays within the database server's connection limit.
- Why can a handler that returns IAsyncEnumerable<Reading> from an open data reader exhaust the pool even though it disposes everything?Disposal happens only when enumeration ends, and the response serializer enumerates while writing to the client. A slow or large download keeps the reader, and therefore the pooled connection, borrowed for the whole transfer. Under load many such responses pin the pool. Buffer the rows into a list, or stream from a dedicated bounded path.
- Raise Maximum Pool Size to 1000 and the exhaustion problem is solved.
- Set Pooling=false so every request gets its own fresh connection.
- Call NpgsqlConnection.ClearAllPools() in a catch block to recover from it.
- The garbage collector returns undisposed connections quickly enough under load.
- Opening a connection per query exhausts the pool; open one per request instead.