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

📚 Interview question

Show how you would implement multi-tenancy in EF Core with a tenant id on every row, a global query filter and a tenant provider. Where does the tenant id come from, how do inserts get it, and what are the risks with IgnoreQueryFilters, DbContext pooling and background jobs?

Shared-schema multi-tenancy in EF Core 10: TenantId columns, a named global query filter, a scoped tenant provider, stamping inserts, and the leaks caused by IgnoreQueryFilters, pooling and jobs without a request.

Mid-Level Coding Intermediate aspnet-core dbcontext-pooling ef-core global-query-filters multi-tenancy security

🎯 Key points

  • A TenantId column on every tenant-owned table, leading the hot composite indexes, e.g. (TenantId, CreatedAt), so tenant-filtered queries seek instead of scanning every tenant's rows
  • A global query filter that compares TenantId with a DbContext member, so EF Core parameterises it per query instead of baking in a constant
  • A scoped ITenantProvider resolved from a validated source (token claim), never from a raw header; it fails closed when no tenant is set
  • Inserts stamped in a SaveChangesInterceptor; cross-tenant updates and deletes rejected
  • EF Core 10 named filters let you ignore only the soft-delete filter and keep the tenant filter
  • IgnoreQueryFilters, raw SQL and bulk paths (ExecuteUpdate/ExecuteDelete from an unfiltered source, SqlBulkCopy) need explicit tenant handling and review
  • With AddDbContextPool the tenant must be set on each lease; background jobs pass the tenant explicitly
  • Automated cross-tenant tests in CI for every endpoint, plus SQL Server row-level security for personal data, because a leak is likely a notifiable data breach under the Privacy Act 1988

⏱ 30-second 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.

🗣 Full answer (senior)

How I would answer this in an interview

"With a shared schema, isolation is a WHERE TenantId = @tenant on every query, and the point of the EF Core design is that nobody has to remember to write it. I add a TenantId to every tenant-owned entity, usually through an ITenantOwned interface, and in OnModelCreating I apply a query filter that compares it with a property on the DbContext. That detail matters: because the filter references a context member, EF Core caches one query plan and passes the tenant as a parameter. If you closed over a local variable instead, you would capture one tenant for the life of the model, which is a data leak.

The tenant itself comes from a scoped ITenantProvider that reads a claim from the validated token, never from a header the client controls. Inserts get the tenant from a SaveChangesInterceptor, which also refuses to save an entity whose tenant doesn't match. For example, at [company] we ran [about 300] tenants in one Azure SQL database, and I added an integration test that ran every repository method as tenant A against data seeded for tenant B and asserted that nothing came back. It caught [two] raw SQL queries that had bypassed the filter.

The mistake I see is believing the filter covers everything. It doesn't apply to FromSqlRaw without composition, ExecuteSql, ExecuteUpdate on unfiltered sets or anything after IgnoreQueryFilters(), which before EF Core 10 also removed the soft-delete filter and the tenant filter together. Pooling and background jobs are the other two holes. I treat the filter as convenience and back it with tests and, for sensitive data, SQL Server row-level security."


Moving parts

Part Responsibility
ITenantOwned + TenantId column Marks tenant data, indexed as the leading key
ITenantProvider (scoped) Resolves the tenant from a validated claim
Global query filter Adds WHERE TenantId = @p to every query
SaveChangesInterceptor Stamps TenantId on inserts, blocks cross-tenant writes
Tests Prove tenant A never sees tenant B's data

Where the filter does not protect you

Gap Why Mitigation
IgnoreQueryFilters() Removes filters EF Core 10 named filters; ignore only SoftDelete
FromSql / SqlQuery / ExecuteSql Raw SQL you wrote Add the tenant predicate; review and test
ExecuteUpdate / ExecuteDelete Filters apply to the source query, but easy to misuse via unfiltered sets Always start from the filtered DbSet
Pooled contexts Context reused across requests Set the tenant on every lease
Background jobs No HttpContext Pass the tenant id in the message; fail closed

Production example

In a [SaaS rostering platform with 300 tenants on one Azure SQL database], adding TenantId as the leading key column to the [six] busiest indexes cut p95 query time from [180 ms to 25 ms], and the cross-tenant test suite of [400] cases ran in CI on every pull request.

