Format
Deep Engineering
Written for
For engineers and technical leads
Thread
SaaS Architecture and Business Logic
SaaS Engineering

Shared Schema, Schema per Tenant or Database per Tenant: Choosing a Multi-Tenancy Model

Every multi-tenant system must answer one question: when tenant A's query runs, what physically stops it reading tenant B's rows? The three common models answer it differently, and the answer shapes everything else.

Khalid Aboubakr
9 min read
Under the HoodSaasMulti-tenancyDatabase

When tenant A's query runs, what physically stops it from reading tenant B's rows? Every multi-tenant SaaS architecture has an answer to that question, whether or not anyone wrote it down. In a shared schema, the answer is a WHERE clause and, ideally, a database policy behind it. In a schema per tenant, it is the search path the connection was given. In a database per tenant, it is a separate database, often a separate set of credentials. Each answer brings a different profile of cost, operational effort and failure modes, and the choice is far easier to make at the start than to change after the hundredth customer.

Three models, and what isolates tenants in each

AWS's SaaS Lens describes the spectrum as silo, pool and bridge: dedicated resources per tenant, shared resources for all tenants, and a mix of the two. At the data layer, those map onto three concrete designs.

Shared schema (pool)Schema per tenantDatabase per tenant (silo)
What isolates tenantstenant_id filters, row-level securitySeparate schema, connection search pathSeparate database and credentials
Cost per additional tenantClose to zeroLowA real floor per tenant
Schema migrationsOnceOnce per tenantOnce per tenant, across many databases
Restore one tenant to yesterdayHard: extract rows from a full backupPossible: dump and restore one schemaStraightforward
Noisy neighboursShared everythingShared server resourcesIsolated, if databases are on separate resources
Cross-tenant reportingA queryA union across schemasA data pipeline

None of these is universally right. A product with thousands of small tenants on a self-service plan has very different needs from one with forty enterprise customers whose contracts mention data residency and per-customer restore. Microsoft's guidance on multitenant data storage makes the same point, and adds that higher tenant density increases noisy-neighbour risk, so the choice is a trade between cost and isolation rather than a search for the best design.

Shared schema: cheap, dense, and only as safe as its weakest query

In the shared model, every tenant-owned table has a tenant_id column and every query filters on it. That is the cheapest model to run and the simplest to migrate, and it scales to very large numbers of tenants. Its weakness is that isolation depends on every query in the codebase being correct. One forgotten filter in a report, an export or an admin endpoint is a cross-tenant data leak.

Two techniques make the shared schema much safer than its reputation suggests. The first is to make the tenant part of every key, so the database refuses references across tenants:

CREATE TABLE projects ( tenant_id uuid NOT NULL REFERENCES tenants (id), id uuid NOT NULL DEFAULT gen_random_uuid(), name text NOT NULL, PRIMARY KEY (tenant_id, id) ); CREATE TABLE tasks ( tenant_id uuid NOT NULL, id uuid NOT NULL DEFAULT gen_random_uuid(), project_id uuid NOT NULL, title text NOT NULL, PRIMARY KEY (tenant_id, id), FOREIGN KEY (tenant_id, project_id) REFERENCES projects (tenant_id, id) );

With a composite foreign key, a task in tenant A cannot point at a project in tenant B, even if application code tries. Leading every primary key and index with tenant_id also keeps per-tenant queries efficient and makes later partitioning or sharding by tenant a natural step.

The second technique is PostgreSQL row-level security as a backstop behind the application's own filters:

ALTER TABLE tasks ENABLE ROW LEVEL SECURITY; ALTER TABLE tasks FORCE ROW LEVEL SECURITY; CREATE POLICY tenant_isolation ON tasks USING (tenant_id = NULLIF(current_setting('app.tenant_id', true), '')::uuid) WITH CHECK (tenant_id = NULLIF(current_setting('app.tenant_id', true), '')::uuid);
-- At the start of every request's transaction, with the tenant from the authenticated session BEGIN; SELECT set_config('app.tenant_id', $1, true); -- true = local to this transaction -- ... the request's queries ... COMMIT;

The details here are where implementations go wrong. The PostgreSQL documentation is explicit that superusers and roles with BYPASSRLS always bypass row security, and that table owners bypass it too unless the table is set to FORCE ROW LEVEL SECURITY. If the application connects as the role that owns the tables, which is common when migrations and the app share credentials, the policies do nothing until you force them; better still, run the application as a separate role that owns nothing. Views deserve the same scrutiny: by default a view queries its tables with the view owner's rights, so a view owned by a role that bypasses row security, such as a superuser or the table owner on a table without FORCE, returns every tenant's rows unless it is created with security_invoker (PostgreSQL 15 and later). Setting the tenant with set_config(..., true) scopes it to the transaction, which matters with transaction-level connection pooling, where the next transaction on the same connection may belong to a different tenant. And the NULLIF guard handles a quiet trap: once a custom setting has been set in a session, even transaction-locally, it reads back as an empty string rather than null after that transaction ends, and casting an empty string to uuid raises an error. With the guard, a query that runs without a tenant matches nothing instead of failing with a confusing cast error. With these in place, a missing tenant context returns no rows, which is the failure you want.

