# Fixing "Timeout Expired: Connection Pool Exhausted" in .NET

> "Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool" is rarely a capacity problem. The usual cause is a leak: connections that were opened and never returned. Here is how to find the leak with pool metrics and database queries before you raise MaxPoolSize.

Published: 2026-11-26. Author: Milan Jovanović.

Canonical: https://milanjovanovic.tech/blog/connection-pool-exhausted-timeout-dotnet

The error arrives in production, never in development:

```text
System.InvalidOperationException: 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.
```

That text is SqlClient's.
Npgsql reports the same condition as an `NpgsqlException` (with an inner `TimeoutException`) that starts with "The connection pool has been exhausted".

The tempting fix is right there in the message: raise the maximum pool size.
Resist it.
Treat the error as a leak or a long-held connection until measurements prove that the configured capacity is too low.
A bigger pool can postpone the same failure until a busier day.

## How the Pool Works (30 Seconds)

Opening a physical database connection costs a TCP handshake, TLS negotiation, and authentication.
So ADO.NET providers pool them: `connection.Open()` rents from the pool, `connection.Dispose()` returns it.
The pool is keyed by connection string, and the maximum pool size defaults to **100** for both SqlClient and Npgsql.
The connection string key is `Max Pool Size` in SqlClient and `Maximum Pool Size` in Npgsql, and Npgsql 10 throws an `ArgumentException` at startup for `Max Pool Size`.

**Dispose is what returns the connection.**
A connection that's opened and never disposed stays checked out.

Npgsql never takes a leaked connection back, so it is gone until the process restarts.
SqlClient can reclaim one, but only after the garbage collector has collected the abandoned `SqlConnection`, and you don't control when that happens.
100 leaked connections later, every `Open()` waits for the connection timeout (15 seconds by default in both providers) and then throws the error above.

