Emre Şahin

Inženirski dnevnik

Tenant isolation is a spectrum, not a switch

How we run pooled and siloed tenants side by side in a .NET SaaS, route DbContexts per tenant, and review authorization as a manifest.

Emre Şahin ·

Most multi-tenancy discussions start with a binary question: shared database or database per tenant? In practice that question is the wrong shape. Isolation is a spectrum, and the useful architectural work is deciding where each tenant sits on it, how a tenant moves along it, and what the code has to guarantee no matter where the tenant ends up.

This post describes how we approached that in a multi-tenant business SaaS I work on as solution architect. It is a set of .NET 10 services behind a YARP gateway, each owning its own PostgreSQL schema, with one identity service that owns tenants and users.

The three points on the spectrum

Pooled. Every tenant shares the same database and tables. Each row carries a tenant_id, and the application filters on it. This is the cheapest option to operate: one database to back up, one set of migrations to run, one connection pool. The failure mode is obvious and severe. A single missing filter is a cross-tenant data leak.

Siloed. Each tenant gets its own database. Isolation is physical, noisy neighbours disappear, and per-tenant backup, restore and deletion become simple operations. The cost moves to operations: every migration must run N times, connection pools multiply, and you now have a fleet to manage instead of a database.

Hybrid. Small tenants share a pool; tenants that are large, regulated or demanding get their own database. You pay the operational cost only where it buys something.

We chose hybrid. Not because it is fashionable, but because our tenant population is uneven. Most tenants are small businesses whose data fits comfortably in a shared pool. A few are large enough that their load, their contractual expectations, or their data-deletion requirements justify a silo. Forcing everyone into silos would have multiplied operational work for tenants that gain nothing from it. Forcing everyone into the pool would have made our largest tenants hostages to everyone else's query patterns.

Rule one: the code must not know where the tenant lives

The most important decision was made before any silo existed. We wrote the services as if every tenant could be pooled, which means every tenant-owned table carries tenant_id, is indexed for it, and is read through a shared DbContext base class that applies global query filters from the current tenant context.

That sounds like it only serves the pooled case. It actually serves both. If a silo database also carries tenant_id and the same filters, then promoting a tenant is a data-copy problem, not a code-rewrite problem. The same entity model and the same migrations run everywhere.

The second half of the rule: services never decide placement themselves. Placement is owned by the identity service, which keeps a registry of where each tenant's data lives.

Per-tenant DbContext routing

Each service registers its context through a tenant-aware extension instead of a fixed connection string:

services.AddTenantDbContext<SalesDbContext>(SalesSchema.Descriptor);

The options callback runs once per request scope. It reads the current tenant, asks a connection resolver for that tenant's connection string, and configures Npgsql with it. Queries never see this; they just get a context pointed at the right database.

The resolver has two implementations selected by configuration: a pooled one that always returns the pool, and a hybrid one that consults the registry. In hybrid mode, the registry lives in the identity schema. Connection strings are stored encrypted with AES-GCM, and only identity can decrypt them. The other services resolve a tenant over gRPC and cache the answer in memory.

A few details in that resolver turned out to matter more than the routing itself:

  • Only a healthy placement is cached. If a tenant is mid-provisioning and we cached "not ready" for the full TTL, the tenant would keep failing after its silo went live. So we re-read the registry until the tenant is active, then cache.
  • Cache freshness is event-driven where it can be. The TTL is a floor, not the mechanism. A switchover bumps a row version in the registry and the resolver exposes an explicit invalidation hook.
  • Fail closed. An early design note had the resolver degrade to the pool if the registry lookup failed. We removed that. If a tenant is supposed to be physically isolated and we cannot confirm where its data lives, the correct answer is an error, not a guess. Falling back to the pool is exactly how you write a silo tenant's data into a shared database.

That last point is the kind of trade-off I care about most in this design. Availability versus isolation is a real tension, and for tenant data we deliberately picked isolation.

Promoting a large tenant

A tenant can be placed in a silo at signup, based on a simple size policy, or promoted later from the admin side. Promotion is the interesting case, because it moves live data.

We modelled it as a saga with compensating steps:

  1. Create the tenant database (idempotent).
  2. Apply every service's migrations to it.
  3. Copy the tenant's rows from the pool, per service, filtered by tenant_id.
  4. Switch over: take a short write lock, sync the final delta, mark the registry entry active.
  5. Clean up the pooled rows after a delay, so there is a window to roll back.

Two decisions shaped this. First, the switchover is a registry write, not a deployment. No service restarts; the next request for that tenant resolves to the new database. Second, the cleanup is deliberately late. Deleting the pooled copy immediately would make the operation irreversible at the exact moment we know least about whether it went well.

Promotion also forced us to be strict about migrations. With one database, a sloppy migration is a bad afternoon. With a fleet, it is a partial outage. Each service keeps its migration history in its own schema, migrations are recorded in a lock file that is checked in CI, and published migrations are never edited or deleted. Destructive changes follow expand/contract across releases. None of this is novel. It just stops being optional once databases multiply.

Authorization as a reviewed manifest

Data isolation is half the problem. The other half is making sure every endpoint asks the right question before touching data. In a codebase with several services and many contributors, the risk is rarely a wrong permission check. It is a missing one, or a check that quietly changes during a refactor.

So we made authorization visible. A test enumerates every endpoint in every service and generates a manifest per service:

{"method":"DELETE","path":"/api/sales/activities/{id:guid}",
 "access":"permission","permissions":["sales.activity.delete"]}

The manifest is committed. The test fails if the generated output differs from what is checked in, and the file is regenerated explicitly. The effect is that any change to an endpoint's access rules shows up as a diff in the pull request, next to the code that caused it. Reviewers do not have to reconstruct the authorization model from attributes scattered across controllers; they read a few changed lines of JSON.

On top of that, pull requests into the development branch run a persona scan: the backend and the user panel start in containers, a matrix of test personas is seeded, and each persona walks the screens it should be able to see. Unexpected 403s, 5xx responses or menu items that lead to a forbidden page fail the build, and the branch policy blocks the merge.

The manifest catches "this endpoint became more permissive". The persona scan catches "this user can no longer do their job". Between them, authorization stops being something we hope is right and becomes something we review.

What I would tell a team starting out

  • Write pooled-ready code from day one, even if you start single-tenant. Retrofitting tenant_id is far more expensive than carrying it.
  • Make placement data, not code. A registry plus a resolver lets you move tenants without deployments.
  • Decide explicitly what happens when you cannot determine placement. For tenant data, fail closed.
  • Treat migrations as fleet operations before you have a fleet.
  • Make authorization diffable. If a reviewer cannot see a permission change, it will eventually ship unnoticed.

Hybrid tenancy is not free. You carry the complexity of both models, and the promotion path is the riskiest code in the system. But it lets the isolation each tenant gets match what that tenant actually needs, and you can move them along the spectrum when that changes.