← Back to FastAPI, page 5

fastapi-0092 · Hard senior

How would you implement multi-tenancy in FastAPI with per-tenant database routing, and what are the isolation trade-offs?

Resolve the tenant early (subdomain, header or token claim), validate it against a registry, and give each request a session bound to that tenant's database through a dependency. Options are database per tenant, schema per tenant (schema_translate_map), or shared tables with a tenant_id column enforced by row-level security. The more isolated the model, the higher the operational cost: connection pools, migrations and monitoring multiply per tenant.

Full answer

Models:

  1. Shared tables with tenant_id: cheapest, easiest to scale to thousands of tenants. Risk: one missing WHERE tenant_id leaks data. Mitigate with a base query helper, PostgreSQL Row-Level Security (SET app.tenant = ... per transaction), and tests.
  2. Schema per tenant (PostgreSQL): one database, separate schemas; use execution_options(schema_translate_map={None: tenant_schema}) per connection. Moderate isolation; migrations must run for every schema.
  3. Database per tenant: strongest isolation, per-tenant backup/restore, noisy-neighbour control, data residency. Costs: many pools and connections, migrations across all databases, onboarding automation.

Routing in FastAPI:

  • Resolve the tenant in a dependency (or pure ASGI middleware) from the subdomain, a header (only if trusted), or a verified JWT claim. Never trust a header the client can set freely when authenticated identity already implies the tenant. Check that the authenticated user belongs to that tenant.
  • Keep a registry (database table or config) mapping tenant to connection URL, and a bounded cache of engines: create engines lazily, evict least-recently-used ones (engine.dispose()), and cap the total number of open connections (pool_size times active tenants).
  • Dependency yields a Session bound to the tenant engine; unknown tenants give 404, suspended ones 403.
  • Set a ContextVar with the tenant for logging and metrics labels; include tenant in cache keys and background job payloads so workers route correctly.
  • Migrations: Alembic needs a loop over tenants with progress tracking and failure handling; version tenants independently or force lockstep.
  • Test cross-tenant leaks explicitly: create data in tenant A, assert tenant B cannot see or fetch it by ID.

Operational: per-tenant rate limits and quotas, backups, observability dimensions, and an admin path with explicit audit trails for support access.

python
import tempfile
from pathlib import Path
from typing import Annotated

from fastapi import Depends, FastAPI, Header, HTTPException
from fastapi.testclient import TestClient
from sqlalchemy import create_engine, select
from sqlalchemy.orm import DeclarativeBase, Mapped, Session, mapped_column

root = Path(tempfile.mkdtemp())
REGISTRY = {"acme": root / "acme.db", "globex": root / "globex.db"}       # tenant -> database (a table in real systems)
engines: dict = {}


class Base(DeclarativeBase):
    pass


class Note(Base):
    __tablename__ = "note"
    id: Mapped[int] = mapped_column(primary_key=True)
    text: Mapped[str]


def engine_for(tenant: str):
    if tenant not in REGISTRY:
        raise HTTPException(status_code=404, detail="Unknown tenant")
    if tenant not in engines:                                      # lazy; evict least-recently-used in real code
        engines[tenant] = create_engine(f"sqlite:///{REGISTRY[tenant]}")
        Base.metadata.create_all(engines[tenant])
    return engines[tenant]


def tenant_session(x_tenant: Annotated[str, Header()]):
    with Session(engine_for(x_tenant)) as db:
        yield db


app = FastAPI()


@app.post("/notes", status_code=201)
def add(text: str, db: Annotated[Session, Depends(tenant_session)]):
    db.add(Note(text=text))
    db.commit()
    return {"saved": text}


@app.get("/notes")
def listing(db: Annotated[Session, Depends(tenant_session)]):
    return list(db.scalars(select(Note.text)))


c = TestClient(app)
c.post("/notes", params={"text": "acme budget"}, headers={"X-Tenant": "acme"})
c.post("/notes", params={"text": "globex roadmap"}, headers={"X-Tenant": "globex"})
print("acme sees:", c.get("/notes", headers={"X-Tenant": "acme"}).json())
print("globex sees:", c.get("/notes", headers={"X-Tenant": "globex"}).json())
print("unknown tenant:", c.get("/notes", headers={"X-Tenant": "evilcorp"}).status_code)
print("missing header:", c.get("/notes").status_code)
print("databases on disk:", sorted(p.name for p in root.iterdir()))

Standalone script. Run it with `python file.py`; it uses temporary SQLite files and TestClient. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): acme sees: ['acme budget'] globex sees: ['globex roadmap'] unknown tenant: 404 missing header: 422 databases on disk: ['acme.db', 'globex.db']

Key points

  • Choose isolation: tenant_id column, schema per tenant or database per tenant
  • Resolve tenant early and verify the user belongs to it
  • Lazy, bounded cache of engines; dispose evicted ones
  • Migrations and pools multiply with isolation level
  • Test cross-tenant access explicitly

Common mistakes

  • Trusting a client-supplied tenant header without verifying membership
  • Forgetting a tenant filter in one query in shared-table designs
  • Unbounded engine caches that exhaust database connections
  • Cache keys and background jobs without the tenant
  • No automated cross-tenant leak tests

Follow-ups

  • How does PostgreSQL row-level security help?
  • How do you run Alembic across all tenants?
  • How do you onboard a new tenant database?

Tips

  • Compare the three isolation models
  • Show tenant resolution
  • Mention bounded engine caches