Diagnosing an intermittent cross-tenant data leak in EF Core 10: pooled contexts keeping tenant state, singleton-captured tenant providers, model-baked filters and caches, with containment and Privacy Act obligations.
First contain it: it is a likely data breach, so switch off the suspect path, preserve logs and start the Notifiable Data Breaches assessment. Then look for shared state, because a leak you cannot reproduce locally usually needs concurrency:
AddDbContextPool reusing a context whose tenant field was set once in the constructor.DbContext.Reproduce it with a load test that alternates tenants and checks every row. Fix by disabling pooling or setting the tenant on every lease, and add row-level security as a backstop. The trade-off: pooling saves microseconds per request, and a leak costs far more.
"I'd treat this as a security incident before a bug. One tenant seeing another's data is likely an eligible data breach under the Privacy Act, so I'd contain first: disable the feature or endpoint if I can identify it, switch off DbContext pooling if it's on, preserve the logs, and bring in whoever owns the Notifiable Data Breaches process. Then I diagnose.
The clue is 'can't reproduce locally'. Locally there's one user and one tenant, so shared state never gets a chance to mix. Under production load many tenants interleave on the same instances. So I look for anything that outlives a request: a pooled
DbContextthat caches the tenant in a field, a singleton service that captured a scoped tenant provider, a query filter that closed over a value at model-build time, or a cache entry keyed by product id instead of tenant and product id. For example, at [company] we'd switched toAddDbContextPoolfor a [small] throughput gain. Pooling only allows a constructor that takes the options, so the context read the tenant from anAsyncLocalthe first time the filter needed it and cached it in a field to avoid repeated lookups. Pooled instances live across requests and EF Core doesn't reset your fields, so a reused instance kept the first tenant it served. Under load about [1 in 2,000] requests got the wrong tenant. A load test alternating two tenants and asserting every row'sTenantIdreproduced it in [minutes].The mistake I see is fixing the line and moving on. I'd also add the tenant id to every log scope and query tag so we can tell exactly which data was exposed and to whom, write a concurrency test that stays in CI, turn on
ValidateScopeseverywhere, check every cache key includes the tenant, and add SQL Server row-level security so a single application bug can't leak data again. Assume shared state is guilty until proven innocent."
| Suspect | Symptom pattern | How to confirm |
|---|---|---|
| Pooled context caching tenant in a field | Rare, load-dependent, random tenant | Load test alternating tenants; log ContextId (instance + lease) and tenant |
| Singleton capturing scoped tenant provider | Always the first tenant since start-up | ValidateScopes; inspect registrations; restart changes the "owner" |
| Filter capturing a local value | Every query uses one tenant | ToQueryString() shows a constant instead of a parameter |
| Cache keyed without tenant | Specific pages or lookups only | Cache key review; cache hit logs |
AsyncLocal not set or flowing into fire-and-forget work |
Background work with wrong tenant | Log tenant at job start and per query |
| Step | Why |
|---|---|
| Disable suspect endpoint or pooling | Stop further exposure |
| Preserve logs and traces | Determine who saw what |
| Notify privacy officer | NDB assessment within 30 days, sooner if clearly eligible |
| Identify affected tenants | Contractual and legal notification |
In a [B2B practice-management SaaS with 400 tenants], disabling pooling cost [about 0.5% CPU] and removed the leak entirely; the alternating-tenant load test of [50,000 requests] went from [25] mismatches to [zero], and RLS added later blocked a separate raw SQL bug in testing.
Checks incident handling for a security-relevant bug and deep knowledge of EF Core pooling, DI lifetimes and shared state.
Green flags
Red flags
Request A (tenant 1) ── lease ctx#7 ── TenantId read, cached in _tenantId = 1 ── return ──┐
EF Core resets tracker and its own state
NOT your fields (_tenantId stays 1) │
Request B (tenant 2) ── lease ctx#7 ── filter reads TenantId → 1 ✖ leak ◀───────────────┘
With AddDbContextPool, a context instance is created once and leased many times, and it must have a constructor that takes only DbContextOptions, so you cannot inject a scoped tenant provider. Teams then reach for ambient state (an AsyncLocal, IHttpContextAccessor) and, to save a lookup, cache the result in a field. That cache is the leak. EF Core's reset on return covers the change tracker, database facade state and a few options, not custom members.
Safe patterns:
AddPooledDbContextFactory plus a scoped factory that leases a context and sets TenantId every time.A singleton that receives a scoped ITenantProvider (or a DbContext) keeps the first instance for the process lifetime. ValidateScopes = true (on by default in Development only) throws at resolve time; ValidateOnBuild catches it at start-up. Enable both in integration tests and staging.
EF Core builds and caches the model once per context type, and the filter expression is part of it.
HasQueryFilter(e => e.TenantId == TenantId) where TenantId is a member of the context: EF Core recognises the context reference and turns it into a parameter evaluated per query, on the current instance.var t = provider.TenantId; HasQueryFilter(e => e.TenantId == t) in OnModelCreating: the closure value is evaluated once while building the model and stored with it, so every context of that type uses the same tenant.ToQueryString() shows the difference: @ef_filter__TenantId versus a literal GUID.
IMemoryCache, HybridCache and output caching are process-wide (and distributed caches are shared across instances). Any key without the tenant, and the user for per-user data, shares entries across tenants. Output caching needs a policy that varies by tenant. Centralise key building in one helper so nobody forgets.
TenantId and DbContext.ContextId (instance id plus lease number, so you can see reuse).TagWith($"tenant:{tenantId}") so the SQL in Query Store and Application Insights carries the expected tenant.TenantId values with the current tenant and logs a critical event.A connection interceptor calls sp_set_session_context @key = N'TenantId', @value = @t, @read_only = 1 on each connection open; a security policy filters every table by SESSION_CONTEXT(N'TenantId'). Even if the application filter is wrong, SQL Server returns no rows for other tenants. With connection pooling, set it on every open.
ContextId per request and watch lease numbers increase on reused instances.ValidateScopes throw.ToQueryString() for a context-member filter and a captured-local filter.The bug: a pooled context that caches the tenant the first time it is read. With AddDbContextPool the instance outlives the request, so the cached value is reused by the next lease.
namespace Practice.Infrastructure;
using Microsoft.EntityFrameworkCore;
// Ambient tenant set by middleware for each request.
public static class TenantContext
{
private static readonly AsyncLocal<Guid?> Current = new();
public static Guid? Value { get => Current.Value; set => Current.Value = value; }
}
// ✖ Pooled contexts are reused across requests; EF Core does not reset _tenantId.
public sealed class LeakyDbContext(DbContextOptions<LeakyDbContext> options) : DbContext(options)
{
private Guid? _tenantId;
public Guid TenantId => _tenantId ??= TenantContext.Value ?? throw new InvalidOperationException();
public DbSet<Patient> Patients => Set<Patient>();
// The filter itself is parameterised correctly (it reads a context member per query) -
// the bug is that the member returns the first tenant this pooled instance ever served.
protected override void OnModelCreating(ModelBuilder b) =>
b.Entity<Patient>().HasQueryFilter("Tenant", p => p.TenantId == TenantId); // EF Core 10 named filter
}
The fix: a pooled factory with a scoped wrapper that sets the tenant on every lease.
namespace Practice.Infrastructure;
using Microsoft.EntityFrameworkCore;
public sealed class PracticeDbContext(DbContextOptions<PracticeDbContext> options) : DbContext(options)
{
// Set on every lease by the scoped factory; read per query by the filter (parameterised).
public Guid TenantId { get; set; }
public DbSet<Patient> Patients => Set<Patient>();
protected override void OnModelCreating(ModelBuilder b) =>
b.Entity<Patient>().HasQueryFilter("Tenant", p => p.TenantId == TenantId);
}
public sealed class TenantDbContextFactory(
IDbContextFactory<PracticeDbContext> pooledFactory,
ITenantProvider tenant) : IDbContextFactory<PracticeDbContext>
{
public PracticeDbContext CreateDbContext()
{
var context = pooledFactory.CreateDbContext();
context.TenantId = tenant.TenantId; // every lease, never cached
return context;
}
}
// Program.cs
builder.Services.AddPooledDbContextFactory<PracticeDbContext>(o =>
o.UseSqlServer(builder.Configuration.GetConnectionString("Practice")));
builder.Services.AddScoped<ITenantProvider, ClaimsTenantProvider>();
builder.Services.AddScoped<TenantDbContextFactory>();
builder.Services.AddScoped(sp => sp.GetRequiredService<TenantDbContextFactory>().CreateDbContext());
// Catch captive dependencies in every environment, not only Development.
builder.Host.UseDefaultServiceProvider(o => { o.ValidateScopes = true; o.ValidateOnBuild = true; });
Cache keys must carry the tenant too:
var fees = await cache.GetOrCreateAsync(
$"tenant:{tenantId}:fee-schedule", // ✔ not just "fee-schedule"
async ct => await db.FeeSchedules.AsNoTracking().ToListAsync(ct),
cancellationToken: ct);
A concurrency test that reproduces the leak (fails with the leaky context, passes with the fix):
[Fact]
public async Task Alternating_tenants_never_see_each_others_rows()
{
var tenants = new[] { TenantA, TenantB };
await Parallel.ForAsync(0, 5_000, async (i, ct) =>
{
var tenant = tenants[i % 2];
var client = factory.CreateClientFor(tenant); // token with that tenant's claim
var patients = await client.GetFromJsonAsync<PatientDto[]>("/patients", ct);
Assert.All(patients!, p => Assert.Equal(tenant, p.TenantId));
});
}
AddDbContextPool for performance without measuring. Why it is wrong: The gain is usually tiny compared with the risk for stateful contexts. Instead: Benchmark first; pool only stateless contexts.ValidateScopes off outside Development. Why it is wrong: Captive scoped services in singletons go undetected. Instead: Enable ValidateScopes and ValidateOnBuild in integration tests and staging.Leaks like this come from optimisations and conveniences that introduce shared state: pooling, singletons, caches, ambient context. My rule for multi-tenant code is that anything process-wide must be explicitly tenant-aware or provably stateless, and that is checked by tests that run tenants concurrently, not by code review alone.
I also want the database to enforce isolation for personal data. Row-level security costs a little CPU and some admin friction, but it turns a single application bug from a breach into a failed query.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| No pooling | Default for tenant-aware contexts | Microseconds per request | Proven, measured hot path |
| Pooled factory + per-lease tenant | High-throughput services | More wiring, must be tested | Teams unfamiliar with the pattern |
| Row-level security backstop | Personal or regulated data | CPU, admin queries need bypass | Non-sensitive data |
| Database per tenant | Strict isolation contracts | Operations, cost | Many small tenants |
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.
It is a captive dependency. The singleton was built once, from the first request's scope, so it holds that request's DbContext for ever. Every user now shares one context: its identity map returns stale entities that were tracked earlier, concurrent requests hit it at the same time and EF throws "A second operation was started", and the change tracker grows. Often the first scope's disposal even leaves it disposed (ObjectDisposedException).
Development would have thrown, because ValidateScopes is on only in Development by default. I confirm by enabling ValidateScopes and ValidateOnBuild and reading the exception. The fix is to make PricingService scoped, or, if it truly must be a singleton (it holds a cache), inject IDbContextFactory<AppDbContext> and create a context per operation. Then turn validation on everywhere.
In a shared schema every tenant-owned table gets a TenantId column, and the DbContext declares a global query filter such as e => e.TenantId == TenantId, where TenantId is a property on the context. EF Core treats that member as a parameter, so each query adds WHERE TenantId = @__TenantId. A scoped tenant provider sets it from a validated claim, and a SaveChanges interceptor stamps it on inserts.
The risks are the gaps around the filter: IgnoreQueryFilters(), raw SQL, ExecuteUpdate, pooled contexts keeping the last tenant, and background jobs with no request. The trade-off: one filter gives cheap, convenient isolation, but it is a single line of defence, so high-stakes systems add row-level security in SQL Server as well.
How to tell it (STAR)
**S:** At [company] we ran a multi-tenant practice-management app for [400] clinics. **T:** Two clinics reported seeing other clinics' patients, and I [led the incident response]. **A:** I treated it as a breach first: hotfixed pooling off, preserved logs and worked with our privacy officer. Logging the context id and tenant showed reused pooled contexts carrying the previous tenant, because the tenant was cached in a field. I reproduced it with an alternating-tenant load test, fixed it with a per-lease tenant factory, and added row-level security. **R:** Exposure was limited to [N] requests over [a week], the test now runs on every build, and RLS has since blocked [one] unrelated raw SQL bug.
Last updated 23 Nov 2026.