← Back to SQL, page 16

sql-0319 · Hard senior

What are the main ways to design a database for a multi-tenant SaaS product, and their trade-offs?

Options are a shared schema with a tenant_id column on every table, a separate schema per tenant, or a separate database per tenant. Shared tables are cheapest and simplest to operate but need strict tenant filtering, ideally enforced with row-level security. Separate schemas or databases isolate data and noisy neighbours better but multiply migrations and connections.

Full answer

Shared schema, tenant_id everywhere:

  • One set of tables and migrations; efficient for thousands of small tenants.
  • Every query must filter by tenant. PostgreSQL row-level security (CREATE POLICY ... USING (tenant_id = current_setting('app.tenant')::int)) makes forgetting impossible.
  • Composite keys and indexes lead with tenant_id, such as (tenant_id, created_at).

Schema per tenant:

  • Stronger separation and easy per-tenant export, but migrations must run N times and catalog size grows.

Database per tenant:

  • Strongest isolation, per-tenant backups and data residency, but connection pooling, upgrades and cross-tenant reporting get hard.

Many products mix them: shared tables for most tenants, dedicated databases for a few large or regulated ones. Whatever the choice, test that one tenant cannot read another's data.

Key points

  • Shared tables with tenant_id are cheapest
  • Row-level security enforces tenant filters
  • Schema or database per tenant improves isolation
  • Isolation costs more operational work
  • Hybrid models are common

Common mistakes

  • Relying on every developer to remember WHERE tenant_id = ?
  • Indexes that do not lead with tenant_id in shared tables

Follow-ups

  • How does row-level security work in PostgreSQL?
  • How would you move a large tenant to its own database?

Tips

  • Compare the three options on cost and isolation