Row-level security is a safety net, not the authorisation model. The application still decides which users may act within a tenant; the policy only guarantees that a bug cannot cross the tenant boundary.

Schema per tenant: real separation with operational drag

Giving each tenant its own schema in one database gives clearer separation: tables are physically distinct, a tenant can be dumped and restored on its own, and a query that forgets a filter can only see the current schema. The connection selects the tenant by setting the search_path, and the same pooling caution applies: the setting must be applied per transaction or reset reliably, or a pooled connection will carry one tenant's path into another's request.

The costs show up in operations. Every migration runs once per schema, so a release with a schema change becomes a loop over every tenant, and a failure halfway through leaves tenants on different versions of the schema at the same time. The application must tolerate that state, or the deployment process must be able to stop, report and resume. The database catalogue also grows with every tenant's tables, indexes and sequences, and tools that walk the catalogue, from backup utilities to migration frameworks, slow down as it grows. With hundreds of tenants this is usually manageable; with tens of thousands, the catalogue and the migration loop become a project of their own.

Database per tenant: the strongest isolation, priced per tenant

Separate databases give the strongest boundary short of separate infrastructure. Credentials can differ per tenant, so a leaked connection string exposes one customer. A tenant can be restored to a point in time without touching anyone else. Data can be placed in a specific region to meet a residency requirement. Encryption keys can be per tenant. A heavy tenant can be moved to its own server without changing the application.

Each of those benefits is paid for. Every database needs connections, and connection pools are per database, so the total connection count grows with tenants rather than with traffic. Migrations become fleet orchestration across many databases, with the same partial-failure problem as schema-per-tenant at a larger scale. Onboarding a tenant means provisioning a database, which must be automated and monitored. Anything that looks across tenants, such as product analytics, billing usage or support search, needs a pipeline that copies data out into a shared store. And there is a cost floor per tenant that makes a free tier or a low-priced plan hard to sustain.

Choosing a multi-tenant SaaS architecture: the questions that settle it

The model usually chooses itself once a few questions are answered honestly.

How many tenants do you expect, and how unequal are they? Thousands of small tenants point strongly to a shared schema. A few dozen large ones make dedicated databases affordable.

What do contracts and regulation require? If customers will ask for data in a specific country, per-tenant encryption keys or proof of physical separation, a shared schema can still be acceptable, but you will need to argue it each time. Obligations depend on jurisdiction and on the contracts you sign, so they are worth confirming with counsel before the architecture assumes them.

Do you need to restore one tenant without affecting others? This requirement is often discovered after the first support incident in which one customer deletes their own data. It is cheap in silo models and expensive in a pool.

How much cross-tenant querying does the business need? Internal analytics, usage-based billing and support tools are trivial in a shared schema and require real engineering in a silo.

What can your team operate? A model that needs fleet-wide migration tooling, per-tenant monitoring and automated provisioning is only viable if someone will build and run those things.

For many products, the answer is a bridge: a shared schema by default, with the option to move a large or regulated tenant into a dedicated database. That option is only real if it is designed in from the start. The most useful single decision is a tenant routing layer, a small lookup that maps each tenant to the database, and optionally schema, that holds its data, used by every connection the application makes. On day one it may contain a single entry for everyone. When the first enterprise customer needs isolation, moving them becomes a data copy and a routing change rather than an architectural rewrite. The broader patterns for partitioning and sharding data as it grows are covered in database design patterns for scale.

Keeping the option to change models

The single habit that keeps every future option open is putting tenant_id on every tenant-owned table, even when it could be derived through a join. A comment row that belongs to a task that belongs to a project already "knows" its tenant through two joins, but extracting one tenant's data for a move, an export or a deletion request then requires following every relationship correctly. With the column present, every table can be filtered directly, copied with a single predicate and verified by counting rows per tenant on both sides.

The same discipline pays off elsewhere. Background jobs, cache keys, file storage paths, search indexes and event payloads should all carry the tenant identifier explicitly. A model change touches all of them, and so does the authorisation work described in authentication and authorisation in production systems, which sits on top of whichever tenancy model you choose.

Checklist for a new multi-tenant system

  1. The definition of a tenant is written down: an organisation, a workspace or an individual, and how users relate to it.
  2. Every tenant-owned table has tenant_id, and every primary key and foreign key includes it.
  3. The application connects as a role that does not own the tables; row-level security is enabled and forced on tenant tables.
  4. Tenant context is set per transaction from the authenticated session, never from request parameters.
  5. A tenant routing lookup exists, even if it has one entry.
  6. Per-tenant export, deletion and restore have been tried at least once, not only designed.
  7. A test suite runs the same requests as two different tenants and asserts that neither can read or modify the other's data.

The last item is the one that turns isolation from a belief into a fact. If you are commissioning a SaaS product, ask to see that test running before launch; tenancy, routing and isolation tests are part of how we approach web platform development. The SaaS arc of Under the Hood returns to tenant isolation in more depth.

References

Related Articles

Backend Design20 min read

Database Design Patterns for Scale

Scale databases with sharding, replication, and partitioning. Covers PostgreSQL, MySQL, and MongoDB scaling patterns with real performance numbers from production systems.