Skip to content

Multi-Tenancy ​

Infrastructure components for automatic data isolation between tenants.

Overview ​

The multi-tenancy infrastructure provides (ADR 0011, D17):

ComponentDescription
ITenantSessionRead port: tenant, group, scope and kind of the current session
ITenantAmbientWrite port: Begin(TenantSnapshot) and BeginSystemScope(reason) — both restore on dispose
TenantSnapshotImmutable value with everything the flow knows about its tenant
TenantAmbientThe single AsyncLocal holding the snapshot, and its only writer
TenantQueryFilterExtensionsEF Core query filter extensions
TenantSaveChangesInterceptorThe tenant write guard of every tenant-owned DbContext

Architecture ​

┌──────────────────────────────────────────────────────────────┐
│                      Application Layer                        │
│  ┌──────────────────────┐        ┌────────────────────────┐   │
│  │    ITenantSession    │        │     ITenantAmbient     │   │
│  │ (read: handlers,     │        │ (write: entry points — │   │
│  │  filters, telemetry) │        │  middleware, jobs)     │   │
│  └──────────┬───────────┘        └───────────┬────────────┘   │
└─────────────┼────────────────────────────────┼────────────────┘
              ▼                                ▼
┌──────────────────────────────────────────────────────────────┐
│                    Infrastructure Layer                       │
│  ┌────────────────────────────────────────────────────────┐   │
│  │  TenantAmbient — AsyncLocal<TenantSnapshot> (one only)  │   │
│  └────────────────────────────────────────────────────────┘   │
│                 │                          │                  │
│        ┌────────┴───────┐         ┌────────┴────────┐         │
│        │ Query filters  │         │ SaveChanges     │         │
│        │ (ITenantQuery- │         │ interceptor     │         │
│        │  Context)      │         │                 │         │
│        └────────────────┘         └─────────────────┘         │
└──────────────────────────────────────────────────────────────┘

The tenant context ​

One immutable TenantSnapshot per execution flow: tenant, group, the scope a read was granted, whether the tenant filter is on and how optional-tenant rows are seen. Code reads it through ITenantSession and changes it only through ITenantAmbient, and every change returns a handle that puts the previous snapshot back — nested, on exception and across awaits:

csharp
public sealed class InvoiceHandler(ITenantSession session) // a handler only reads
{
    public Guid Tenant => session.RequiredTenantId();
}

public sealed class NightlyJob(ITenantAmbient ambient)   // an entry point writes
{
    public async Task RunForAsync(Guid tenantId)
    {
        using (ambient.Begin(TenantSnapshot.ForTenant(tenantId)))
        {
            // everything here — queries, saves, telemetry — runs as tenantId
        }
        // the worker's previous context is back, even if the block threw
    }
}

The HTTP request's snapshot is begun by the session middleware from the tenant_id claim of the validated session (D18) — never from a header, query string or route value. The scope pipeline step narrows it to the granted scope with TenantSnapshot.WithScope(...).

Why static? ​

EF Core caches compiled models (including query filters) per DbContext type, so the filter cannot close over a per-request object. It reads TenantAmbient.Current at query execution time, and AsyncLocal keeps that value with its flow across awaits and apart from concurrent flows.

Query Filters ​

Every entity that carries a tenant declares how with one of the two markers of Gryd.Domain.Abstractions (ADR 0011, D22): IRequireTenant (the row always has an owner) or IOptionalTenant (a null tenant means a global row). ApplyTenantQueryFilters filters every marked entity:

csharp
using Gryd.Infrastructure.Tenancy;

public class AppDbContext : DbContext, ITenantQueryContext
{
    public DbSet<Product> Products => Set<Product>();

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.ApplyTenantQueryFilters(this);
    }
}

ITenantQueryContext ​

The DbContext declares it and implements nothing: its members read the snapshot of the flow, and EF Core parametrizes them, so the value is evaluated at query time.