![A connection pool hands connections to your code; disposing returns them, but a code path that skips disposal leaks the connection, and an empty pool makes the next Open wait until it throws the pool-exhausted timeout](https://milanjovanovic.tech/blogs/articles/connection-pool-exhausted-timeout-dotnet/pool-rent-return-leak.png)

## The Usual Suspects, in Order of Likelihood

**1. A code path that skips disposal.**
The classic is manual ADO.NET without `using`, where the error path leaks:

```csharp
// BROKEN: if ExecuteReaderAsync throws, the connection never returns
public async Task<List<Order>> GetOrdersAsync()
{
    var connection = new NpgsqlConnection(_connectionString);
    await connection.OpenAsync();

    var command = new NpgsqlCommand("SELECT * FROM orders", connection);
    var reader = await command.ExecuteReaderAsync();
    // ...
}
```

The fix is mechanical, `await using` on everything that touches the connection:

```csharp
public async Task<List<Order>> GetOrdersAsync()
{
    await using var connection = new NpgsqlConnection(_connectionString);
    await connection.OpenAsync();

    await using var command = new NpgsqlCommand("SELECT * FROM orders", connection);
    await using var reader = await command.ExecuteReaderAsync();

    var orders = new List<Order>();
    while (await reader.ReadAsync())
    {
        orders.Add(MapOrder(reader));
    }

    return orders;
}
```

This applies equally to Dapper code, which is just ADO.NET underneath.

**2. DbContext lifetime mistakes.**
EF Core returns the connection when the operation completes or the context is disposed.
The leaks come from lifetime bugs: a `DbContext` resolved from a singleton service (captive dependency), contexts created with `new` and never disposed, or an `IDbContextFactory` context without `await using`.
If you're fuzzy on scoped-vs-singleton capture rules, that's the first thing to audit; I covered them in **dependency injection lifetimes in .NET**.

**3. Connections held, not leaked.**
The pool can also starve while every connection is legitimately "in use":

- **Long transactions**: a transaction spanning an external HTTP call holds its connection for the whole call. Keep transactions tight; I showed the patterns in [**working with transactions in EF Core**](https://milanjovanovic.tech/blog/working-with-transactions-in-ef-core).
- **Slow queries**: 100 connections all running 8-second queries is exhaustion with zero bugs. That's a query tuning problem.
- **Streaming with slow consumers**: iterating an EF Core query with `AsAsyncEnumerable` (or an API response streaming **IAsyncEnumerable**) holds the connection until iteration completes.
- **Unbounded concurrency**: `Parallel.ForEachAsync` with a high degree of parallelism, or a burst of background jobs, can legitimately want more than 100 connections at once. Cap the concurrency instead of uncapping the pool.

**4. Sync-over-async blocking.**
`.Result` and `.Wait()` on database calls can starve the thread pool, which slows everything, which stretches connection hold times, which exhausts the pool as a downstream symptom.
The cause to fix is **thread pool starvation**.

## Finding the Leak With Metrics

Both providers publish the pool numbers you need.

**Npgsql** exposes OpenTelemetry metrics (`Npgsql` meter): `db.client.connection.count` split by its `db.client.connection.state` attribute into `used` and `idle`, plus `db.client.connection.max` and `db.client.connection.npgsql.pending_requests`.
**Microsoft.Data.SqlClient** exposes event counters (event source `Microsoft.Data.SqlClient.EventSource`) such as `active-hard-connections`, `number-of-active-connections`, `number-of-free-connections`, and `number-of-reclaimed-connections`, which counts connections recovered from garbage-collected `SqlConnection` objects.
You can watch them live with `dotnet-counters monitor --counters Microsoft.Data.SqlClient.EventSource -p <PID>`.

Wire the Npgsql metrics into your existing pipeline (the Prometheus exporter is still a prerelease package):

```bash
dotnet add package OpenTelemetry.Extensions.Hosting
dotnet add package OpenTelemetry.Exporter.Prometheus.AspNetCore --prerelease
```

```csharp
// Program.cs
using OpenTelemetry.Metrics;

builder.Services.AddOpenTelemetry()
    .WithMetrics(metrics => metrics
        .AddMeter("Npgsql")
        .AddPrometheusExporter());

// After builder.Build(): serves the scrape endpoint at /metrics
app.MapPrometheusScrapingEndpoint();
```

The diagnostic signal is the *shape* of the busy-connections curve:

- **Climbs steadily and never comes down**, even under flat traffic: a leak. The slope tells you roughly how often the leaking path executes.
- **Tracks request concurrency but hits the ceiling at peak**: connections are held too long (slow queries, long transactions) or you need more capacity.
- **Spikes with specific operations**: correlate timestamps with logs and you've found the offending endpoint or job.

Then look from the database side to see what the open connections are actually doing.
On PostgreSQL:

```sql
SELECT state, count(*),
       max(now() - state_change) AS longest_in_state
FROM pg_stat_activity
WHERE application_name = 'my-api'
GROUP BY state;
```

A pile of connections in `idle in transaction` points to undisposed transactions.
On SQL Server, `sys.dm_exec_sessions` joined with `sys.dm_exec_connections` gives you the same picture.

For an interim safety net, Npgsql supports `Connection Idle Lifetime` and SQL Server has connection lifetime settings, but these prune *idle* connections; they cannot reclaim leaked busy ones.
Disposal is the only reliable way to return a connection: Npgsql never reclaims a leaked one, and SqlClient's reclaim waits on the garbage collector.

## When Raising MaxPoolSize Is Actually Right

After you've confirmed there's no leak and no accidental holding, some workloads do need more than 100 concurrent connections: high-throughput APIs with concurrent database work, or fan-out batch processing.

Do the arithmetic first.
Every connection is real memory and a real backend process (PostgreSQL) or worker resources (SQL Server) on the database side.
If you run 10 API instances with `Maximum Pool Size=200`, you've authorized 2,000 connections against a database that might be configured for `max_connections = 100`.

```text
Host=db;Database=app;Username=api;Password=...;Maximum Pool Size=200;Timeout=15
```

For PostgreSQL at scale, an external pooler (PgBouncer) in transaction mode multiplexes thousands of client connections onto tens of server connections, which is usually the better lever than per-instance pool inflation.
And on the application side, make sure you're using a single shared `NpgsqlDataSource` rather than ad-hoc connection strings; I covered why in [**NpgsqlDataSource and connection pooling in .NET**](https://milanjovanovic.tech/blog/npgsqldatasource-connection-pooling-dotnet).

`DbContext` pooling ([**EF Core DbContext pooling**](https://milanjovanovic.tech/blog/ef-core-dbcontext-pooling)) reuses *context objects*, not database connections.
It reduces allocation overhead, but it neither causes nor fixes connection pool exhaustion.

## A Checklist for the Incident

When the error is firing in production right now:

1. Check pool metrics: is busy-connections pinned at max? Since when? What deployed around then?
2. Query `pg_stat_activity` / `sys.dm_exec_sessions`: what are the connections doing? `idle in transaction` means undisposed transactions; `active` on the same statement means slow queries.
3. Grep recent changes for `new NpgsqlConnection`, `new SqlConnection`, `BeginTransaction`, and manually opened EF Core connections without `using`.
4. Check for background jobs or parallel processing that scaled up concurrency recently.
5. Restart the affected instances to reclaim leaked connections and buy time. Then fix the leak, because it will be back at exactly the same rate.

## Summary

"Connection pool exhausted" means more connections were rented than returned.

The discipline that prevents it:

- `await using` every connection, command, reader, and transaction; dispose every `DbContext`
- Keep transactions short and never span external calls with them
- Cap concurrency at the application level instead of uncapping the pool
- Watch pool metrics continuously; a climbing busy-connections line under flat load is an early sign of a leak
- Raise the maximum pool size only after doing the connection arithmetic

When the error fires, start by finding the code path that never returns its connection.

## Frequently asked questions

### What causes the connection pool exhausted timeout in .NET?

The most common cause is leaked connections: code paths that open a connection and never dispose it, often in an error path. Long-running transactions, slow queries holding connections, and sudden concurrency spikes are the other frequent causes. A real capacity shortage is the rarest.

### Should I increase MaxPoolSize to fix pool exhaustion?

Usually no. If connections are leaking, a bigger pool just delays the same failure while putting more load on the database. Raise MaxPoolSize only after you have confirmed there is no leak and the workload needs more concurrent connections.

### How do I find leaked connections in .NET?

Compare the pool counters (busy versus idle connections) from Npgsql or SqlClient metrics with your actual request concurrency, and query pg_stat_activity or sys.dm_exec_sessions to see what the open connections are doing. Steadily climbing busy connections under flat load means a leak.

### Does EF Core leak connections?

Not when used normally. EF Core opens and closes connections around each operation, and disposing the DbContext returns the connection. Leaks happen when a DbContext is never disposed, when you manually open the connection and never close it, or when undisposed transactions or data readers keep it pinned.
