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

📚 Interview question

A customer reports seeing another tenant's records in your multi-tenant EF Core application, and you cannot reproduce it locally. How do you diagnose whether tenant state is leaking through DbContext pooling, a captured tenant provider or caching, and how do you fix and contain it?

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.

Senior Debugging Advanced dbcontext-pooling debugging ef-core multi-tenancy privacy-act security

🎯 Key points

  • Treat it as a security incident first: contain (flag off, disable pooling), preserve logs, start the Notifiable Data Breaches assessment
  • Intermittent and load-dependent leaks point to shared state: pooled DbContext fields, singleton services capturing a scoped tenant, static or AsyncLocal misuse, caches keyed without tenant
  • AddDbContextPool reuses instances (unchanged behaviour through EF Core 10): EF Core resets its own state on return, not your fields, so a tenant cached in a field survives to the next lease
  • A filter that captures a local value at model-build time becomes a constant in the cached model; a DbContext member becomes a parameter, which ToQueryString() shows
  • Every cache key (IMemoryCache, HybridCache, output caching) includes the tenant, and the user for per-user data
  • Reproduce with a load test that alternates tenants and asserts every row's TenantId; add tenant and ContextId to logs and query tags
  • Fix: avoid pooling or set the tenant per lease via a scoped factory; prevent with ValidateScopes/ValidateOnBuild, concurrent cross-tenant tests and SQL Server row-level security

⏱ 30-second answer

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.
  • A singleton capturing a scoped tenant provider or a DbContext.
  • A query filter that captured a value when the model was built.
  • A cache keyed without the tenant.

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 DbContext that 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 to AddDbContextPool for a [small] throughput gain. Pooling only allows a constructor that takes the options, so the context read the tenant from an AsyncLocal the 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's TenantId reproduced 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 ValidateScopes everywhere, 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."


Suspects, symptoms and checks

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

Containment checklist

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

Production example

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.

🔍 What the interviewer is checking

Checks incident handling for a security-relevant bug and deep knowledge of EF Core pooling, DI lifetimes and shared state.

Green flags

  • Contains first and mentions Privacy Act / NDB obligations
  • Explains why pooling keeps custom fields and how to set tenant per lease
  • Lists captive dependencies, model-baked filters and caches as suspects
  • Reproduces with a concurrent alternating-tenant test

Red flags

  • "Add a Where clause" as the fix
  • No containment or notification thinking
  • Cannot explain why it doesn't reproduce locally

📚 Learn in depth

1. How pooling reuses a context

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:

  • Don't pool (context creation is cheap compared with a database round trip; measure before pooling).
  • AddPooledDbContextFactory plus a scoped factory that leases a context and sets TenantId every time.
  • If you read ambient state, read it on every access and never cache it in the instance.

2. Captive dependencies

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.

3. Parameterised versus model-baked filters

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.

4. Caches

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.

5. Making the bug observable

  • Logging scope with 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.
  • A materialisation or command interceptor in test environments that compares returned TenantId values with the current tenant and logs a critical event.

6. Backstop: row-level security

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.

Try it yourself

  1. Build a pooled context that caches the tenant in a field; run a load test with two tenants and count mismatches.
  2. Log ContextId per request and watch lease numbers increase on reused instances.
  3. Register a singleton that takes a scoped provider and see ValidateScopes throw.
  4. Compare ToQueryString() for a context-member filter and a captured-local filter.
  5. Add a simple RLS policy and confirm cross-tenant queries return nothing even with the EF filter removed.

💻 Code

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));
    });
}

⚠ Common mistakes

  • Mistake: Treating it as an ordinary bug and fixing quietly. Why it is wrong: It is likely an eligible data breach with Privacy Act notification duties. Instead: Contain, preserve evidence and involve the privacy officer immediately.
  • Mistake: Trying to reproduce with one user locally. Why it is wrong: Shared-state leaks need concurrency and tenant interleaving. Instead: Load test alternating tenants with row-level assertions.
  • Mistake: Copying the tenant into a field in a pooled context's constructor. Why it is wrong: The constructor runs once per pooled instance. Instead: Set the tenant on every lease or don't pool.
  • Mistake: Turning on 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.
  • Mistake: Leaving 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.
  • Mistake: Cache keys without the tenant. Why it is wrong: Process-wide caches share entries across tenants. Instead: Include tenant (and user where relevant) in every key.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions DbContext pooling Why: Checks what EF Core resets on return to the pool and what it does not
    How to 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.

  2. When: Candidate mentions a singleton capturing a scoped service Why: Checks captive dependencies and ValidateScopes
    How to answer

    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.

  3. When: Candidate describes the correct tenant filter design Why: Checks the baseline shared-schema tenancy implementation
    How to answer

    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.

🛠 Real-world problems: how you handle them

Pooled DbContext served patients from another clinic
Situation
[Practice-management SaaS for allied health clinics, ~400 tenants, Azure App Service and Azure SQL in Australia East]. A performance sprint switched `AddDbContext` to `AddDbContextPool`; because pooled contexts cannot take scoped services, the context read the tenant from an `AsyncLocal` and cached it in a field.
Signals
Two clinics reported seeing unfamiliar patient names in search results [a week] after the release. No errors; the issue was rare and could not be reproduced locally.
Investigation
Added `TenantId` and `DbContext.ContextId` to the logging scope and found requests where the lease number was above 1 and the filter's tenant differed from the caller's claim. Code review found the cached `_tenantId` field. A load test alternating two tenants reproduced [25] mismatches in [50,000] requests.
Resolution
Immediate: reverted to `AddDbContext` (non-pooled) with a hotfix, identified affected requests from logs, and started the Notifiable Data Breaches assessment with the privacy officer and affected clinics. Real fix: a pooled factory with a scoped wrapper setting the tenant per lease, after benchmarking showed pooling was worth [only a few %] CPU.
Prevention
The alternating-tenant load test in CI, `ValidateScopes` and `ValidateOnBuild` in all environments, tenant id in every log scope, cache key and query tag, and SQL Server row-level security on patient tables.

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.

↩ Usually asked after

More in Production EF

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me