The Multi-Tenancy Conundrum
Every SaaS engineer encounters the multi-tenancy dilemma. Should you isolate customers using:
- Database-per-tenant: Total isolation, but nightmare DevOps management, migration overhead, and cost scaling for thousands of SMBs.
- Schema-per-tenant: Better connection pooling, but Postgres table locks during schema migrations degrade as tenant counts pass 500+.
- Shared-database with tenant_id column: Highly efficient and cost-effective, but vulnerable to a single developer forgetting a
WHERE tenant_id = ?clause, causing cataclysmic data leakage.
PostgreSQL Row Level Security (RLS) offers the ultimate hybrid: the efficiency and unified schema of a single database, backed by kernel-level security guarantees that make data leakage mathematically impossible at the query engine level.
Enabling RLS and Session Context in Postgres
First, enable RLS on tenant-sensitive tables and define security policies that inspect a transactional runtime variable:
-- Enable RLS on core tenant entities
ALTER TABLE organizations ENABLE ROW LEVEL SECURITY;
ALTER TABLE invoices ENABLE ROW LEVEL SECURITY;
ALTER TABLE orders ENABLE ROW LEVEL SECURITY;
-- Force RLS even for table owners (crucial for pooled connections)
ALTER TABLE invoices FORCE ROW LEVEL SECURITY;
ALTER TABLE orders FORCE ROW LEVEL SECURITY;
-- Define tenant isolation policy using session setting
CREATE POLICY tenant_isolation_policy ON orders
AS RESTRICTIVE
FOR ALL
USING (
tenant_id = NULLIF(current_setting('app.current_tenant_id', true), '')::BIGINT
)
WITH CHECK (
tenant_id = NULLIF(current_setting('app.current_tenant_id', true), '')::BIGINT
);
Hooking RLS into Prisma with Client Extensions
Prisma connects via a shared connection pool, meaning transactions must set and reset app.current_tenant_id per query boundary. Prisma Client Extensions make this transparent to application code:
import { PrismaClient } from "@prisma/client";
const basePrisma = new PrismaClient();
export function createTenantPrisma(tenantId: number) {
return basePrisma.$extends({
query: {
$allModels: {
async $allOperations({ args, query }) {
const [, result] = await basePrisma.$transaction([
basePrisma.$executeRawUnsafe(
`SET LOCAL app.current_tenant_id = '${tenantId}'`
),
query(args),
]);
return result;
},
},
},
});
}
Bypassing RLS for System Operations & Background Cron
Background daemons (e.g. system backups, billing reconciliations, or cross-tenant aggregate dashboards) sometimes require elevated access. In Postgres, this is handled through a designated super-tenant role or explicit bypass setting:
CREATE POLICY admin_bypass_policy ON orders
AS PERMISSIVE
FOR ALL
TO service_role
USING (true)
WITH CHECK (true);
Performance Impact & Indexing Strategies
Does RLS hurt query planning? Not when paired with composite indices. When Postgres evaluates tenant_id = current_setting(...), it pushes the predicate down to index scans:
-- Compound index with tenant_id always as the leading column
CREATE INDEX idx_orders_tenant_created ON orders (tenant_id, created_at DESC);
CREATE INDEX idx_invoices_tenant_status ON invoices (tenant_id, status);
With this index strategy, the query planner executes lightning-fast index range scans without full table reads.