🔍 What the interviewer is checking

Checks whether the candidate can implement shared-schema tenancy correctly and knows exactly where EF Core's filter stops protecting them.

Green flags

  • References a DbContext member in the filter and explains parameterisation
  • Resolves the tenant from a validated claim and fails closed
  • Names IgnoreQueryFilters, raw SQL, pooling and background jobs as gaps
  • Mentions cross-tenant tests or row-level security

Red flags

  • Tenant from a header or query string
  • "The filter handles it" with no tests
  • No indexing on TenantId

📚 Learn in depth

1. How a context-member filter becomes a parameter

HasQueryFilter(e => e.TenantId == this.TenantId)
        │  EF Core sees a reference to the DbContext instance
        ▼
Compiled query (cached once per model):
  SELECT ... FROM Orders o WHERE o.TenantId = @__ef_filter__TenantId
        │  at execution, EF reads this.TenantId from the current context
        ▼
Parameter value differs per context instance

EF Core special-cases members of the DbContext in filters: it extracts them as parameters at execution time. A captured local or a static field is evaluated once when the model is built and frozen into the cached model, so every tenant would see the first tenant's data.

2. Named filters in EF Core 10

Before EF Core 10 an entity had only one filter, so tenant and soft delete were combined with &&, and IgnoreQueryFilters() removed both. EF Core 10 adds named filters:

modelBuilder.Entity<Order>()
    .HasQueryFilter("Tenant", o => o.TenantId == TenantId)
    .HasQueryFilter("SoftDelete", o => !o.IsDeleted);

db.Orders.IgnoreQueryFilters(["SoftDelete"]);   // tenant filter still applies

3. Resolving the tenant safely

HTTP request → JWT validated → claim "tid" → ITenantProvider (scoped) → DbContext.TenantId

Never trust X-Tenant-Id from the client by itself. If tenants are chosen by subdomain, map the host to a tenant and check the user belongs to it.

4. Pooling

AddDbContextPool reuses context instances. EF Core resets its own state (tracker, options) but not your fields. Two safe patterns:

  • Do not pool; context creation costs microseconds compared with a database round trip.
  • Use AddPooledDbContextFactory and a scoped wrapper factory that leases a context and sets TenantId every time.

5. Background work and fail-closed design

A hosted service has no request scope. Create a scope, set the tenant from the message or job argument, and have the provider throw when no tenant is set. An unset tenant must mean "no rows", or better an exception, never "all rows".

6. Indexing

Every query now filters on TenantId, so it should lead the composite keys of the hottest indexes: (TenantId, CreatedAt), (TenantId, CustomerId). A unique email per tenant is (TenantId, Email).

7. Defence in depth

SQL Server row-level security (a security predicate function using SESSION_CONTEXT(N'TenantId'), set by a connection interceptor) enforces the same rule inside the database, covering raw SQL and other tools. It costs a little CPU and complicates admin queries.

Try it yourself

  1. Build the filter with a captured local variable, run queries as two tenants, and watch the second see the first's data.
  2. Switch to a context property and check the parameter with ToQueryString().
  3. Enable AddDbContextPool, forget to reset the tenant, and write a test that exposes the leak.
  4. Add EF Core 10 named filters and verify IgnoreQueryFilters(["SoftDelete"]) keeps tenant isolation.
  5. Write a parameterised test that runs every read endpoint as tenant A against tenant B's data.

💻 Code

A tenant provider, a named query filter, and an interceptor that stamps and checks the tenant on save:

namespace Rostering.Infrastructure;

using System.Security.Claims;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;

public interface ITenantOwned { Guid TenantId { get; set; } }

public interface ITenantProvider { Guid TenantId { get; } }

// Scoped: one per request. Fails closed when no tenant is present.
public sealed class ClaimsTenantProvider(IHttpContextAccessor accessor) : ITenantProvider
{
    public Guid TenantId =>
        Guid.TryParse(accessor.HttpContext?.User.FindFirstValue("tid"), out var id)
            ? id
            : throw new InvalidOperationException("No tenant for this operation.");
}

