Multi-tenancy means one running system serves many customers, called tenants, while each tenant sees only its own data and experiences consistent performance. It is the economic engine of SaaS: shared infrastructure lowers cost per customer, and a single release reaches everyone. It is also the source of the worst class of SaaS incidents, in which one customer sees another’s data or one heavy customer slows down all the rest.
This article walks through the decisions that shape a multi-tenant system: the data isolation model, how identity and authorization carry the tenant, how billing connects to usage, how to contain noisy neighbors, and how to migrate an existing single-tenant product.
Start with the tenant model
Before choosing a database layout, define what a tenant is. In a B2B product it is usually an organization, with users who may belong to several organizations. In B2C, a tenant may be a household or a workspace. Decide early:
- Can a user belong to multiple tenants? (Almost always yes eventually; model it as a membership table, not a column on the user.)
- Is there a hierarchy, such as an enterprise with departments or a reseller with sub-accounts?
- What identifies a tenant externally: a subdomain, a path prefix, a header, or an API key?
- Which data is global (plans, feature flags, reference data) and which is tenant-owned?
Write the answers down. Retrofitting a hierarchy or multi-membership into a schema that assumed one user per tenant is one of the most painful migrations in SaaS.
Data isolation models
There are three canonical approaches, and most mature products end up using a mix.
| Model | How it works | Isolation | Cost per tenant | Operational complexity | Best for |
|---|---|---|---|---|---|
| Shared schema (pooled) | All tenants in the same tables with a tenant_id column |
Logical, enforced by code and policies | Lowest | Low at start, higher at scale | Many small tenants, self-service |
| Schema per tenant | One database, one schema per tenant | Stronger, per-tenant objects | Low to medium | Migrations must run N times | Tens to low thousands of tenants |
| Database per tenant (siloed) | Separate database or instance per tenant | Strongest, per-tenant backup and restore | Highest | High: fleet management required | Enterprise, regulated, data residency |
Pooled tables with row-level security
For the shared model, do not rely on every developer remembering WHERE tenant_id = ?. Enforce it in the database. PostgreSQL row-level security (RLS) is well suited:
ALTER TABLE invoices ENABLE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON invoices
USING (tenant_id = current_setting('app.tenant_id')::uuid);
-- Per request, inside the transaction:
SET LOCAL app.tenant_id = '6f1c2d9e-...';
Make tenant_id the leading column of composite indexes and of primary keys where feasible, since nearly every query filters by it. Use a connection pooler in transaction mode carefully: the tenant setting must be applied with SET LOCAL within each transaction, otherwise it can leak between requests on a reused connection. Test this specifically, with a test that attempts cross-tenant reads.
Schema and database per tenant
Separate schemas give cleaner per-tenant exports and the option to move a single tenant elsewhere. The costs are migration orchestration (every change applied to every schema, with failure handling and version tracking), catalog bloat at thousands of schemas, and connection management.
Database-per-tenant is the right answer when contracts demand it: dedicated encryption keys, data residency in a specific region, bespoke retention, or independent restore. It requires automation for provisioning, migrations, monitoring and cost allocation. Do not adopt it for the sake of purity; adopt it where a customer pays for it.
The hybrid pattern
A common and sensible architecture is pooled by default with the ability to promote a tenant to its own database. Design for that from the start: keep a tenant registry table that records where each tenant’s data lives, and resolve connections through it. Then a “move this tenant to a dedicated database” operation is a project, not a rewrite.

