How to Design Multi-Tenant Database Schemas
Choose a multi-tenant data model: shared tables with a tenant key, schema-per-tenant, or database-per-tenant, and enforce tenant isolation.
On this page
Introduction
A multi-tenant application stores data for many customers in shared infrastructure. How that data is isolated is one of the earliest and most consequential schema decisions, because it shapes queries, indexes, migrations, backups, and the blast radius of a bug. The three common models — shared tables with a tenant key, a schema per tenant, and a database per tenant — offer different trade-offs between isolation, operational cost, and scale.
This tutorial walks through the three models, how to design a shared schema correctly with the tenant key everywhere, how to enforce isolation in depth so a missing filter cannot leak data, and how to test cross-tenant access. The examples use PostgreSQL, but the models and the enforcement reasoning apply to any relational database.
Choose the isolation model
Shared tables with a tenant key put every tenant’s rows in the same tables, distinguished by a tenant_id column. This is the simplest to operate: one schema to migrate, one set of indexes, and connections that can serve any tenant. Its risk is a missing filter leaking data, and its limit is that a very large tenant’s data lives beside everyone else’s. It is the right starting point for most SaaS.
Schema per tenant gives each tenant its own tables within one database, which gives stronger logical isolation and lets a tenant be moved or backed up separately, at the cost of many schemas to migrate and a connection that must switch schema. Database per tenant gives the strongest isolation, including separate credentials and resource limits, and the highest operational cost, which suits a small number of large or compliance-bound tenants. Choose the model from isolation needs and tenant count, and expect to mix models over time.
-- shared model: tenant key on every table
CREATE TABLE projects (
id bigint GENERATED ALWAYS AS IDENTITY,
tenant_id bigint NOT NULL,
name text NOT NULL,
PRIMARY KEY (id),
UNIQUE (tenant_id, name)
);
CREATE INDEX idx_projects_tenant ON projects (tenant_id);
Put the tenant key everywhere
In the shared model the tenant key must appear on every table that holds tenant data, including join tables and child tables. A child table can carry the tenant key directly or reach it through its parent, but carrying it directly makes every query and constraint tenant-aware without a join. Include the tenant key in primary and unique constraints so uniqueness is per tenant, not global, which is essential: two tenants may both have a project named ‘default’.
Lead indexes with the tenant key so the common query, which filters one tenant, reads a compact slice of the index. A composite index on (tenant_id, created_at) serves both the tenant filter and the sort. Because most queries touch one tenant, an index that starts with tenant_id is far more selective than one that does not, and it keeps a large table manageable by letting the planner seek to one tenant’s range.
CREATE TABLE project_files (
id bigint GENERATED ALWAYS AS IDENTITY,
tenant_id bigint NOT NULL,
project_id bigint NOT NULL,
path text NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (project_id) REFERENCES projects (id),
UNIQUE (tenant_id, project_id, path)
);
CREATE INDEX idx_project_files_tenant_project ON project_files (tenant_id, project_id);
Enforce isolation in depth
Application code that must remember to add a tenant filter on every query will eventually miss one. Add a defense in depth so a missing filter cannot leak data. Row-level security lets the database enforce a predicate automatically: enable it on each table and add a policy that restricts rows to the current tenant, set as a session variable. Then even a query without a tenant predicate can only see the current tenant’s rows.
Pair row-level security with a data-access layer that sets the tenant for each request and never exposes an unscoped query. For a small number of privileged operations such as an admin dashboard, use a role that bypasses the policy deliberately. The principle is that the default is isolated, and crossing tenants requires an explicit, auditable action rather than being the accidental result of an omitted WHERE clause.
ALTER TABLE projects ENABLE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON projects
USING (tenant_id = current_setting('app.tenant_id')::bigint);
-- each request sets the tenant for its session
SET app.tenant_id = '42';
Handle migrations and shared resources
In the shared model one migration touches all tenants at once, which is simple but means a long migration affects everyone. Run migrations with the online patterns: add columns nullable, backfill in batches, add constraints later. In the schema-per-tenant model the same migration must run per schema, so script it to iterate schemas and track which have been migrated; the risk is a tenant left behind.
Decide where shared data lives. Reference data such as countries or plan definitions is often global, not per tenant, so keep it in a separate schema or table without the tenant key and reference it from tenant tables. Be explicit about which tables are global and which are tenant-scoped, because a global table mistakenly given a tenant key fragments what should be one shared set.
Test cross-tenant isolation
Add tests that attempt to read and write another tenant’s rows through every path: a normal query, a query by primary key, a join, and an update. With row-level security enabled and the session set to tenant A, assert that selecting a row belonging to tenant B returns nothing and that updating it affects zero rows. Then attempt the same through the application layer. This is the test that catches the missing filter before a customer does.
psql -d app <<'SQL'
SET app.tenant_id = '1';
SELECT count(*) FROM projects WHERE tenant_id = 2; -- expect 0 (RLS blocks it)
UPDATE projects SET name = 'x' WHERE tenant_id = 2; -- expect UPDATE 0
SQL
Common pitfalls
Putting the tenant key on parent tables but not child or join tables, making unique constraints global instead of per tenant, relying on developers to remember the filter, leading indexes with something other than the tenant key, and running a schema-per-tenant migration without tracking which schemas are done are the recurring mistakes. A tenant key everywhere, tenant-aware constraints, row-level security, tenant-leading indexes, and tracked migrations address them.
Conclusion
A multi-tenant schema is an isolation decision. Start with shared tables and a tenant key, put that key on every tenant table and into every unique constraint, lead indexes with it, and enforce isolation with row-level security so a forgotten filter cannot leak data. Self-check by attempting to read and write another tenant’s rows and asserting every path is denied. When isolation is enforced by the database, a bug in application code is a returned empty set instead of a data breach.
Sources: PostgreSQL: Row security policies, PostgreSQL: Multitenancy considerations, Microsoft Azure: Multitenant SaaS patterns.
FAQ
- Which model should a new SaaS start with?
- Shared tables with a tenant key, because it is the simplest to operate and migrate from. Move a large or isolation-sensitive tenant to its own database later if needed, which is easier than starting from the most isolated model and needing to consolidate.
- How do I prevent a forgotten tenant filter?
- Use row-level security policies or a data-access layer that always injects the tenant scope, so a query without an explicit tenant predicate is impossible or returns nothing. Relying on every developer to remember the filter is the failure mode.
Report a problem with this articleOpens a pre-filled issue on GitHub.