Reads fail closed, as fixed behaviour (D19): with no tenant in session an IRequireTenant entity returns no row and an IOptionalTenant one only its global rows.

Bypassing the tenant filter ​

There is one way, and it is audited (D21):

csharp
await using (ambient.BeginSystemScope("files: retention purge across every tenant"))
{
    // reads here see every tenant's rows
}

It is for jobs, hosted services and provisioning only — an architecture test refuses it in request handlers and controllers — and each use is recorded in the scope audit trail (IScopeAuditor, entity SystemScope) with its reason, caller, the flow's tenant, start and duration. The record is written when the scope ends, after the filter is back on; prefer await using. A routine that runs often and usually finds nothing to do can ask to be recorded only when it changed something: BeginSystemScope(reason, SystemScopeRecording.OnlyWhenChanged), then scope.MarkChanged() where it acts. The default records every use.

IgnoreQueryFilters() drops the tenant filter for a whole query, so it is allowed only in the members listed in build/ignore-query-filters-exceptions.txt, each with its justification; a query that reads one tenant restates the tenant predicate itself. TenantBypassArchitectureTests fails on an unlisted use and on a stale entry.

SaveChanges Interceptor ​

TenantSaveChangesInterceptor is the one write guard (D20). Attach it to every DbContext with a tenant entity; a module registers it with services.TryAddGrydTenantSaveChangesInterceptor():

csharp
builder.Services.AddDbContext<AppDbContext>((sp, options) =>
{
    options.UseNpgsql(connectionString);
    options.AddInterceptors(sp.GetRequiredService<TenantSaveChangesInterceptor>());
});

Its four guards are always on:

GuardBehaviour
StampA new IRequireTenant row without a tenant gets the session's; without one it is refused. An IOptionalTenant row is never stamped.
Immutable ownerA change of TenantId is refused.
Session tenantA tenant session never writes a row owned by another tenant. Under a global scope or a system flow the row keeps the tenant its code chose.
Group scopeNothing is written under a group scope (ADR 0006).

modelBuilder.ProtectTenantWrites() adds the tenant to the UPDATE/DELETE predicate as a concurrency token, so a detached row of another tenant attached with a forged owner cannot overwrite it. ExecuteUpdate/ExecuteDelete bypass both and must stay explicitly scoped.

Crossing the Tenant Filter ​

Soft Delete Filters ​

csharp
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.ApplyTenantQueryFilters(this);
    modelBuilder.ApplySoftDeleteFilters();
}

ApplySoftDeleteFilters() hides every ISoftDeletable row with IsDeleted = true from queries. It also makes the unique indexes of those entities agree with that filter: a soft-deleted row stays in the table, so a unique index that still counted it would refuse the row a re-creation inserts (delete a link, create it again → unique violation). Every unique index of a soft-deletable entity becomes partial on "IsDeleted" = false, AND-ed with the filter the index already declares. Call it after the entity configurations, so it sees every index.

IndexResult
Unique, no filter"IsDeleted" = false
Unique, with a filter"IsDeleted" = false AND (<filter>)
Unique, filter already names "IsDeleted"Left as written
Unique, marked .IncludesSoftDeletedRows()Left as written: counts deleted rows
Not uniqueLeft as written

Keep the default for business keys: a name, a slug, a number, the link between two entities. Opt out only for a value the system issues once and never again, which must stay unique across the whole history:

csharp
builder.HasIndex(token => token.TokenHash)
    .IsUnique()
    .IncludesSoftDeletedRows();

A deleted row is kept as history. Re-creating it inserts a new row next to it; it does not restore the old one.

DI Registration ​

A host with GrydAuth or the remote consumer gets the tenancy from them. Any other host registers it once and sets the request's tenant from the session:

csharp
builder.Services.AddGrydTenancy();
// ...
app.UseAuthentication();
app.UseGrydTenantSession();
app.UseAuthorization();

See Also ​

Released under the MIT License.