Entity Framework Core Interview Question #146

What is connection pooling and how does it relate to EF Core?

Performance, Raw SQL, Stored Procedures & Advanced Queries Senior Advanced

Quick Interview Answer

Database providers commonly pool physical connections. Opening a connection typically obtains one from the pool, and closing or disposing it normally returns it for reuse. Connection pooling is different from DbContext pooling: DbContext is EF Core's unit of work, while connection pooling is managed primarily by the database provider. Avoid holding connections or transactions longer than necessary.

Detailed Explanation

Database providers commonly pool physical connections. Opening a connection typically obtains one from the pool, and closing or disposing it normally returns it for reuse. Connection pooling is different from DbContext pooling: DbContext is EF Core's unit of work, while connection pooling is managed primarily by the database provider. Avoid holding connections or transactions longer than necessary.

Code Example

await using var db = await dbContextFactory.CreateDbContextAsync();
var product = await db.Products
    .AsNoTracking()
    .FirstOrDefaultAsync(p => p.Id == id);