public sealed class Shift : ITenantOwned
{
    public Guid Id { get; init; } = Guid.CreateVersion7();
    public Guid TenantId { get; set; }
    public required string Role { get; set; }
    public DateTimeOffset StartsAt { get; set; }
}

public sealed class RosterDbContext(DbContextOptions<RosterDbContext> options, ITenantProvider tenant)
    : DbContext(options)
{
    // A DbContext member: EF Core reads it per query and sends it as a parameter.
    public Guid TenantId => tenant.TenantId;

    public DbSet<Shift> Shifts => Set<Shift>();

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Shift>(b =>
        {
            b.HasQueryFilter("Tenant", s => s.TenantId == TenantId); // EF Core 10 named filter
            b.HasIndex(s => new { s.TenantId, s.StartsAt });          // tenant leads the index
        });
    }
}

public sealed class TenantStampInterceptor(ITenantProvider tenant) : SaveChangesInterceptor
{
    public override ValueTask<InterceptionResult<int>> SavingChangesAsync(
        DbContextEventData eventData, InterceptionResult<int> result, CancellationToken ct = default)
    {
        foreach (var entry in eventData.Context!.ChangeTracker.Entries<ITenantOwned>())
        {
            if (entry.State == EntityState.Added)
                entry.Entity.TenantId = tenant.TenantId;
            else if (entry.State is EntityState.Modified or EntityState.Deleted
                     && entry.Entity.TenantId != tenant.TenantId)
                throw new InvalidOperationException("Cross-tenant write blocked.");
        }
        return base.SavingChangesAsync(eventData, result, ct);
    }
}
// Program.cs: no pooling, so the scoped provider and interceptor are fresh per request.
builder.Services.AddHttpContextAccessor();
builder.Services.AddScoped<ITenantProvider, ClaimsTenantProvider>();
builder.Services.AddScoped<TenantStampInterceptor>();
builder.Services.AddDbContext<RosterDbContext>((sp, options) => options
    .UseSqlServer(builder.Configuration.GetConnectionString("Roster"))
    .AddInterceptors(sp.GetRequiredService<TenantStampInterceptor>()));

The SQL EF Core sends for db.Shifts.Where(s => s.StartsAt >= from):

SELECT [s].[Id], [s].[Role], [s].[StartsAt], [s].[TenantId]
FROM [Shifts] AS [s]
WHERE [s].[TenantId] = @ef_filter__TenantId AND [s].[StartsAt] >= @from

⚠ Common mistakes

  • Mistake: Writing the filter against a captured local or static value. Why it is wrong: It is evaluated once and frozen into the cached model, so every tenant sees one tenant's data. Instead: Reference a property on the DbContext.
  • Mistake: Taking the tenant from a client-supplied header. Why it is wrong: Any user can read another tenant's data by changing it. Instead: Use a claim from a validated token and check membership.
  • Mistake: Calling IgnoreQueryFilters() to show deleted rows. Why it is wrong: Before EF Core 10 it also removes the tenant filter. Instead: Use EF Core 10 named filters and ignore only SoftDelete.
  • Mistake: Writing raw SQL without a tenant predicate. Why it is wrong: Global filters do not apply to ExecuteSql or uncomposed raw SQL. Instead: Add the predicate, or compose LINQ over FromSql so the filter applies, and test it.
  • Mistake: Turning on AddDbContextPool with tenant state in fields. Why it is wrong: A pooled instance keeps the previous request's tenant. Instead: Avoid pooling or set the tenant on every lease.
  • Mistake: Defaulting to "all tenants" when no tenant is resolved. Why it is wrong: A missing claim or a background job then reads everything. Instead: Fail closed and throw.
  • Mistake: Leaving TenantId out of indexes. Why it is wrong: Every query filters on it, so scans grow with the number of tenants. Instead: Make it the leading key of the hot indexes.

🏛 Senior insight: trade-offs

A global filter is a convenience, not a security boundary. I want three layers for tenant isolation: the EF Core filter so normal code is correct by default, automated cross-tenant tests so mistakes are caught in CI, and, where the data is sensitive or contractual isolation is promised, SQL Server row-level security so the database enforces it even for raw SQL and reporting tools.

