How to Implement Tenant Isolation in a Shared Database
Keep tenant data separate in one database with row-level policies, scoped queries and defence so a missing filter cannot leak data.
On this page
Introduction
Serving many tenants from one database is efficient: one schema, one backup, one connection pool. The risk is isolation: a query that forgets its tenant filter returns another tenant’s rows, and a single missed WHERE clause becomes a data breach. Tenant isolation in a shared database is about making that mistake hard and detectable, not only about remembering to add the filter. This article compares isolation models, shows how row-level security enforces the filter in the database, and covers the application-layer practices that keep tenants separate even when a query is wrong.
Isolation Models
There is a spectrum. At one end, a database-per-tenant gives the strongest isolation, the easiest per-tenant restore, and the highest operational cost. At the other, a shared table with a tenant_id column gives the lowest cost and the weakest isolation, because everything depends on every query filtering correctly. In between are schema-per-tenant, which isolates tables but still shares the database and its resources.
Choose by the sensitivity of the data and the cost of a leak. Regulated or high-value data may justify database-per-tenant; a multi-tenant SaaS with many small tenants usually needs a shared table with strong controls and is served best by row-level security. The shared model is viable if isolation is enforced by the database rather than trusting every query.
Row-Level Security
PostgreSQL row-level security applies a policy to a table so that queries see only the rows the policy allows, based on the current session’s identity. Set a session variable to the tenant, and every query against the table is filtered automatically, including queries written by a developer who forgot the filter. This turns a policy into enforcement at the storage layer, which is exactly the defence a shared table needs.
ALTER TABLE documents ENABLE ROW LEVEL SECURITY;
-- Each tenant sees only its own rows.
CREATE POLICY tenant_isolation ON documents
USING (tenant_id = current_setting('app.tenant_id')::uuid)
WITH CHECK (tenant_id = current_setting('app.tenant_id')::uuid);
-- USING gates reads and existing-row updates/deletes; WITH CHECK gates inserts
-- and the new row of updates, so a tenant cannot write another tenant's data.
-- The application sets the tenant per connection (or per transaction):
SET LOCAL app.tenant_id = '3f0a...';
-- From here, SELECT * FROM documents returns only this tenant's rows.
Scoped Queries and Defence in Depth
Even with row-level security, scope the queries in the application so the intent is explicit and the query is efficient. A repository that takes the tenant as a required argument, and includes it in every statement, keeps the filter visible in code review and in the query plan. Row-level security is the backstop; the explicit filter is the primary control, and the two together tolerate a mistake in either.
// The tenant is a required argument, so a query cannot be built without it.
type TenantId = string & { readonly __brand: 'TenantId' };
export function findDocuments(db: Pool, tenantId: TenantId, filter: Filter) {
return db.query(
'SELECT * FROM documents WHERE tenant_id = $1 AND status = $2',
[tenantId, filter.status],
);
}
// A route handler runs the whole request inside the tenant's scope:
async function handler(req: Request) {
const tenantId = req.auth.tenantId as TenantId; // from the authenticated user
if (!tenantId) throw new Unauthorized();
await db.query('SET LOCAL app.tenant_id = $1', [tenantId]); // RLS backstop
return findDocuments(db, tenantId, req.filter);
}
Cross-Tenant Risks in Shared Resources
Isolation extends beyond the primary tables. Caches keyed by entity id but not tenant collide across tenants and may serve one tenant’s cached value to another. File storage paths that omit the tenant allow a guessed path to read another tenant’s object. Background jobs that process all rows must set the tenant per iteration, or row-level security will filter them to nothing. Search indexes and analytics tables need the same tenant column and the same discipline.
The lesson is that every shared resource is a potential leak point, and each needs the tenant in its key, path or policy. Enumerate the shared resources, tag each with how the tenant is enforced, and review the list when a new one is added. A cache key or storage path without the tenant is the same bug as a query without the filter.
Testing Isolation
Test isolation adversarially: create data for tenant A and tenant B, authenticate as A, and assert that no query returns any of B’s rows, including by id, by list, and through every endpoint. Assert that an insert with B’s tenant_id while authenticated as A is rejected by the policy. These tests must run against the real database with the real policies, because the guarantee comes from the policy and a mock would not exercise it.
Also test the negative paths: a request with no tenant must fail rather than default to all rows, and a tenant id that does not exist must return nothing rather than everything. The most dangerous bug is a default that widens access when the tenant is missing, so the default must be to deny. A missing tenant should be an error, not wildcard.
Operations Per Tenant
Shared isolation complicates operations. A noisy tenant can consume the shared pool and slow everyone, so per-tenant rate limits and resource accounting matter. Backups and restores are whole-database, so restoring one tenant’s data means extracting it carefully. Deleting a tenant means deleting rows across every table and cache, which is error-prone without a clear tenant column and a checklist.
Plan the operational side before you scale: how a tenant is onboarded, how its data is exported for a subject access request, how it is deleted, and how a hotspot tenant is contained. These are the questions a shared database makes harder rather than easier, and answering them up front is the difference between a shared model that scales and one that becomes a compliance problem.
Conclusion
Tenant isolation in a shared database is enforced, not remembered. Choose the isolation model from the data’s sensitivity, use row-level security as a storage-layer backstop so a missing filter does not leak, keep the tenant a required argument in every query so the intent is explicit, and apply the same discipline to caches, file paths, jobs and indexes. Test isolation adversarially against the real policies, make a missing tenant an error rather than a wildcard, and plan the per-tenant operations before they become urgent. Then one database can serve many tenants without one missing clause becoming a breach.
Sources: PostgreSQL: Row Security Policies, OWASP: Multi-tenant security, AWS: tenant isolation models.
FAQ
- How does row-level security help if I already filter by tenant?
- It is a backstop for the query you forgot to filter. The explicit filter is the primary control, and the policy enforces the same rule at the storage layer, so a mistake in either is caught by the other. Both together tolerate a slip.
- What should happen when a request has no tenant?
- It must fail, not default to all rows. The most dangerous bug is a default that widens access when the tenant is missing. Require the tenant from the authenticated identity and reject the request if it is absent.
Report a problem with this articleOpens a pre-filled issue on GitHub.