Multi-tenancy from day one

Retrofitting tenants into a platform is one of the most expensive refactors in software. Putting them in on the first commit costs about a week. Here's what that week looks like.

Stacked translucent planes of coloured cells, each plane a separate tenant

Sooner or later, someone in a planning meeting asks, reasonably, why the first week of a project went on tenant plumbing when there's exactly one customer. It's a fair question. The honest answer is that the alternative is one of the most expensive refactors there is.

The pattern goes like this. You build for one customer. It works. A second customer arrives, and you add a customer_id column to the tables that obviously need it. A third arrives with a requirement that their data stays in a particular region. A fourth wants a feature turned off. By the tenth, every query, cache key, background job and log line is a place where one customer's data might leak into another's, and the only way to know is to read all of it. Teams lose quarters to this.

Putting tenancy in on the first commit costs about a week. This post is what that week looks like, and what matters when a platform grows from one customer to many.

Pick an isolation model on purpose

There's no single right answer, and the wrong move is to not choose. The three common models trade operational cost for blast radius.

Three isolation models comparedIsolation is a dial, not a switch. Most platforms end up mixing models: pooled by default, siloed where a contract demands it.

ModelIsolationCost per tenantMigrationsGood for
Shared tables, tenant columnlogical, enforced in DBlowestrun oncemany small tenants
Schema per tenantnamespacemediumrun N timestens of tenants, some custom
Database per tenantphysicalhighestrun N times, N connectionsregulated, residency, very large tenants

A good default is shared tables, enforced by the database rather than application code, with the option to move a tenant to its own database when a contract requires it. That "option" is the important part. It only stays an option if nothing in the application assumes which model a tenant is on.

Rule one: tenant context is not a parameter

The first instinct is to pass tenant_id around as an argument. Do that and within a month someone forgets it in one function, and that function is the one that matters.

Instead, the tenant is resolved exactly once, at the edge, from the authenticated identity, and carried implicitly from there: in a request-scoped context in the API, in message headers on the queue, in the database session. Application code never chooses a tenant. It inherits one.

How tenant context travels through a requestThe tenant is resolved once at the gateway from the token, never from the request body, and every hop inherits it.

platform/tenancy.py
python
from contextvars import ContextVar
 
_tenant: ContextVar[str | None] = ContextVar("tenant", default=None)
 
class TenantMiddleware:
    async def __call__(self, scope, receive, send):
        claims = await verify_token(scope)
        # the tenant comes from the signed token, never from a header or body field
        token = _tenant.set(claims["tenant"])
        try:
            await self.app(scope, receive, send)
        finally:
            _tenant.reset(token)
 
def current_tenant() -> str:
    t = _tenant.get()
    if t is None:
        raise RuntimeError("no tenant in context")  # fail closed, loudly
    return t

Two details matter. The tenant comes from the signed token, never from a field the caller can set. And current_tenant() raises instead of returning a default. A missing tenant is a bug, and bugs in tenancy should be loud. I would much rather page someone at 3am than serve one customer's documents to another.

Rule two: let the database say no

Application-level filtering works until it doesn't. Every WHERE tenant_id = ... is a line someone can forget, and an ORM query built dynamically is exactly where it gets forgotten. So the database enforces it with row-level security. Even a query with no filter at all returns only the current tenant's rows.

migrations/0003_rls.sql
sql
alter table documents enable row level security;
alter table documents force row level security;  -- applies to the table owner too
 
create policy tenant_isolation on documents
  using (tenant_id = current_setting('app.tenant_id')::uuid)
  with check (tenant_id = current_setting('app.tenant_id')::uuid);
 
-- the app role cannot bypass RLS; migrations run as a separate role
create role app_runtime nologin;
grant select, insert, update, delete on documents to app_runtime;

On every connection checkout, the pool runs set local app.tenant_id = ... inside the transaction, taken from the context variable. If the setting is missing, current_setting errors and the query fails. Fail closed again.

This has costs. Query plans need the tenant_id column leading the relevant indexes or performance drifts. Connection pooling has to be transaction-scoped so a setting can't leak to the next borrower. Debugging in a SQL console means remembering to set the tenant first, which annoys everyone for exactly one week. All of that is cheaper than one leak.

Rule three: every key has a tenant in it

The database was the obvious place. The leaks I've actually seen, in other systems, came from everywhere else.

  • Cache keys. user:42:profile is a cross-tenant leak waiting for two tenants to both have a user 42. Every key gets a tenant prefix, built by one helper, and raw key strings fail review.
  • Object storage. Paths start with the tenant. Signed URLs are scoped to the prefix.
  • Search and vector indexes. Either one index per tenant, or a mandatory tenant filter applied by the retrieval layer itself, not by the caller. For an AI platform this is the one that keeps you up at night, because a retrieval leak looks like a perfectly fluent answer.
  • Queues and jobs. The tenant travels in message metadata, and the worker restores the context before running anything.
  • Logs and metrics. Tagged with the tenant, so that when one tenant has a bad day you can see it without grepping.
lib/keys.ts
ts
// The only way to build a cache key. Lint rule bans raw template strings to redis.
export function key(tenant: string, ...parts: (string | number)[]): string {
  if (!tenant) throw new Error("key() without tenant");
  return ["t", tenant, ...parts].join(":");
}
 
