There are two different kinds of pooling to explain: database connection pooling (ADO.NET) and DbContext pooling (EF Core). 1. Database connection pooling - Opening a physical database connection is expensive (network handshake, authentication, TLS). - ADO.NET providers such as Microsoft.Data.SqlClient and Npgsql keep a pool of open physical connections per unique connection string. - When EF Core opens a connection, it takes one from the pool; when the connection is closed or disposed, it goes back to the pool instead of being closed. - EF Core opens a connection just before a query or SaveChanges and closes it right after, so connections are held only briefly. - Configured through the connection string: Max Pool Size (default 100 for SqlClient), Min Pool Size, Pooling=true, Connection Timeout. - Pool exhaustion error: "Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool." Causes: connections not disposed (manual ADO.NET code), long-running transactions or queries holding connections, sync-over-async blocking, or more concurrency than the pool size. 2. DbContext pooling - Creating a DbContext instance has some setup cost. With AddDbContextPool, EF Core keeps a pool of DbContext instances and reuses them across requests: builder.Services.AddDbContextPool<AppDbContext>(o => o.UseSqlServer(builder.Configuration.GetConnectionString("Default")), poolSize: 1024); - When the request scope ends, the context is reset (change tracker cleared, state reset) and returned to the pool. - Useful for high-throughput APIs; benchmarks show measurable gains in requests per second. - Restrictions: the DbContext must not hold per-request state in its own fields (for example a tenant ID set in the constructor), because instances are reused. Use a different approach for such state, such as a scoped service or IDbContextFactory with pooling (AddPooledDbContextFactory). - OnConfiguring runs once per pooled instance, not per request. Summary - Connection pooling: reuses physical database connections; on by default; managed by the ADO.NET provider. - DbContext pooling: reuses DbContext objects; opt-in; managed by EF Core. Best practices: keep a single consistent connection string (different strings create separate pools), keep transactions short, use async methods, dispose manually created contexts, and monitor pool usage under load.
Ravindra Wadile · · 0 likes