Database connection pooling
suggest changeIn .NET, establishing a physical database connection is an expensive operation that requires socket initialization, network handshakes, TLS negotiation, and database authentication. Connection pooling significantly enhances application performance by keeping a pool of active physical connections open and reusing them across requests.
Both ADO.NET (e.g., Microsoft.Data.SqlClient, Npgsql) and Entity Framework Core implement connection pooling by default.
1. How ADO.NET Connection Pooling Works
The ADO.NET pool manager allocates a separate connection pool for each unique connection string:
conn.Open()orawait conn.OpenAsync(): The pool manager checks if an idle physical connection is available in the pool. If available, it resets its session state and hands it to the caller. If the pool is empty and belowMax Pool Size, a new physical connection is created. If the pool is saturated, the call blocks until a connection is returned orConnection Timeoutexpires.conn.Close()orconn.Dispose(): The physical socket connection is not terminated. Instead, the connection is returned to the pool for reuse.
using System;
using System.Data;
using System.Threading.Tasks;
using Microsoft.Data.SqlClient;
class ConnectionPoolingExample
{
private static readonly string ConnectionString =
"Server=tcp:sqlserver.local,1433;Database=Ecommerce;User Id=appuser;Password=Secret123!;Pooling=true;Min Pool Size=5;Max Pool Size=100;Connection Timeout=15;";
static async Task ExecuteQueryAsync()
{
// 'using var' guarantees connection is returned to the pool immediately upon exit
await using var connection = new SqlConnection(ConnectionString);
await connection.OpenAsync();
await using var command = new SqlCommand("SELECT COUNT(*) FROM Orders", connection);
int orderCount = (int)(await command.ExecuteScalarAsync() ?? 0);
Console.WriteLine($"Total orders: {orderCount}");
} // connection.DisposeAsync() returns the physical connection to the pool here
}
2. Key Connection String Parameters
You can tune pool behavior directly within the connection string:
| Parameter | Default | Description |
|---|---|---|
Pooling |
true |
Enables or disables connection pooling. (Should almost always be true). |
Min Pool Size |
0 |
Minimum number of physical connections maintained in the pool at all times. |
Max Pool Size |
100 |
Maximum number of concurrent connections permitted in this specific pool. |
Connection Timeout |
15 |
Seconds to wait for a free connection from the pool before throwing an InvalidOperationException. |
Connection Lifetime |
0 |
Maximum age (in seconds) of a connection before it is closed and replaced on return. 0 disables expiration. |
3. The Pool Starvation Pitfall (Connection Leaks)
The most common database issue in .NET web applications is pool starvation:
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.
Bad: Forgetting to Dispose Connections
// DANGEROUS: If an exception is thrown, Close() is skipped, leaking the connection!
var conn = new SqlConnection(ConnectionString);
conn.Open();
DoWork(conn);
conn.Close();
Good: Always Use using or await using
// SAFE: Connection is returned to the pool even if unhandled exceptions occur
await using (var conn = new SqlConnection(ConnectionString))
{
await conn.OpenAsync();
await DoWorkAsync(conn);
}
4. Pool Fragmentation
Because ADO.NET creates a distinct pool for every unique connection string, variations in connection strings fragment the pool:
// BAD: Dynamically embedding username creates a separate pool for every tenant/user!
string badConnStr = $"Server=sql.local;Database=app;User Id={currentUser};Password={pass};";
// GOOD: Use a shared application connection pool, and set tenant context via SQL commands:
string goodConnStr = "Server=sql.local;Database=app;User Id=AppService;Password=Secret;";
Keep connection strings strictly uniform and centralized in appsettings.json.
5. Resetting and Clearing Pools
During server failover or network interruptions, pooled connections may become invalid. Clear the pool programmatically:
using Microsoft.Data.SqlClient;
// Clear the pool associated with a specific connection
SqlConnection.ClearPool(connection);
// Or clear all active pools in the current application domain
SqlConnection.ClearAllPools();
6. Entity Framework Core: DbContext Pooling
In addition to underlying ADO.NET connection pooling, Entity Framework Core can pool DbContext instances to eliminate object allocation overhead during high-concurrency web requests:
var builder = WebApplication.CreateBuilder(args);
// Reuses DbContext instances across HTTP requests instead of instantiating new ones
builder.Services.AddDbContextPool<AppDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")),
poolSize: 128
);
7. Best Practices
- Open Late, Close Early: Only call
conn.OpenAsync()immediately before executing queries, and dispose of the connection as soon as queries complete. - Always Use Async APIs: Prefer
OpenAsync(),ExecuteReaderAsync(), andDisposeAsync()to avoid tying up OS threads while waiting for connections or queries. - Never Manually Cache
SqlConnectionin Static Fields: Let the ADO.NET pool manager handle lifetimes. Always instantiate and dispose connections per unit of work.