Product Engineering
Multi-tenant SaaS on PostgreSQL: row-level security in practice
Isolate customer data in a shared PostgreSQL database with row-level security: tenancy models, policies, connection pooling pitfalls and isolation tests.
By Envexa Engineering7 min read
Almost every SaaS product has the same non-negotiable requirement: customer A must never see customer B's data. The usual approach, remembering to add WHERE tenant_id = ? to every query, works until the day someone forgets once. PostgreSQL's row-level security (RLS) moves that rule into the database, so a mistake in application code cannot leak data.
Three ways to model tenancy
- Database per tenant. Strongest isolation and easy per-customer backup or restore, but expensive to operate and migrate at scale.
- Schema per tenant. A middle ground, though thousands of schemas strain tooling and migrations.
- Shared tables with a `tenant_id` column. The simplest to operate and the most common for early and mid-stage products. Isolation depends on discipline, which is where RLS helps.
Turning on RLS
ALTER TABLE projects ENABLE ROW LEVEL SECURITY;
ALTER TABLE projects FORCE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON projects
USING (tenant_id = current_setting('app.tenant_id', true)::uuid)
WITH CHECK (tenant_id = current_setting('app.tenant_id', true)::uuid);USING filters which rows are visible; WITH CHECK stops inserting or updating rows into another tenant. FORCE ROW LEVEL SECURITY matters: by default the table owner bypasses RLS, and so do superusers and roles with BYPASSRLS. Your application should connect as a dedicated, unprivileged role that owns nothing.
Telling the database who the tenant is
Set the tenant for the current transaction after authenticating the request:
BEGIN;
SELECT set_config('app.tenant_id', $1, true); -- true = local to this transaction
-- ... run queries; RLS applies automatically ...
COMMIT;Using the transaction-local form is essential with connection pooling. A session-level setting can leak to the next request that reuses the connection, which is exactly the leak you are trying to prevent. With a pooler in transaction mode, always set the value inside each transaction.
Pitfalls
- Missing policies fail closed, bad ones fail open. If
app.tenant_idis unset,current_setting(..., true)returns null and the comparison matches no rows. That is the safe default; keep it that way. - Indexes. Put
tenant_idfirst in common composite indexes, since every query is now effectively filtered by it. - Unique constraints should usually include
tenant_id, so two tenants can use the same slug or email. - Background jobs and admin tools need an explicit, audited way to act on behalf of a tenant, or a separate role designed for it.
- Views and functions. Views run with the owner's rights by default, which can bypass RLS. Use
security_invokerviews, and reviewSECURITY DEFINERfunctions carefully.
Prove it with tests
Write tests that create two tenants and assert that tenant A cannot read, update, delete or insert into tenant B's rows through every table and endpoint. Run them in CI against a real PostgreSQL instance as the application role, not as an admin. Add a check that every table with a tenant_id column has RLS enabled, so a new table cannot ship unprotected.
RLS is a safety net, not a substitute for authorisation logic. Combine it with proper permission checks in the application, and you get defence in depth: a coding mistake becomes a bug rather than a data breach.
Related articles
Why most MVPs should start as a modular monolith
Microservices solve scaling problems most MVPs do not have yet. How to structure a modular monolith that is fast to build now and splittable later.
Idempotency keys: designing APIs that are safe to retry
Networks fail and clients retry. How idempotency keys prevent duplicate charges and orders, with implementation, edge cases and storage design.