Lesson 34 of 59Identity and access
Multi-Tenant SaaS Backends
Isolate customer data in a SaaS backend: pick a tenancy model, resolve the tenant safely, filter every query automatically, and back it up with Postgres RLS.
A support ticket arrives on a Friday: "When I download invoice 4812 I get a PDF with another company's name on it." Your product is a B2B SaaS app. Every customer company, called a tenant, shares the same API and the same database, and one endpoint added last sprint forgot a WHERE tenant_id = .... That is a data breach, with a disclosure process, not a bug you hotfix and forget. Multi-tenancy is the design work that makes this mistake hard to make and easy to catch. This lesson covers the three isolation models, how to resolve the tenant on each request, how to make SQLAlchemy add the filter for you, and how Postgres Row-Level Security catches what the app misses.
Three ways to isolate tenants
Every SaaS backend picks one of three models, or a mix of them. The trade-offs are about isolation, cost and how much work each schema change becomes.
Shared schema (tenant_id column) | Schema per tenant | Database per tenant | |
|---|---|---|---|
| Isolation | Logical only. One missing filter leaks | Better. Queries resolve tables through search_path | Strongest. Separate credentials, backups, even regions |
| Cost per tenant | Near zero | Low, but catalogue bloat at thousands of schemas | Highest. A database (or cluster) each |
| Migrations | Run once | Run N times, and some tenants fail halfway | Run N times across N servers |
| Noisy neighbours | One big tenant slows everyone | Same server, same problem | Isolated |
| Compliance asks ("our data in the EU, our own keys") | Hard | Hard | Easy |
| Onboarding a tenant | Insert a row | Create a schema, run migrations | Provision a database |
The shared schema is the default for most SaaS products, and it is what the rest of this lesson builds. It scales to hundreds of thousands of small tenants, migrations happen once, and cross-tenant reporting is a plain GROUP BY. Its weakness is that isolation is only as good as your discipline, so you add layers of enforcement.
Schema per tenant sounds like a middle ground, and in Postgres you switch with SET search_path TO tenant_42. In practice it combines the costs of both. Alembic has to loop over every schema, connection pools hold search_path state, and Postgres slows down at catalogue level once you have tens of thousands of schemas. Teams that pick it usually regret it at scale.
Database per tenant is what enterprise customers pay for: their own encryption keys, their own region, a backup they can restore alone. Mature products often run a hybrid. Most tenants share a pooled database, and a few large or regulated ones live in dedicated "silo" databases. The application code stays the same either way. Only the routing changes, which is why you design for the shared model with a clean tenant boundary from day one.
Resolving the tenant on each request
Before any query runs, the request has to answer one question: which tenant is this? There are four common sources.
- Subdomain:
acme.yourapp.com. Clean for browser apps and white-labelling, and it needs wildcard DNS and TLS. - Path:
/orgs/acme/projects. Explicit, easy to cache and log, and common in public APIs. - Header:
X-Org-Id: 42. Common for internal APIs and for users who belong to several organisations and switch between them. - Token claim: an
org_idclaim in the access token, issued by your identity provider at login. You cannot spoof it without forging the token.
The rule that matters: a tenant id from the URL or a header is a claim, not a fact. A user can type any subdomain or header they like. You must check that the authenticated user is a member of that tenant before you trust it. A token claim is already trusted, because your identity provider signed it.
from contextvars import ContextVar
from typing import Annotated
from uuid import UUID
from fastapi import Depends, Header, HTTPException
from app.auth import CurrentUser
from app.db import SessionDep
from app.memberships import get_membership
current_tenant: ContextVar[UUID | None] = ContextVar("current_tenant", default=None)
async def resolve_tenant(
user: CurrentUser,
session: SessionDep,
x_org_id: Annotated[UUID, Header()],
) -> UUID:
membership = await get_membership(session, user_id=user.id, org_id=x_org_id)
if membership is None:
raise HTTPException(status_code=404, detail="Organisation not found")
current_tenant.set(x_org_id)
return x_org_id
TenantId = Annotated[UUID, Depends(resolve_tenant)]Two details are deliberate. The failure is a 404, not a 403, so an attacker cannot use the API to discover which organisation ids exist. And the tenant goes into a ContextVar. Each asyncio task gets its own copy of the context, and FastAPI runs each request in its own task, so the value set by one request never leaks into a concurrent one. It also follows the request into def routes running in the threadpool, because Starlette copies the context when it hands work to a thread. A module-level global would be shared by every request on the process. One trap: keep resolve_tenant an async def. A plain def dependency runs in a worker thread on a copy of the context, so a value it sets is gone by the time your route runs.
The org id in the header is only a claim. Anyone can send any value.
Making the filter automatic
Writing .where(Model.tenant_id == tenant) in every query works until the day someone forgets. SQLAlchemy can add it for you. The do_orm_execute session event runs before every ORM statement, and with_loader_criteria attaches an extra WHERE to every entity that matches a class, including lazy loads of relationships.
from uuid import UUID
from sqlalchemy import event
from sqlalchemy.orm import Mapped, ORMExecuteState, Session, mapped_column, with_loader_criteria
from app.tenancy import current_tenant
def tenant_from_context():
tenant_id = current_tenant.get()
if tenant_id is None:
raise LookupError("no tenant set for this request")
return tenant_id
class TenantScoped:
"""Mixin for every table that belongs to a tenant."""
tenant_id: Mapped[UUID] = mapped_column(index=True, default=tenant_from_context)
@event.listens_for(Session, "do_orm_execute")
def add_tenant_criteria(state: ORMExecuteState) -> None:
if state.is_column_load or state.is_relationship_load:
return # the criteria already travel with the parent query
if state.execution_options.get("all_tenants"):
return # explicit opt-out for admin jobs, easy to grep for
if state.is_select or state.is_update or state.is_delete:
tenant_id = tenant_from_context()
state.statement = state.statement.options(
with_loader_criteria(TenantScoped, lambda cls: cls.tenant_id == tenant_id, include_aliases=True)
)This covers ORM select(), session.get(), relationship lazy loads, and ORM-enabled update() and delete(). The column default fills tenant_id on insert from the same context. If no tenant is set, the code raises instead of silently returning everything, which is the property you want: fail closed.
It does not cover raw text() SQL, Core statements run on a plain connection, or anything outside SQLAlchemy, such as a reporting script. That is why you still need a database-level layer.
Two schema habits complete the picture. Make uniqueness per tenant, with UniqueConstraint("tenant_id", "slug"), because two companies can both have a project called web. And use composite foreign keys for child tables: if tasks references projects (tenant_id, id) instead of just projects (id), the database itself refuses a task in tenant A that points at a project in tenant B. An API that accepts a project_id in the body is otherwise an easy way to attach your data to someone else's records.
Row-Level Security as the safety net
Postgres Row-Level Security (RLS) lets the database filter rows by a policy, whatever SQL the app sends. You tell Postgres the tenant for each transaction, and a policy compares it with the row:
ALTER TABLE invoices ENABLE ROW LEVEL SECURITY;
ALTER TABLE invoices FORCE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON invoices
USING (tenant_id = NULLIF(current_setting('app.tenant_id', true), '')::uuid)
WITH CHECK (tenant_id = NULLIF(current_setting('app.tenant_id', true), '')::uuid);USING filters the rows a statement can see, update or delete. WITH CHECK rejects inserts and updates that would write a row for another tenant, with new row violates row-level security policy. The true argument to current_setting returns NULL instead of an error when the setting is missing, so a request with no tenant sees zero rows. The NULLIF(..., '') is there because once a session has set a custom setting, it reads back as an empty string rather than NULL, and ''::uuid is an error.
The app then sets the tenant at the start of every transaction:
from sqlalchemy import event, text
from sqlalchemy.orm import Session
from app.tenancy import current_tenant
@event.listens_for(Session, "after_begin")
def set_tenant_for_rls(session, transaction, connection) -> None:
tenant_id = current_tenant.get()
if tenant_id is not None:
connection.execute(
text("SELECT set_config('app.tenant_id', :tenant, true)"),
{"tenant": str(tenant_id)},
)The third argument true makes it transaction-local, the same as SET LOCAL. That choice matters with connection pools. A plain session-level SET stays on the connection after it goes back to the pool, so the next request that borrows it inherits the previous tenant. With PgBouncer in transaction mode it is worse: consecutive transactions from one client can land on different server connections, so session state is unreliable anyway. Transaction-local settings start and end with the transaction, which is exactly the unit PgBouncer hands out.
The traps that silently disable RLS:
- Table owners bypass RLS unless you add
FORCE ROW LEVEL SECURITY. If your app connects as the role that ran the migrations, the policies do nothing. - Superusers and roles with
BYPASSRLSalways bypass it. Your app role must have neither. - Policies only apply to tables you enabled it on. A new table added next quarter needs its own migration. Add a CI check that lists tables with a
tenant_idcolumn wherepg_class.relrowsecurityis false.
The clean setup is two roles: a migration role that owns the tables, and an app role with only SELECT, INSERT, UPDATE and DELETE grants. RLS costs a little planning work per query and makes some plans worse, so keep tenant_id leading in your indexes. It is defence in depth, not a reason to drop the ORM filter.
Everything else that must carry the tenant
The database is only one place where tenants mix. Anything that stores or shares state across requests needs the tenant in it.
- Cache keys:
tenant:{id}:dashboard:{user}, neverdashboard:{user}. A cache keyed without the tenant is a cross-tenant leak that no SQL policy can catch. - Background jobs: a task enqueued during a request runs later in a worker with no request context. Pass
tenant_idas an explicit task argument, and set theContextVarat the start of the task, so the same filters and RLS apply in workers. - Object storage: prefix keys with the tenant (
tenants/{id}/exports/...) so a lifecycle rule, an export or a deletion can target one tenant. - Rate limits and quotas: limit per tenant as well as per user, so one customer's runaway integration cannot starve the others. Track usage per tenant for billing.
- Feature flags: target flags by tenant for betas and enterprise-only features.
- Logs and traces: put
tenant_idon every log line and span. When the big customer says "it is slow for us", you need to filter by them.
Indexes need care too. In a shared schema almost every query filters by tenant, so tenant_id should lead your composite indexes: (tenant_id, created_at) rather than (created_at). For very large tables, Postgres declarative partitioning by tenant_id (hash or list) keeps each tenant's rows together and lets you detach one tenant's partition.
Match each place to the way it must include the tenant.
Export, deletion and moving a big tenant
Tenants leave, and regulators give them rights. Under GDPR a customer can ask for an export of their data or its deletion. In a shared schema this is a sweep over every table with a tenant_id, plus caches, object storage, search indexes, backups and any third-party processors. That is one more reason for the column to exist on every tenant-owned table, even child tables that could find their tenant through a join.
Eventually one tenant grows big enough to hurt everyone else, or signs a contract that requires its own database. Moving it is much easier if you planned for it:
- Use UUIDs or other globally unique ids for tenant-owned rows. Copying rows with sequence ids into another database collides with the ids already there.
- Keep a routing table (
tenant_id → database URL) and look it up when you resolve the tenant. On day one every row points at the shared database. - Move with replication, not a long pause. Copy the tenant's rows to the new database, keep them in sync (logical replication or change data capture), then briefly freeze writes for that tenant, flip the routing entry, and delete the old rows.
Testing for cross-tenant leaks
The one test every multi-tenant API needs: as tenant A, try to reach every resource that belongs to tenant B, through every endpoint, and expect nothing. Here is the idea with plain SQLite. One handler forgot its filter, and the check finds it:
Press Run (⌘ Enter) to see what happens.Both tenants can own an INV-001 because uniqueness is per tenant. download_pdf leaks invoice 3. And outside a request, the code fails closed instead of returning every tenant's rows.
In a real FastAPI suite, the same idea becomes a parametrised test over your routes, run against a real Postgres with RLS enabled:
import pytest
ROUTES = [
("GET", "/invoices/{invoice_id}"),
("GET", "/invoices/{invoice_id}/pdf"),
("PATCH", "/invoices/{invoice_id}"),
("DELETE", "/invoices/{invoice_id}"),
]
@pytest.mark.parametrize(("method", "path"), ROUTES)
async def test_tenant_a_cannot_touch_tenant_b(client, tenant_a_headers, invoice_of_tenant_b, method, path):
url = path.format(invoice_id=invoice_of_tenant_b.id)
response = await client.request(method, url, headers=tenant_a_headers, json={})
assert response.status_code == 404Generate ROUTES from app.routes instead of a hand-written list, and fail the test when a new route with an id parameter is not covered. Then the test grows with the API.
Run after the block above. What does this print?
token = current_tenant.set(2)
print(len(search("INV-001")), get_invoice(1))
current_tenant.reset(token)
print(current_tenant.get())Put the steps of a tenant-scoped request in order.
- Tap the steps below in the right order.
- tenant
- One customer organisation in a SaaS product. Its users and data must be invisible to every other tenant.
- shared schema
- All tenants in the same tables, separated by a tenant_id column. Cheapest model, weakest isolation by itself.
- ContextVar
- A variable with a separate value per asyncio task or copied context, used to hold the current request's tenant.
- with_loader_criteria
- A SQLAlchemy option that adds a WHERE condition to every query and lazy load of matching entities.
- Row-Level Security
- A Postgres feature where policies filter which rows each statement can read or write.
- FORCE ROW LEVEL SECURITY
- Makes RLS apply to the table owner too. Without it, an app connecting as the owner bypasses the policies.
- noisy neighbour
- A tenant whose load slows down others on shared infrastructure.