Under the Privacy Act 1988, one tenant seeing another's personal information is likely a notifiable data breach. That makes the cost of the extra layers easy to justify for anything holding personal data.

Option When it fits Cost When not to
EF Core filter only Low-sensitivity data, small team Cheapest Personal or financial data
Filter + cross-tenant tests Most SaaS apps Test suite upkeep —
Filter + SQL Server RLS Sensitive data, contractual isolation Some CPU, harder admin queries Prototypes
Database per tenant Strong isolation, per-tenant restore Operations and cost Thousands of tiny tenants

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions global query filters Why: Checks how filters work internally and EF Core 10 named filters
    How to answer

    A global query filter is a predicate configured with HasQueryFilter that EF Core adds to every LINQ query for that entity type: direct queries, Includes, navigation loads, Find and even ExecuteUpdate/ExecuteDelete. Typical uses are soft delete (!IsDeleted) and multi-tenancy (TenantId == _tenantId). Per-request values must come from a DbContext member so EF parameterises them per context instance. IgnoreQueryFilters() turns filters off for one query, and EF Core 10 named filters let you define several and ignore just one (IgnoreQueryFilters(["SoftDelete"])). The big pitfall: a required navigation to a filtered entity becomes an INNER JOIN, so dependants vanish silently. The trade-off is safety by default versus hidden behaviour that surprises people and needs matching indexes.

  2. When: Candidate mentions DbContext pooling Why: Checks what pooling resets and how tenant state leaks
    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.

  3. When: Candidate mentions defence in depth Why: Checks combining the EF filter with SQL Server row-level security
    How to answer

    The EF filter keeps normal code tenant-scoped automatically, so handlers stay simple and nobody forgets a Where. Row-level security enforces the same rule in the database: create a security policy with an inline predicate function comparing TenantId to SESSION_CONTEXT(N'TenantId') (plus a block predicate to stop cross-tenant writes), and set the session context from a DbConnectionInterceptor when each connection opens, with @read_only = 1. Together they're defence in depth: raw SQL, IgnoreQueryFilters or a bug still can't read another tenant's rows. Costs: the predicate runs on every query, so TenantId must lead the relevant indexes or RLS can turn seeks into scans on large tables; debugging is harder because rows silently disappear; and the session context must be set on every connection open because of pooling.

🛠 Real-world problems: how you handle them

A reporting query bypassed the tenant filter
Situation
[Multi-tenant HR SaaS on Azure SQL, Australia East, ~300 tenants in one database]. A new export endpoint used `FromSqlRaw` with a hand-written CTE for performance.
Signals
A customer support ticket reported names they did not recognise in an export. No errors in logs; the endpoint returned 200 with more rows than expected.
Investigation
Reproduced with two test tenants. `ToQueryString()` and EF Core command logging showed the SQL had no `TenantId` predicate: the raw query ended in `ORDER BY`, so EF Core could not compose over it and the global filter was not applied. Searched the codebase for `FromSqlRaw`, `SqlQuery` and `ExecuteSql` and found two more.
Resolution
Immediate: disabled the endpoint with a feature flag, identified affected tenants from logs, and started the Notifiable Data Breaches assessment with the privacy officer. Real fix: rewrote the query to compose LINQ over `FromSql` (so the filter applies) and added an explicit tenant parameter to the other raw queries.
Prevention
A cross-tenant integration test for every read endpoint, an analyser rule that flags raw SQL APIs for review, and SQL Server row-level security keyed on `SESSION_CONTEXT` set by a connection interceptor.

How to tell it (STAR)

**S:** At [company] we ran [300] tenants in one Azure SQL database with an EF Core tenant filter. **T:** A customer reported unfamiliar names in an export, and I [led the investigation]. **A:** I reproduced it with two tenants and found the export used raw SQL that EF Core could not compose over, so the filter never applied. I switched the endpoint off, worked with our privacy officer on the breach assessment, rewrote the query, and added cross-tenant tests for every endpoint plus row-level security in the database. **R:** [N] tenants were affected for [a few hours]; since then the test suite has caught [several] unsafe queries before merge.

↩ Usually asked after

More in Production EF

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me