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

databasedotnetef-coreperformance
Fixing "Timeout Expired: Connection Pool Exhausted" in .NET

The error arrives in production, never in development:

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

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:

// 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:

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.
  • 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):

dotnet add package OpenTelemetry.Extensions.Hosting
dotnet add package OpenTelemetry.Exporter.Prometheus.AspNetCore --prerelease
// 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:

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.

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.

DbContext pooling (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.

  • PostgreSQL Indexing for .NET Developers

    B-tree indexes cover most of your queries. Learn when GIN, partial, and covering indexes beat a plain B-tree for the rest, and how to configure each one from EF Core so it survives your migrations.

  • PostgreSQL Table Partitioning for .NET Applications

    DELETE FROM on a 500 million row table runs for hours and leaves the table bloated. Dropping a partition takes milliseconds. Here is when PostgreSQL partitioning pays off, how to set it up, and how to use it from EF Core.

  • Using Read Replicas in .NET Applications

    Routing reads to replicas is the standard way to scale a read-heavy database, but replication lag introduces a new class of bugs. Here is how to route queries to replicas in .NET with EF Core, and how to protect read-your-writes consistency while doing it.

Browse all Databases guides →
Loading comments...

Whenever you're ready, there are 5 ways I can help you:

  1. Pragmatic Self-Hosting: Learn to deploy and run your apps on a VPS with Dokploy and Tailscale. Keep administration private, automate releases, and practice restoring backups, with source code and a runbook you can reuse.
  2. Pragmatic Clean Architecture: Join 5,000+ students in this comprehensive course that will teach you the system I use to ship production-ready applications using Clean Architecture. Learn how to apply the best practices of modern software architecture.
  3. Modular Monolith Architecture: Join 2,800+ engineers in this in-depth course that will transform the way you build modern systems. You will learn the best practices for applying the Modular Monolith architecture in a real-world scenario.
  4. Pragmatic REST APIs: Join 1,900+ students in this course that will teach you how to build production-ready REST APIs using the latest ASP.NET Core features and best practices. It includes a fully functional UI application that we'll integrate with the REST API.
  5. Patreon Community: Join a community of 5,000+ engineers and software architects. You will also unlock access to the source code I use in my YouTube videos, early access to future videos, and exclusive discounts for my courses.

The .NET Weekly

One practical .NET tip, every Saturday.

Join 66,000+ engineers who read it. Free, and you can unsubscribe any time.