skip to content

In EF Core 10, what does AddDbContextPool reuse, what does its poolSize of 1024 actually limit, and what does returning a context to the pool reset?

level: seniorimportance: should knowfreq 40%

answer

  1. context instances, not connections
  2. poolSize = instances retained
  3. past 1024: plain new contexts
  4. one public ctor with DbContextOptions
  5. your own fields are not reset

basics

~20 s

AddDbContextPool reuses DbContext instances to skip their setup cost. poolSize, 1024 by default, caps how many idle instances are kept, not concurrency. On return EF clears tracking, transactions and owned connections and restores startup settings, but not your own fields.

solid answer

~40 s

`AddDbContextPool<TContext>` keeps a pool of context instances so a request rents a ready-made context instead of building one; it is unrelated to the driver's connection pool. `poolSize` defaults to 1024 and is the maximum number of instances **retained**; beyond it EF simply creates and disposes contexts without pooling, so it never blocks. Options become a frozen singleton, the context needs exactly one public constructor taking `DbContextOptions` (since EF Core 8 other parameters may be singletons), and `OnConfiguring` runs once per instance. When the scope ends, EF resets the instance: clears the change tracker, disposes any transaction, closes an EF-owned connection, and restores change-tracker and database settings plus event handlers to what they were after construction. Your own fields, such as a tenant id, are not reset.

code

csharp · 13 lines
csharp
public class NewsContext : DbContext
{
    public NewsContext(DbContextOptions<NewsContext> options) : base(options)
        => ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;

    public DbSet<Article> Articles => Set<Article>();

    // NOT reset by the pool: leaks into the next request if set per request
    public string? EditionCode { get; set; }
}

builder.Services.AddDbContextPool<NewsContext>(
    o => o.UseNpgsql(builder.Configuration.GetConnectionString("news")));

go deeper

for a junior

Recall that AddDbContextPool reuses context instances, that the default poolSize is 1024, and that it is separate from connection pooling.

for a middle

Explain the constructor requirement, why OnConfiguring runs once per pooled instance, and that poolSize limits retained instances rather than concurrency.

for a senior

Walk through what the reset restores from the post-construction snapshot and what it leaves, and how per-request fields leak between requests.

for a principal

Decide whether pooling's gain justifies its constraints for a service, based on measured context-creation cost and the team's ability to keep contexts stateless.

## What pooling reuses A `DbContext` is light, but each new instance still sets up internal services and objects. **Context pooling** pays that cost once: when a pooled context is disposed, EF resets its state and puts it back in an internal pool, and the next request gets that instance instead of a fresh one. The EF documentation's single-row benchmark measured about 701 microseconds and 50 KB allocated without pooling against about 350 microseconds and 4.6 KB with it, with the usual warning to benchmark your own workload. Context pooling is **orthogonal to connection pooling**. The ADO.NET driver (Npgsql, SqlClient) pools physical connections; EF pools context objects. A pooled context still opens a connection just before each operation and closes it afterwards. For a high-traffic news API, the registration is one call: ```csharp builder.Services.AddDbContextPool<NewsContext>( o => o.UseNpgsql(builder.Configuration.GetConnectionString("news")), poolSize: 1024); ``` When a request resolves `NewsContext`, EF rents an instance through a scoped lease; when the request's scope is disposed, the lease returns the instance to the pool instead of disposing it. Application code looks exactly the same as without pooling. ## What poolSize means The `poolSize` parameter **sets the maximum number of instances retained by the pool**, and the default is `1024`. - It is a **retention** limit, not a concurrency cap: the pool never makes a request wait. - When more contexts are in use than the pool holds, EF creates extra instances on demand, and on return they are **disposed instead of pooled**. - A value of 0 or below throws `ArgumentOutOfRangeException` ("The specified poolSize must be greater than 0"). - Raising it does not add database capacity; the connection pool and the server still limit concurrent queries. ## What pooling requires of the context 1. **Options are built once and frozen.** EF registers the options as a singleton and freezes them when the pool is created. 2. **Exactly one public constructor with parameters**, and it must take `DbContextOptions` or `DbContextOptions<TContext>`. Otherwise EF throws `InvalidOperationException`: the context "cannot be pooled because it does not have a public constructor accepting a single parameter of type DbContextOptions or has more than one constructor". 3. **Extra constructor parameters come from the root provider.** Since EF Core 8 the constructor may take more parameters, which EF resolves from the application's root service provider, so they must be **singletons**. A scoped service there would be a captive dependency. 4. **`OnConfiguring` runs once per instance**, when the pool first creates it, and may not change the frozen options: doing so throws "'OnConfiguring' cannot be used to modify DbContextOptions when DbContext pooling is enabled". ## What the reset covers When the dependency-injection scope ends, the context goes back to the pool and EF resets it. Right after creating each instance, EF takes a **configuration snapshot**, and every new lease restores it. | Reset on return | Not reset | |---|---| | Tracked entities cleared from the change tracker | Fields and properties you added to your context class | | Current transaction disposed | A `DbConnection` you supplied and manage yourself | | EF-owned connection closed, command timeout restored | Session state you changed in the database with raw SQL | | `ChangeTracker.QueryTrackingBehavior`, `AutoDetectChangesEnabled`, `LazyLoadingEnabled`, cascade timings restored | Anything a singleton constructor dependency holds | | `Database.AutoTransactionBehavior` and `AutoSavepointsEnabled` restored | | | `SavingChanges`, `SavedChanges`, `SaveChangesFailed` handlers restored | | Because the snapshot is taken after construction, a setting changed in the constructor, such as `ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking`, becomes the baseline every lease starts from. A setting changed during one request does not leak into the next. ## The state that does leak A pooled instance is effectively **reused across requests**, so anything EF does not know about survives: - a `TenantId` or `CurrentUser` property set during one request is still there for the next one; - an explicitly opened connection or a connection-level session setting you changed through SQL must be restored by you before the context goes back. The documented pattern for per-request values is a scoped wrapper that rents from a pooled factory and sets the value on every lease, not a constructor parameter or `OnConfiguring`. ## When pooling is worth it Pooling helps when context creation is a measurable share of request time: many short requests with cheap queries. It brings constraints in return, so measure before switching, and keep contexts free of per-request fields if you do.

  • What happens when 1,500 requests hold a pooled NewsContext at the same time with the default poolSize?
    Nothing blocks. The pool hands out the instances it has and creates further contexts on demand. As requests finish, instances return until 1,024 are retained; any returned beyond that are disposed instead of pooled. The real limits on concurrency are the driver's connection pool and the database server.
  • Why can a pooled context's constructor not take a scoped ITenantProvider?
    EF resolves extra constructor parameters of a pooled context from the root service provider, because the instance outlives any one scope. A scoped service resolved there would be captured for the instance's whole life and shared by unrelated requests, which is exactly the tenant leak pooling invites. Per-request values are set after renting instead.

A pooled context is a hotel room between guests: housekeeping strips the bed, empties the bins and resets the thermostat to the house setting, because those are on its checklist. A note the last guest taped inside a drawer is not on the list, so the next guest finds it.

  • AddDbContextPool pools database connections, replacing the ADO.NET connection pool.
  • When 1024 contexts are in use, the next request waits for one to be returned.
  • The pool resets every property on the context, including ones you added.
  • OnConfiguring runs on every lease, so it can read the current tenant.
  • A pooled context can take any scoped service in its constructor since EF Core 8.

Assumes EF Core 10; since EF Core 8 a pooled context's constructor may take singleton services beside DbContextOptions, where earlier releases accepted only the options.