📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

What is DbContext pooling in EF Core? Explain AddDbContextPool and AddPooledDbContextFactory, what EF Core resets when a context goes back to the pool and what it does not, how per-request state such as a tenant id can leak, and how much performance it really gains.

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.

Mid-Level Theory Intermediate aspnet-core dbcontext-pooling dependency-injection ef-core multi-tenancy performance

🎯 Key points

  • Pooling reuses DbContext instances instead of building a new one per scope
  • AddDbContextPool registers a scoped lease; AddPooledDbContextFactory gives a singleton factory
  • Default pool size 1024 (EF Core 6+) is how many are kept, not a concurrency cap: bursts create extra contexts that are disposed
  • On return EF Core resets only state it owns: change tracker, its options, transaction
  • Your own fields and properties on the context are NOT reset: tenant ids leak
  • Constructor may take only DbContextOptions; OnConfiguring runs once per instance
  • Set per-request state on every lease through a scoped factory wrapper
  • The gain is in context setup (microseconds and allocations per request); measure at real throughput

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"Normally AddDbContext gives 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: AddDbContextPool keeps 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, QueryTrackingBehavior and other ChangeTracker and Database options go back to their configured values, and any transaction is gone. It knows nothing about fields you added. So if your context has a TenantId property 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 takes DbContextOptions, OnConfiguring runs 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 AddPooledDbContextFactory plus 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 options

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

What is and isn't reset

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

Production example

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.

🔍 What the interviewer is checking

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

  • Explains rent, reset and return and the default pool size
  • States clearly that custom fields are not reset
  • Knows the single-constructor and OnConfiguring restrictions
  • Uses a pooled factory with a scoped wrapper for per-request state
  • Talks about measuring with a load test and dotnet-counters

Red flags

  • Thinks pooling makes queries faster
  • Sets a tenant id in OnConfiguring or a constructor of a pooled context
  • Treats pool size as a cap on concurrent requests

📚 Learn in depth

1. What a DbContext costs to create

new 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.

2. How the pool works

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.

3. The reset

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.

4. Restrictions

  • One public constructor accepting DbContextOptions<T> (or DbContextOptions); no scoped services.
  • OnConfiguring runs once per instance, not per request, so it cannot read request data.
  • The options are fixed, so per-request connection strings (database-per-tenant) need a different approach, such as a connection interceptor or a non-pooled factory.

5. Safe per-request state

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.

6. Measuring the gain

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.

Try it yourself

  1. Benchmark creating and disposing a context with AddDbContext versus a pooled factory using BenchmarkDotNet's MemoryDiagnoser.
  2. Add a TenantId property to a pooled context, set it in one scope, and observe its value in the next scope that gets the same instance.
  3. Implement the scoped factory wrapper and write a test proving the tenant is set on every lease.
  4. Run a load test at 500 and 3,000 requests per second with and without pooling, watching allocation rate in dotnet-counters.
  5. Watch dotnet-counters monitor Microsoft.EntityFrameworkCore for active contexts during a spike.

💻 Code

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.

⚠ Common mistakes

  • Mistake: Adding fields such as 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.
  • Mistake: Keeping per-request data in static or shared fields that the context reads (for example a static 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.
  • Mistake: Injecting scoped services into a pooled context's constructor. Why it is wrong: pooled contexts must have a single constructor taking options; the instance outlives the scope. Instead: pass values in through the factory wrapper.
  • Mistake: Reading request data in 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.
  • Mistake: Treating pool size as a concurrency limit. Why it is wrong: when the pool is empty EF Core creates new contexts; the size only caps how many are kept. During a burst you briefly pay the full creation cost plus the memory of the extra instances, and a very large pool keeps up to that many contexts (and their buffers) alive after the burst. Instead: size the pool near your real peak concurrency and control concurrency elsewhere (connection pool, rate limiting).
  • Mistake: Expecting pooling to fix slow endpoints. Why it is wrong: context creation is microseconds; slow endpoints are almost always the SQL. Instead: measure query time first; use pooling for high request rates with cheap queries.
  • Mistake: Changing 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.
  • Mistake: Using pooling with database-per-tenant connection strings in the options. Why it is wrong: the options are fixed for the pool. Instead: use a non-pooled factory or set the connection per lease.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions the DbContext lifetime or AddDbContext Why: Checks they can justify scoped as the default lifetime for a DbContext
    How to answer

    I choose by state and thread safety, then check dependencies:

    1. Does it hold per-unit-of-work state (a change tracker, the current user)? → scoped.
    2. Is it shared, thread-safe and worth building once (a cache, a client pool, compiled config)? → singleton.
    3. Stateless and cheap? → transient (or singleton if every dependency is a singleton).
    4. A service can't outlive its shortest-lived dependency.

    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.

  2. When: Candidate mentions AddPooledDbContextFactory for background work Why: Checks they can use scoped database work correctly from a BackgroundService
    How to answer

    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.

  3. When: Candidate mentions running queries in parallel with a factory Why: Checks they understand why one context cannot run concurrent operations and how factories solve it
    How to answer

    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.

🛠 Real-world problems: how you handle them

Tenant filter reading the previous request's tenant after enabling pooling
Situation
A multi-tenant SaaS API on ASP.NET Core and EF Core with a shared Azure SQL database [in Australia East]. A performance change switched `AddDbContext` to `AddDbContextPool` for [a 15% CPU target].
Signals
An automated cross-tenant test in the staging environment started failing intermittently: a request for tenant A returned invoices of tenant B. No errors in logs; only under parallel load.
Investigation
Reproduced with a load test of two tenants in parallel. Logged the context's `TenantId` and `GetHashCode()` per request and saw the same instance reused with the old tenant. Found that a middleware set `TenantId` only when the tenant header was present, and health-check and some background routes left it unset.
Resolution
Immediately rolled back to `AddDbContext`. Then introduced `AddPooledDbContextFactory` with a scoped `TenantDbContextFactory` that always sets `TenantId` (and throws if no tenant is resolved), re-enabled pooling, and reran the load test.
Prevention
A permanent cross-tenant integration test under parallel load; an analyser-style unit test that fails if a pooled context type declares settable members not set by the factory; the incident reviewed against our Privacy Act and Notifiable Data Breaches process (no production exposure); an ADR on pooling rules.

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.

↩ Usually asked after

More in EF Core Performance

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me