Introduction
Database performance in an ASP.NET Core application is not determined only by how quickly a query executes. The lifetime of each DbContext, the time when physical database connections are opened and released, the number of requests sharing a connection pool, and the duration of transactions all affect throughput and latency.
In this lesson, we will separate three related but different concepts: DbContext lifetime, EF Core DbContext pooling, and ADO.NET connection pooling. Incorrect configuration can lead to connection exhaustion, request queuing, lock contention, unnecessary memory usage, and errors such as “A second operation was started on this context.”
The goal is to choose an appropriate lifetime for each workload, open connections late and release them early, control parallel database work, and measure database capacity instead of guessing.
1. DbContext represents a unit of work
In EF Core, DbContext tracks entities, executes queries, and persists changes to the database. In a web application, one HTTP request often corresponds to one unit of work. For that reason, a scoped lifetime is usually the correct default for a web API.
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(connectionString));AddDbContext registers the context as scoped by default. Services within the same request scope can use the same context, and the dependency-injection scope disposes it when the request ends.
This is very different from storing one context for the entire application. The following pattern is incorrect:
public class ProductService
{
private static AppDbContext? _context;
public ProductService(AppDbContext context)
{
_context ??= context;
}
}A singleton service holding a scoped DbContext creates a lifetime mismatch. A context that lives too long can also retain unnecessary entities in its change tracker and allow state from different requests to interfere with one another.
2. Choosing scoped context, a factory, or short-lived contexts
Regular HTTP requests
Injecting a context into a controller or scoped service is appropriate for most CRUD operations:
public sealed class OrdersService
{
private readonly AppDbContext _db;
public OrdersService(AppDbContext db)
{
_db = db;
}
public async Task<Order?> GetAsync(
int id,
CancellationToken cancellationToken)
{
return await _db.Orders
.AsNoTracking()
.SingleOrDefaultAsync(x => x.Id == id, cancellationToken);
}
}EF Core asynchronous operations should be awaited immediately. Starting two operations on the same context without coordination is not supported.
Multiple independent units of work
A background service, a long-running workflow, or an HTTP request containing several independent units of work may need separate context instances. In those cases, use IDbContextFactory<TContext>:
builder.Services.AddDbContextFactory<AppDbContext>(options =>
options.UseSqlServer(connectionString));
public sealed class ReportWorker
{
private readonly IDbContextFactory<AppDbContext> _factory;
public ReportWorker(IDbContextFactory<AppDbContext> factory)
{
_factory = factory;
}
public async Task<int> CountPendingAsync(
CancellationToken cancellationToken)
{
await using var db = await _factory.CreateDbContextAsync(cancellationToken);
return await db.Jobs.CountAsync(
x => x.Status == JobStatus.Pending,
cancellationToken);
}
}The application code owns the lifetime of a context created by the factory. Therefore, using or await using is essential.
3. DbContext pooling is not connection pooling
DbContext pooling reuses EF Core context instances. With AddDbContextPool, a disposed context may be reset and returned to a pool instead of being recreated for the next request. This can reduce context construction and initialization overhead, but the gain is often small and should be verified with measurements.
builder.Services.AddDbContextPool<AppDbContext>(
options => options.UseSqlServer(connectionString),
poolSize: 128);When context pooling is enabled, configuration must remain stable between uses. Services injected into the context also require careful review because a pooled context instance can be reused by later requests.
Connection pooling operates at a lower level in Microsoft.Data.SqlClient. It reuses physical connections to avoid repeating network setup, authentication, and session initialization. When SqlConnection.Close, Dispose, or DisposeAsync is called, the connection is normally returned to the pool if it is usable rather than physically destroyed.
| Concept | Resource managed | Purpose |
|---|---|---|
| DbContext lifetime | EF Core unit-of-work object | Defines the boundary of application data work |
| DbContext pooling | DbContext instances | Reduces context allocation and initialization overhead |
| Connection pooling | Physical database connections | Reduces connection setup and authentication overhead |
Disposing a context and destroying a physical database connection are not necessarily the same event. EF Core and the provider open connections when needed, release them when possible, and let the connection pool manage reuse.
4. Understanding connection-string settings
The following settings are commonly relevant for SQL Server connection pooling:
"Server=localhost;Database=StoreDb;Trusted_Connection=True;
TrustServerCertificate=True;Max Pool Size=100;Min Pool Size=0;
Connect Timeout=5;"- Max Pool Size: The maximum number of physical connections retained in one pool. When the pool is full, new requests wait for a connection to become available.
- Min Pool Size: The minimum number of connections the pool attempts to maintain. An unnecessarily high value can keep sessions open at the database.
- Connect Timeout: The time allowed to establish a connection. It does not define how long a SQL query may execute.
- Pooling: Enabled by default. Disabling it is generally not a performance optimization and should be reserved for specific diagnostic cases.
Do not increase the pool size randomly. Request rate, query duration, database CPU capacity, worker concurrency, and the database server’s ability to process simultaneous work must be considered together.
5. Open late and release early
For most EF Core queries, the provider opens a connection when the query executes and releases it after the result is consumed. Transactions and active data readers can hold a connection for longer.
A safe pattern for custom ADO.NET code looks like this:
await using var connection = new SqlConnection(connectionString);
await connection.OpenAsync(cancellationToken);
await using var command = new SqlCommand(
"SELECT COUNT(*) FROM Orders WHERE Status = @status",
connection);
command.Parameters.AddWithValue("@status", "Pending");
var result = await command.ExecuteScalarAsync(cancellationToken);
var count = Convert.ToInt32(result);Keeping a connection in a global field or leaving it open for the entire application can defeat the benefits of connection pooling. It also makes network failures and server-side timeouts harder to handle safely.
6. Excessive parallelism and connection exhaustion
Starting every operation with Task.WhenAll can exceed database capacity. For example, launching 500 contexts and queries for 500 items may quickly consume application workers and available pooled connections.
A better approach is to limit concurrency:
var options = new ParallelOptions
{
MaxDegreeOfParallelism = 8,
CancellationToken = cancellationToken
};
await Parallel.ForEachAsync(jobIds, options, async (jobId, token) =>
{
await using var db = await factory.CreateDbContextAsync(token);
await ProcessJobAsync(db, jobId, token);
});The value 8 is not universally correct. Choose it based on query duration, database capacity, pool configuration, and measured results. Do not share one DbContext across parallel operations; use a separate context for each independent unit of work or execute operations sequentially.
7. Long-running transactions and locks
A transaction should contain only the database work that must be atomic. Waiting for user input, calling an external HTTP service, or performing file operations inside a transaction can hold connections and locks unnecessarily.
await using var transaction =
await db.Database.BeginTransactionAsync(cancellationToken);
try
{
db.Orders.Add(order);
await db.SaveChangesAsync(cancellationToken);
await transaction.CommitAsync(cancellationToken);
}
catch
{
await transaction.RollbackAsync(cancellationToken);
throw;
}Move validation that can happen before the transaction outside of it. Reduce the number of queries and update only the required rows. Even when a long transaction does not literally fill the pool, it keeps a connection busy for longer and can create request queues.
8. Measuring capacity and diagnosing bottlenecks
To evaluate a database optimization, monitor at least the following together:
- Average and p95/p99 HTTP response time
- Database query duration and timeout count
- Active and waiting connections
- Symptoms of connection-pool saturation
- SQL Server CPU, I/O, and lock duration
- Number of queries per request
Begin with a repeatable workload. For example, run product-list and order-creation endpoints with 100 concurrent clients. Repeat the test with different pool sizes, concurrency limits, and transaction durations.
If increasing the number of connections does not reduce p95 latency, the bottleneck may not be the pool. Inspect query plans, indexes, locks, and database CPU. Conversely, if reducing the pool increases response time, that does not prove that a larger pool is always better. The database server is also a finite resource.
Common mistakes
- Using a singleton DbContext: It is not thread-safe and creates a long-lived change tracker.
- Injecting a scoped context directly into a background service: A background service is typically singleton and should create a scope or use a factory.
- Running parallel queries on one context: Await operations sequentially or create separate contexts.
- Failing to dispose connections: Manual ADO.NET code can consume pooled connections if resources are not released.
- Increasing Max Pool Size without measurement: This may simply move the bottleneck to the database server.
- Calling external services inside a transaction: Locks and connections remain occupied unnecessarily.
- Assuming context pooling is automatically beneficial: It adds configuration constraints and should be enabled only when tests show a meaningful gain.
Short practice exercise
- Register an
AppDbContextwithAddDbContextand the scoped lifetime. - Add
AddDbContextFactoryfor a background worker. - Process 100 jobs with
MaxDegreeOfParallelism = 4instead of starting all jobs simultaneously. - Temporarily add
Max Pool Size=20;Connect Timeout=5to the connection string. - Run tests with 50 and 100 concurrent requests and record p95 latency, timeout count, and completed jobs.
- Repeat with pool sizes of 50 and 100. Include database CPU and query duration in the results.
In your report, do not simply identify the “fastest setting.” Explain which configuration provides acceptable latency and resource usage under each workload.
Conclusion
A healthy ASP.NET Core data layer treats DbContext as a short-lived unit of work, uses a scoped lifetime for regular requests, and creates independent contexts through a factory for background or parallel work. DbContext pooling and connection pooling are separate mechanisms, and both should be enabled or tuned only when measurements support the decision.
Opening connections late, releasing them early, keeping transactions short, limiting parallel queries, and evaluating pool settings together with database capacity reduces the risk of connection exhaustion. The next optimization is not always adding more connections; it is making visible where each resource is held and for how long.
Sources
- https://learn.microsoft.com/en-us/ef/core/dbcontext-configuration/
- https://learn.microsoft.com/en-us/ef/core/performance/advanced-performance-topics
- https://learn.microsoft.com/en-us/Sql/connect/ado-net/sql-server-connection-pooling?view=sql-server-ver16
- https://learn.microsoft.com/en-us/SQL/connect/ado-net/connection-options?view=fabric
- https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.dependencyinjection.entityframeworkservicecollectionextensions.adddbcontextpool?view=efcore-10.0