Org Skills

Multi-tenancy in a .NET service

Supporting material for dotnet-architecture. Agents load it on demand; it ships inside the skill folder.

RawSource

Verified 2026-09 against https://learn.microsoft.com/en-us/ef/core/querying/filters, https://learn.microsoft.com/en-us/ef/core/miscellaneous/multitenancy and https://learn.microsoft.com/en-us/ef/core/performance/advanced-performance-topics.

1. Choose the isolation model

Model Isolation Cost Pick it when
Shared schema, TenantId column Logical only — a missing filter leaks data Lowest; one migration, one connection pool Default. Many tenants, similar size, no regulatory separation
Schema per tenant (same database) Stronger; per-tenant backup is awkward One migration run per schema; connection strings stay identical Tens of tenants, per-tenant customisation of a few tables
Database per tenant Strongest; per-tenant restore, region placement, key management Migration fan-out, connection-pool pressure, deployment is a loop Regulated tenants, very uneven sizes, or a contractual requirement
Hybrid — shared by default, dedicated for named tenants Per-tenant Two code paths through the same DbContext factory Enterprise tier on a self-serve product

Decide once, write it in the ADR, and make the choice invisible to feature code: everything below resolves through ITenantContext, so switching a tenant from shared to dedicated is a configuration change, not a rewrite.

2. Resolve the tenant once, at the edge

public interface ITenantContext
{
    string TenantId { get; }
}

internal sealed class HttpTenantContext(IHttpContextAccessor accessor) : ITenantContext
{
    public string TenantId =>
        accessor.HttpContext?.User.FindFirst("tenant_id")?.Value
        ?? throw new InvalidOperationException("No tenant on the current principal.");
}

Registered scoped. Take the tenant from the validated token, never from a header, query string or route value the caller controls — that is the entire security boundary of a shared-schema model.

Background work has no HttpContext. Give the worker an explicit implementation that reads the tenant from the message headers, and set it inside the scope it creates per message.

3. Shared schema: global query filters

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Order>()
        .HasQueryFilter("SoftDeletion", o => !o.IsDeleted)   // named filters: EF Core 10+
        .HasQueryFilter("Tenant", o => o.TenantId == _tenant.TenantId);
}

Before EF Core 10, one HasQueryFilter call per entity combined with &&; a second call silently replaced the first, which is a classic cause of a "deleted rows are back" bug:

modelBuilder.Entity<Order>().HasQueryFilter(o => !o.IsDeleted && o.TenantId == _tenant.TenantId);

Disabling filters is per query: IgnoreQueryFilters() removes all of them; EF Core 10 takes names, IgnoreQueryFilters(["SoftDeletion"]), so an admin report can see deleted rows without seeing other tenants' rows. Reserve the un-named IgnoreQueryFilters() for migrations and support tooling.

Two filter traps worth knowing before you debug them:

  • A required navigation to a filtered entity produces an INNER JOIN, so the child rows disappear along with the filtered parent. Either make the navigation optional or put the matching filter on both entity types.
  • Filters apply to queries, not to Add. Set TenantId in SaveChangesAsync from ITenantContext so a handler cannot forget, and assert it: an entity saved with the wrong tenant is invisible afterwards, which makes the bug look like data loss.

4. DbContext pooling and the tenant

AddDbContextPool reuses context instances, and a pooled instance keeps the model it was built with. A filter that closes over a scoped ITenantContext is therefore not safe with the default pooling setup — the second tenant can get the first tenant's compiled filter.

Two safe combinations:

  • AddDbContext (no pooling) with the tenant injected into the context. Simple; costs a small allocation per request.
  • AddDbContextPool plus AddDbContextFactory with a dynamic model cache key so each tenant gets its own compiled model. Only worth it under measured pressure — see the EF "advanced performance" guidance before taking it on.

5. Schema or database per tenant

  • Resolve the connection string per tenant from a tenant catalogue (its own small database), cached, and build the context through IDbContextFactory<T>.
  • Connection pools are per connection string. A hundred tenant databases at Max Pool Size=100 is ten thousand possible connections; size the pool down and put the number in the ADR.
  • Migrations become a loop over tenants, with a per-tenant success record and a resumable runner. Deploy code that works before and after the migration (expand/contract, see database-migrations), because the loop is never atomic across tenants.
  • Onboarding a tenant is now a provisioning workflow: create the store, run migrations, seed, record it in the catalogue. Make it idempotent — it will be retried.

6. Guardrails

  • An architecture or model test that fails when an entity has a TenantId property and no query filter (architecture-tests.md §4).
  • An integration test that authenticates as tenant A and asserts 404 — not 403 — for tenant B's resource id, so the response does not confirm existence.
  • A test that a background message handler without a tenant in its headers is dead-lettered rather than processed under the last tenant seen.
  • Tenant id on every log record and trace (service-operability), because the first question about every incident is "which tenants are affected".