Covers how EF Core DbContext pooling works, AddDbContextPool versus AddPooledDbContextFactory, what is reset on return, the constructor and state restrictions, safe per-request state through a factory, and how to measure the gain.
DbContext pooling keeps a pool of context instances and hands one out per scope instead of constructing a new one, saving the setup cost and allocations of each context. AddDbContextPool<T>() registers a scoped lease; AddPooledDbContextFactory<T>() registers a singleton factory for background work. When a lease ends, EF Core resets its own state: the change tracker, tracking options, the current transaction. It does not reset your fields, so a TenantId property set in one request can leak into the next. Pooled contexts must have a single constructor taking DbContextOptions and can't inject scoped services. For per-request values I wrap the pooled factory in a scoped factory that sets them on every lease. The trade-off: the gain is real but small per request, worth it at high throughput, and it adds a class of state bugs.
"Normally
AddDbContextgives you a new context per request. Creating one isn't hugely expensive, because the model is built once and cached, but each instance still sets up its internal service provider lookups, the state manager and a fair amount of objects. Pooling keeps those instances around:AddDbContextPoolkeeps up to 1,024 contexts by default, leases one to each request scope, and when the scope ends it resets the context and returns it to the pool.The important part is what 'reset' means. EF Core resets everything it owns: the change tracker is cleared,
QueryTrackingBehaviorand otherChangeTrackerandDatabaseoptions go back to their configured values, and any transaction is gone. It knows nothing about fields you added. So if your context has aTenantIdproperty that a middleware sets, the next request that gets that instance sees the previous tenant, unless every request sets it again. That's a data-isolation bug, not a performance one. Pooling also restricts the context: it must have one public constructor that takesDbContextOptions,OnConfiguringruns only when an instance is first created, and you can't inject scoped services like a tenant provider into the constructor.The safe pattern for per-request state is
AddPooledDbContextFactoryplus a small scoped factory: it creates a context from the pool and sets the tenant id from the current request every time, and the app registers the context as scoped through that factory. On the gain: Microsoft's own benchmarks show context creation getting much cheaper, but that is microseconds and a few kilobytes per request. At a few hundred requests per second you won't see it next to the SQL. At thousands per second with cheap queries it shows up in CPU and GC. The mistake I see is turning pooling on as a free speed-up in a multi-tenant app without checking the context for state."
| Registration | Lifetime | Use for |
|---|---|---|
AddDbContext<T>() |
New context per scope | Default; any constructor, scoped dependencies allowed |
AddDbContextPool<T>(o => ..., poolSize) |
Scoped lease from a pool | High-throughput APIs with stateless contexts |
AddDbContextFactory<T>() |
Singleton factory, new context per call | Blazor Server, background jobs, parallel work |
AddPooledDbContextFactory<T>() |
Singleton factory over a pool | Background or parallel work at high throughput; base for per-request wrappers |
| Reset by EF Core on return | Not reset |
|---|---|
| Change tracker contents | Your own fields and properties (tenant id, user id) |
ChangeTracker.QueryTrackingBehavior, AutoDetectChangesEnabled, cascade timings |
Static state |
Database.AutoTransactionBehavior, command timeout set at run time |
State inside services you captured in the context |
| Current transaction and enlisted state | Event handlers you subscribed on the context |
A high-volume read API [in a system I worked on] served about 3,000 requests per second with simple key lookups. Moving from AddDbContext to pooling cut allocations per request by roughly 20% and CPU by a few percent, measured with dotnet-counters and a load test. In a separate multi-tenant service the same change, made without the factory wrapper, briefly served one tenant's records under another tenant's filter in a test environment, which is why the wrapper is now the standard.
Checks that the candidate knows how pooling works, what the reset covers, the leaking-state risk and restrictions, and whether the gain justifies it.
Green flags
OnConfiguring restrictionsRed flags
OnConfiguring or a constructor of a pooled contextnew AppDbContext(options)
├─ resolve the internal service provider (cached per options)
├─ create StateManager, ChangeDetector, query context factory ...
└─ first use: look up the cached model, open connection lazily
The model itself is built once per context type and cached, so creation is far cheaper than in EF6. What remains is object allocation and wiring, which pooling avoids.
request scope starts -> lease = pool.Rent() (or new context if the pool is empty)
request uses lease.Context
scope disposed -> context.ResetState() -> pool.Return()
(if the pool already holds poolSize instances, the context is disposed)
The pool is a concurrent queue per context type and options. The default size is 1,024 since EF Core 6 (it was 128 before). The pool size is the maximum retained, not a limit on concurrency: under a spike, extra contexts are created and then disposed.
On return EF Core calls the reset logic on every internal service that implements its resettable interface: the state manager is cleared, ChangeTracker and Database facade options are restored to the values from DbContextOptions, and the connection is returned. It does not touch members you declared, because it can't know whether they're safe to keep.
DbContextOptions<T> (or DbContextOptions); no scoped services.OnConfiguring runs once per instance, not per request, so it cannot read request data.scoped TenantDbContextFactory
uses singleton IDbContextFactory<AppDbContext> (pooled)
CreateDbContext(): ctx = pooled.CreateDbContext(); ctx.TenantId = tenant.Id; return ctx
services.AddScoped(sp => sp.GetRequiredService<TenantDbContextFactory>().CreateDbContext())
The value is set on every lease, so leftover state is always overwritten. Global query filters that reference TenantId on the context then read the current request's value.
Use a load test (k6, bombardier, Azure Load Testing) against a real endpoint and watch dotnet-counters: System.Runtime allocation rate, GC count and CPU, plus the Microsoft.EntityFrameworkCore counters (active contexts, queries per second). Microbenchmarks of context creation exaggerate the gain; what matters is the difference at your request rate.
AddDbContext versus a pooled factory using BenchmarkDotNet's MemoryDiagnoser.TenantId property to a pooled context, set it in one scope, and observe its value in the next scope that gets the same instance.dotnet-counters monitor Microsoft.EntityFrameworkCore for active contexts during a spike.Pooling for a stateless context, and the scoped factory wrapper for per-request tenant state.
namespace Shop.Data;
using Microsoft.EntityFrameworkCore;
public sealed class AppDbContext(DbContextOptions<AppDbContext> options) : DbContext(options)
{
// Not reset by the pool: must be set on every lease.
public Guid TenantId { get; set; }
public DbSet<Invoice> Invoices => Set<Invoice>();
protected override void OnModelCreating(ModelBuilder b) =>
// The filter reads the context's current TenantId at query time.
b.Entity<Invoice>().HasQueryFilter(i => i.TenantId == TenantId);
}
public sealed class Invoice
{
public int Id { get; set; }
public Guid TenantId { get; set; }
public decimal Amount { get; set; }
}
public interface ITenantContext { Guid TenantId { get; } }
// Scoped: one per request. Sets the tenant on every context it hands out.
public sealed class TenantDbContextFactory(IDbContextFactory<AppDbContext> pooled, ITenantContext tenant)
{
public AppDbContext CreateDbContext()
{
var context = pooled.CreateDbContext();
context.TenantId = tenant.TenantId;
return context;
}
}
// Program.cs
var connectionString = builder.Configuration.GetConnectionString("Shop")
?? throw new InvalidOperationException("Missing connection string 'Shop'.");
// Stateless context, high throughput: plain pooling.
// builder.Services.AddDbContextPool<ReportingDbContext>(o => o.UseSqlServer(connectionString), poolSize: 1024);
// Context with per-request state: pooled factory + scoped wrapper.
builder.Services.AddPooledDbContextFactory<AppDbContext>(o => o.UseSqlServer(connectionString));
builder.Services.AddScoped<ITenantContext, HttpTenantContext>();
builder.Services.AddScoped<TenantDbContextFactory>();
builder.Services.AddScoped(sp => sp.GetRequiredService<TenantDbContextFactory>().CreateDbContext());
// The container disposes the scoped AppDbContext at the end of the request, returning it to the pool.
TenantId or CurrentUser to a pooled context and setting them only sometimes. Why it is wrong: the pool doesn't reset your members, so a later request can run with the previous request's value. Instead: set them on every lease through a scoped factory wrapper.CurrentTenant used by a query filter). Why it is wrong: statics are shared by every concurrent request and every pooled instance, so they are wrong under load with or without pooling. Instead: keep per-request data on the leased instance or in a scoped service passed through the factory.OnConfiguring. Why it is wrong: it runs once per pooled instance, not per request. Instead: configure in AddDbContextPool options and set per-request values on the lease.ChangeTracker settings at run time and assuming they persist. Why it is wrong: EF Core resets them on return. Instead: configure defaults in the options, for example UseQueryTrackingBehavior.Pooling is an optimisation with a correctness cost, so I treat it as opt-in for contexts that are provably stateless or that receive their state through a factory on every lease. In a multi-tenant system I would rather lose a few microseconds than risk cross-tenant reads, so the wrapper pattern and a test that asserts the tenant is set per lease come with the change. I decide based on a load test at real request rates, not a microbenchmark.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
AddDbContext |
Most apps, any constructor | Small allocation per request | Very high throughput with trivial queries |
AddDbContextPool |
Stateless contexts, thousands of requests per second | Constructor and OnConfiguring restrictions |
Contexts with per-request fields |
| Pooled factory + scoped wrapper | Per-request state (tenant, user) with pooling | One extra class | Database-per-tenant connection strings |
Non-pooled AddDbContextFactory |
Blazor Server, background work | New context per call | Hot request paths where allocations matter |
I choose by state and thread safety, then check dependencies:
So: DbContext is scoped (not thread-safe, one unit of work), or created per operation with IDbContextFactory<T> outside requests. HttpClient comes from IHttpClientFactory (pooled handlers, DNS refresh) or is one singleton with PooledConnectionLifetime. IMemoryCache is a singleton. The trade-off is sharing versus safety: wider lifetimes save allocations but demand thread safety and stricter dependencies.
AddHostedService<T>() registers the worker as a singleton, so a scoped DbContext in its constructor would be a captive dependency: one context for the life of the process (Development throws at start-up). Instead, inject IServiceScopeFactory and create a scope per unit of work:
await using var scope = scopes.CreateAsyncScope();
var svc = scope.ServiceProvider.GetRequiredService<IOrderService>();
Each message or tick gets a fresh context that is disposed at the end. Pass stoppingToken everywhere, use PeriodicTimer for polling, and catch exceptions per item: since .NET 6 an unhandled exception in ExecuteAsync stops the host by default. If only a context is needed, IDbContextFactory<T> is simpler. Trade-off: smaller scopes mean fresher state and less memory, but more allocations per item.
A DbContext wraps one connection and one change tracker and allows one operation at a time; EF's concurrency detector throws when a second async operation starts before the first completes, usually from a shared context or a missing await. To run work in parallel, give each branch its own context (IDbContextFactory<T>.CreateDbContextAsync()), or combine the queries into one round trip. Never share a context across Task.WhenAll branches.
How to tell it (STAR)
**S:** We enabled DbContext pooling in [our multi-tenant API] to reduce CPU. **T:** Our cross-tenant test in staging started failing intermittently, and I owned the investigation. **A:** I reproduced it with two tenants under parallel load and logged the context instance per request: the same pooled instance came back still holding the previous tenant, because our middleware only set it on some routes and the pool doesn't reset custom fields. I rolled back, then built a pooled factory with a scoped wrapper that sets the tenant on every lease and fails if none is resolved, and made the parallel cross-tenant test permanent. **R:** We kept pooling's gain of about [10%] CPU, the leak never reached production, and the test has guarded every release since.
Last updated 23 Nov 2026.