Carrying the tenant through auth
The tenant context must be established once, early and unambiguously, then propagated everywhere.
- Resolution: derive tenant from the subdomain (
acme.example.com), a signed token claim, or an API key that maps to a tenant. Never trust a tenant ID supplied in a request body or query string without checking membership. - Token claims: include the tenant ID and the user’s role in that tenant in the access token. When a user switches organizations, issue a new token rather than mutating state client-side.
- Authorization: model roles per tenant (owner, admin, member, viewer) and check permissions at the service layer, not only in the UI. A policy engine or a well-tested permission module avoids scattered checks.
- Single sign-on: enterprise buyers will ask for SAML or OIDC per tenant. Store identity provider configuration per tenant, verify the email domain before enabling it, and support just-in-time provisioning, plus SCIM if you target larger accounts.
- Background jobs: a job runs with no request, so it must carry the tenant ID in its payload and re-establish context before touching data. Forgotten context in queue workers is a frequent cause of cross-tenant bugs.
- Caches and search: prefix cache keys with the tenant ID, and filter search indexes by tenant. A shared cache without tenant-scoped keys is a data leak waiting to happen.
Isolation bugs rarely come from the database layer. They come from the places that forgot to ask which tenant is calling: jobs, caches, exports and admin tools.
Billing that follows the tenant
Billing is a tenant-level concern, and it should be decoupled from your core domain through a thin internal service or module.
- Plans and entitlements: separate what a customer pays for (the plan) from what the product allows (entitlements such as seat count, API quota, features). Application code should check entitlements, never plan names, so you can change pricing without code changes.
- Provider integration: use a payment platform such as Stripe Billing for subscriptions, invoices, proration and tax, and treat its webhooks as the source of truth for subscription state. Make webhook handlers idempotent and verify signatures.
- Usage-based billing: meter events with an idempotency key, aggregate per tenant per period, and report to the billing provider. Keep raw usage events for dispute resolution. Show customers their usage in-product so invoices are never a surprise.
- Lifecycle states: define behavior for trial, active, past due, suspended and canceled. A past-due tenant should usually enter a grace period with read access before restrictions apply. Data deletion after cancellation should follow a documented retention window.
- Cost attribution: tag infrastructure usage by tenant where possible, so you can compute gross margin per customer and spot plans that lose money.
Containing noisy neighbors
In a shared system, a single tenant running a huge export or a runaway integration can degrade everyone else. Plan limits at several levels:
- API rate limiting per tenant, using a token bucket stored in Redis or at the gateway, with limits tied to plan. Return
429with aRetry-Afterheader. - Query governance: statement timeouts, pagination caps, and restrictions on unbounded reports. Route heavy analytical queries to a read replica or a separate analytics store.
- Queue fairness: a single shared job queue lets one tenant’s 100,000 imports starve everyone. Use per-tenant concurrency limits, weighted fair queuing, or separate queues for heavy job types.
- Resource quotas: storage, file size, number of records, webhook endpoints.
- Cell-based architecture: at larger scale, split tenants into independent cells (full copies of the stack) and assign tenants to cells. A failure or overload affects one cell, and you can place large tenants in their own.
Observability must be tenant-aware. Include the tenant ID as a field in logs, traces and metrics (watching cardinality in metrics systems; use logs and traces for high-cardinality tenant breakdowns). Build a view of the top tenants by requests, database time and error rate. Without it, noisy neighbors are diagnosed by guesswork.
Migrating from single-tenant to multi-tenant
Many products begin as one deployment per customer, or as a single-customer app. A migration can be done incrementally:
- Introduce the tenant concept in the code first. Add a
tenantstable and atenant_idto every tenant-owned table, filled with a default tenant. Nothing changes functionally. - Add enforcement. Introduce a request-scoped tenant context, update the data access layer to apply it automatically, and add RLS or equivalent policies in report-only or shadow mode first, logging queries that would have been blocked.
- Fix globals. Audit unique constraints (an email may now be unique per tenant, not globally), file storage paths, cache keys, scheduled jobs and configuration stored in files or environment variables.
- Backfill and consolidate. Move existing customer deployments into the shared system one at a time, with ID remapping if primary keys collide. Rehearse on a copy, verify record counts and checksums, and keep a rollback plan.
- Add tenant-aware tooling. Admin impersonation with audit logs, per-tenant export and deletion, and feature flags per tenant.
Write cross-tenant tests early: create two tenants, populate both, and assert that every API endpoint, export and background job returns only the caller’s data. Run them in CI on every change. In our work at Datainter on SaaS platforms, this single suite has caught more serious defects than any other test category.
Compliance and data lifecycle
Enterprise customers will ask about encryption, residency and deletion. Be ready with encryption at rest and in transit, optional per-tenant keys for siloed tenants, documented backup retention, and a tested procedure to export or delete all of one tenant’s data on request. For pooled databases, deletion means a reliable cascade across every table, cache, search index, object store and backup policy, so maintain a registry of where tenant data lives.
Key takeaways
- Define the tenant model first, including multi-membership and hierarchy, since these are costly to retrofit.
- Pooled schemas with row-level security are the economical default; reserve schema-per-tenant or database-per-tenant for customers who need stronger isolation, and keep a tenant registry so tenants can be promoted.
- Establish tenant context once, in auth, and carry it into jobs, caches, search and admin tools, where most isolation bugs hide.
- Bill from entitlements and metered usage with idempotent webhooks, and keep plan logic out of application code.
- Contain noisy neighbors with per-tenant rate limits, query timeouts, fair queues and, at scale, cells; make observability tenant-aware.
- Migrate incrementally and gate every change with automated cross-tenant leakage tests.