// key(t, "user", 42, "profile") -> "t:9f2c...:user:42:profile"

Per-tenant configuration, not per-tenant code

Tenants want different things. One wants the agent builder off. Another wants a particular connector, a different retention window, a different default language, a stricter approval policy for certain tools. The temptation is an if tenant == ... in the code. That's the start of maintaining ten products.

Everything that varies by tenant lives in a typed configuration record, versioned, with defaults. Code asks "is this feature on for the current tenant", never "which tenant is this". When a new customer comes on board, onboarding is a config change and a data migration, not a release.

tenants/defaults.yaml
yaml
features:
  agent_builder: true
  web_search: false            # off unless a tenant opts in
  slack: true
  teams: true
retention:
  conversations_days: 365
  audit_days: 2555
approvals:
  write_external: require_human
  irreversible: require_named_approver
region: eu-west

Noisy neighbours

Shared infrastructure means one tenant can ruin everyone's afternoon. A bulk import, a connector that re-indexes a few hundred thousand documents, a team running an evaluation script in a loop. None of it malicious, all of it real.

One tenant's bulk import, before and after per-tenant limitsWithout limits, one tenant's spike becomes everyone's latency. With per-tenant budgets, the spike stays inside its own lane.

What helps most, roughly in order:

  1. Per-tenant rate limits at the gateway, sized from the tenant's contract, not a global number.
  2. Separate queues for bulk work. Indexing and imports go to a lane with its own workers, so they never sit in front of an interactive request.
  3. Fair scheduling inside shared workers, so a tenant with ten thousand queued jobs doesn't starve one with ten.
  4. Model and token budgets per tenant, because on an AI platform the expensive shared resource isn't the database, it's inference capacity.
  5. Dashboards sliced by tenant, so when latency moves you can see whose traffic moved it in seconds.

Data residency and the escape hatch

Some tenants can't be pooled. A contract says their data lives in a specific place, or on hardware they own, or on a network with no outside connection at all. If tenancy is baked in properly, moving one tenant to a dedicated database or a dedicated deployment is an operational task: provision, migrate that tenant's rows, update the routing table. The application doesn't notice, because it never knew which model the tenant was on.

That's the real payoff of doing this early. On-prem and air-gapped deployments become "the same platform, configured for one tenant" rather than a fork.

Migrations across many tenants

Shared tables make schema migrations simple: run once. What's not simple is data migrations, backfills and anything that touches every tenant's rows. Rules that hold up:

  • Migrations run as a separate database role that bypasses RLS on purpose, and only that role can.
  • Backfills run tenant by tenant, with progress recorded, so a failure on tenant seven doesn't mean starting over, and one huge tenant doesn't hold a lock over everyone.
  • Every migration is tested against a fixture with at least two tenants. A surprising number of bugs only exist when there's a second tenant in the table.

Proving it, not just believing it

Every rule above is a claim. Claims about isolation need evidence, because the person asking for it is usually a customer's security reviewer, and "we're careful" is not an answer they accept.

Keep three kinds of proof running all the time:

  1. Cross-tenant tests in CI. For every API endpoint, a test creates data as tenant A, then calls the endpoint as tenant B and asserts nothing comes back. New endpoints get the test for free through a shared fixture, so nobody has to remember.
  2. A canary tenant in production. A synthetic tenant with planted documents containing unique marker strings. A scheduled job asks questions as every real tenant's test user and alerts if a marker ever appears in an answer. Ideally it never fires. It should still run every hour.
  3. Audit trails with the tenant on both ends. Every read of a document records who asked, on behalf of which tenant, and which tenant owns the row. A mismatch is an alert, not a log line.

The canary is the one reviewers like most, because it tests the whole system the way a user would experience a leak, rather than any one layer.

What retrofitting costs

Retrofits like this tend to look the same: an audit of every query, every cache key, every job and every log line; a long tail of "we think this one is fine"; a freeze on features while it happened; and at least one incident found in production rather than in review. It can take most of a year of someone senior's time.

Against that, the first-week version is small: a context variable, a middleware, an RLS policy per table, a key helper, a config record, and a lint rule or two. Most of it is boring, which is the point.

What I'd do differently

Write the two-tenant test fixture on day one. Plenty of bugs only show up with a second tenant present. Every test should run with at least two.

Put tenant budgets on inference from the start. It's common to have rate limits on the API long before budgets on model calls. On an AI platform, the model is the shared resource most likely to be exhausted by one tenant.

Make the tenant visible in every log line and trace by default. Leave it late and the first few incidents take longer than they should, because nobody can immediately see whose traffic it was.

Decide residency rules before the first regulated tenant asks. Otherwise the routing table gets designed under deadline pressure, when it could have been a calm afternoon months earlier.

The short version

Multi-tenancy is a property of the whole system, not a column. Resolve the tenant once from something the caller can't forge. Let the database refuse cross-tenant queries. Put the tenant in every key, path and log line. Vary behaviour through configuration, never code. Give every tenant its own budget for the expensive things. And do all of it before you need it, because the week it costs at the start is the cheapest week you will ever spend on it.