← Back to PostgreSQL, page 5

postgresql-0092 · Hard senior

Choose between a shared table with tenant_id, a schema per tenant and a database per tenant for a B2B SaaS on PostgreSQL.

A shared schema with a tenant_id column on every table scales to many tenants with one set of migrations and pooled connections, and row-level security can enforce isolation. Schema per tenant gives stronger separation and easy per-tenant export but makes migrations and catalogs heavy beyond a few thousand tenants. Database per tenant isolates most strongly, suits a few large or regulated customers, and costs the most to operate. Many products mix them: shared by default, dedicated for large customers.

Full answer

Compare on the dimensions that decide it:

ConcernShared tables + tenant_idSchema per tenantDatabase per tenant
Tenant count it handles wellUp to millionsHundreds to low thousandsTens to hundreds
IsolationLogical (RLS, app checks)Namespace levelStrong, separate catalogs
MigrationsOne runOne run per schemaOne run per database
Connection poolingOne poolOne pool, search_path per tenantPool per database
Cross-tenant analyticsSimple queriesUNION across schemasSeparate pipeline
Per-tenant restore or deleteHarder (filtered)Drop or dump a schemaDrop or dump a database
Noisy neighboursShared resourcesShared resourcesCan be placed on separate servers

Design details for the shared model: put tenant_id first in composite primary keys and indexes, include it in every foreign key so rows cannot point across tenants, enforce it with RLS and SET LOCAL per transaction, and plan to shard by tenant_id later (for example with Citus) if one server is not enough.

Decide by tenant count, size skew, compliance needs (data residency, dedicated hardware) and team capacity for operations. This is a design item with nothing to run.

Key points

  • Shared tables scale to many tenants
  • Schemas give middle-ground isolation
  • Databases isolate strongly but cost most
  • Lead indexes and keys with tenant_id
  • Hybrid models are common

Common mistakes

  • Schema per tenant with tens of thousands of tenants
  • Shared tables without tenant_id in foreign keys

Follow-ups

  • How would you move one large tenant to its own database?
  • How does Citus distribute by tenant?

Tips

  • Compare along fixed dimensions