Why Multi-Tenancy Decisions Haunt You Later
Most SaaS teams pick a multi-tenancy model in week two of the project and never revisit it. By the time the choice matters — when the 200th tenant signs up and query latency doubles, or an enterprise customer demands a dedicated database for SOC 2 — the architecture is load-bearing and expensive to change.
This guide exists so that decision costs less. We benchmark the three dominant PostgreSQL strategies, show the migration paths between them, and give you the monitoring queries that catch isolation failures before your customers do.
The Three Strategies
1. Shared Schema with Row Level Security (RLS)
Every tenant's data lives in the same tables. A tenant_id column on every row, combined with PostgreSQL RLS policies, enforces isolation at the database level.
-- Enable RLS on the orders table
ALTER TABLE orders ENABLE ROW LEVEL SECURITY;
-- Policy: tenants see only their own rows
CREATE POLICY tenant_isolation ON orders
USING (tenant_id = current_setting('app.current_tenant039;)::uuid);
-- Application sets the tenant context per request
SET app.current_tenant = 'a1b2c3d4-...039;;
How it works at runtime:
Request → App sets current_setting('app.current_tenant039;) → Every SELECT/INSERT/UPDATE/DELETE
is filtered by the RLS policy automatically → No application-layer WHERE clause needed
2. Schema-per-Tenant
Each tenant gets a dedicated PostgreSQL schema (tenant_abc.orders, tenant_xyz.orders). The application sets search_path per connection to route queries to the right schema.
-- Create a schema for a new tenant
CREATE SCHEMA tenant_abc;
-- Create tables inside the tenant schema
CREATE TABLE tenant_abc.orders ( ... );
-- Route queries by setting search_path
SET search_path TO tenant_abc, public;
3. Database-per-Tenant
Each tenant gets an entirely separate PostgreSQL database (or cluster). The application maintains a routing table that maps tenant identifiers to connection strings.
Tenant Registry:
┌──────────┬──────────────────────────────────────────┐
│ tenant │ connection_string │
├──────────┼──────────────────────────────────────────┤
│ acme │ postgres:#6a9955]">//db1.internal:5432/acme │
│ globex │ postgres:#6a9955]">//db2.internal:5432/globex │
│ initech │ postgres:#6a9955]">//db3.eu-west.internal:5432/init │
└──────────┴──────────────────────────────────────────┘
Benchmark Comparison
We ran synthetic workloads on a PostgreSQL 16 instance (8 vCPU, 32 GB RAM, NVMe SSD) with a realistic schema: 12 tables, 6 foreign keys, 3 composite indexes, and a mix of read-heavy (80%) and write (20%) queries.
| Metric | Shared + RLS | Schema-per-Tenant | Database-per-Tenant |
|---|---|---|---|
| 100 tenants — p95 read latency | 2.1 ms | 2.0 ms | 1.9 ms |
| 1 000 tenants — p95 read latency | 3.4 ms | 2.8 ms | 2.0 ms |
| 10 000 tenants — p95 read latency | 8.2 ms | 6.1 ms (schema bloat) | 2.1 ms (per-db) |
| Migration complexity (DDL change) | 1 migration | N migrations (1 per schema) | N migrations (1 per database) |
| Backup granularity | Full database only | pg_dump per schema | pg_dump per database |
| Connection overhead (PgBouncer) | Low — 1 pool | Medium — search_path switching | High — 1 pool per database |
| Tenant data residency | Not possible | Not possible (same cluster) | Possible (separate clusters) |
| Noisy-neighbor risk | High — shared indexes | Medium — shared buffer pool | Low — isolated resources |
Decision Flowchart
┌─────────────────────────┐
│ Do any tenants require │
│ data residency in a │
│ specific region? │
└────────┬────────────────┘
│
Yes ─────┼───── No
│ │
▼ ▼
Database-per-Tenant ┌─────────────────────────┐
(for those tenants) │ Will you exceed 1 000 │
│ tenants within 2 years?│
└────────┬────────────────┘
│
Yes ─────┼───── No
│ │
▼ ▼
Hybrid: Shared + RLS
Shared + RLS (simplest path)
for small tenants,
schema/db for
enterprise
RLS Deep Dive: Policies That Work in Production
Basic Tenant Isolation
The minimal policy uses a session variable and an equality check:
CREATE POLICY tenant_read ON orders
FOR SELECT
USING (tenant_id = current_setting('app.current_tenant039;)::uuid);
CREATE POLICY tenant_write ON orders
FOR INSERT
WITH CHECK (tenant_id = current_setting('app.current_tenant039;)::uuid);
Role-Based Access Within a Tenant
For applications that need row-level permissions within a tenant (e.g., managers see all orders, sales reps see only their own):
CREATE POLICY tenant_role_access ON orders
FOR SELECT
USING (
tenant_id = current_setting('app.current_tenant039;)::uuid
AND (
current_setting('app.current_role039;) = 039;manager039;
OR assigned_to = current_setting('app.current_user_id039;)::uuid
)
);
Superuser Bypass for Admin Operations
-- Admin role bypasses RLS for cross-tenant reporting
ALTER ROLE admin_reporting BYPASSRLS;
Use this sparingly. Every BYPASSRLS role is a potential data leak if credentials are compromised. Audit access and rotate credentials on a schedule.
Connection Pooling: The Hidden Constraint
Shared Schema + RLS with PgBouncer
PgBouncer in transaction mode works well. The application sets app.current_tenant at the start of each transaction, and PgBouncer recycles the connection when the transaction ends.
App Request → PgBouncer (transaction mode) → PostgreSQL
BEGIN;
SET LOCAL app.current_tenant = 'tenant-uuid039;;
SELECT * FROM orders; -- RLS filters automatically
COMMIT;
-- Connection returned to pool
Schema-per-Tenant with PgBouncer
This is where teams get burned. PgBouncer transaction mode does not preserve search_path across transactions. You must use SET LOCAL search_path inside every transaction block:
BEGIN;
SET LOCAL search_path TO tenant_abc, public;
SELECT * FROM orders; -- Resolves to tenant_abc.orders
COMMIT;
-- search_path reset — safe for pool reuse
If you use session mode instead, PgBouncer holds one connection per client session, which defeats the purpose of pooling at scale.
Database-per-Tenant with PgBouncer
Each database needs its own pool. At 500 tenants with a minimum of 2 connections per pool, you need 1 000 connections across your PgBouncer instances. This is manageable with multiple PgBouncer processes but adds operational complexity.
Migrating Between Strategies
Shared → Schema-per-Tenant (for a single enterprise customer)
This is the most common migration. An enterprise customer needs dedicated resources or compliance isolation.
Step 1: Create the target schema
CREATE SCHEMA tenant_enterprise;
Step 2: Copy table structures
pg_dump --schema-only --table='public.orders039; | sed 039;s/public/tenant_enterprise/g039; | psql
Step 3: Migrate data
INSERT INTO tenant_enterprise.orders
SELECT * FROM public.orders WHERE tenant_id = 'enterprise-uuid039;;
Step 4: Update the routing layer
Tenant registry: enterprise → search_path = tenant_enterprise
Step 5: Delete migrated rows from shared tables
DELETE FROM public.orders WHERE tenant_id = 'enterprise-uuid039;;
Step 6: Verify isolation
Run the monitoring queries below.
Schema-per-Tenant → Database-per-Tenant
For data residency or hard resource isolation:
-- Export the schema
pg_dump --schema=tenant_abc source_db > tenant_abc.sql
-- Create the target database
CREATE DATABASE tenant_abc_db;
-- Import, remapping the schema to public
cat tenant_abc.sql | sed 's/tenant_abc./public./g039; | psql tenant_abc_db
-- Update the routing table
UPDATE tenant_registry SET connection_string = 'postgres://new-host:5432/tenant_abc_db039;
WHERE tenant_id = 'abc039;;
Monitoring Queries for Tenant Isolation
Run these in CI and on a recurring schedule in production.
Verify RLS Is Enabled on All Tenant Tables
SELECT schemaname, tablename, rowsecurity
FROM pg_tables
WHERE schemaname = 'public039;
AND tablename IN ('orders039;, 039;invoices039;, 039;customers039;, 039;inventory039;)
AND rowsecurity = false;
-- Expected result: 0 rows. Any result means RLS is disabled on a tenant table.
Detect Cross-Tenant Data Leaks (Shared Schema)
-- Set context to tenant A
SET app.current_tenant = 'tenant-a-uuid039;;
-- Attempt to read tenant B's data
SELECT count(*) FROM orders WHERE tenant_id = 'tenant-b-uuid039;;
-- Expected result: 0. If non-zero, the RLS policy is broken.
Schema-per-Tenant: Verify No Tables Exist in Public
SELECT tablename FROM pg_tables
WHERE schemaname = 'public039;
AND tablename NOT IN ('schema_migrations039;, 039;tenant_registry039;, 039;spatial_ref_sys039;);
-- Expected result: only shared infrastructure tables.
Common Mistakes
1. Forgetting to Set the Tenant Context
If the application fails to call SET app.current_tenant before a query, RLS policies that use current_setting will either return no rows (safe but confusing) or raise an error (depends on current_setting's second parameter). Always set a default that returns zero rows, never one that disables filtering:
-- Safe: returns empty string if not set, matching no tenant_id
current_setting('app.current_tenant039;, true)
2. Indexing the Tenant Column as an Afterthought
RLS policies on tenant_id are only fast if the column is indexed. For shared-schema models, every table with a tenant_id column needs at minimum:
CREATE INDEX idx_orders_tenant ON orders (tenant_id);
-- For queries that filter by tenant + date:
CREATE INDEX idx_orders_tenant_date ON orders (tenant_id, created_at DESC);
3. Running Aggregate Queries Across Tenants Without BYPASSRLS
Admin dashboards that show cross-tenant metrics will return only the current tenant's data if the connection has RLS active. Use a dedicated reporting role with BYPASSRLS, accessed through a separate connection pool with strict audit logging.
4. Using Session-Mode Pooling with Schema-per-Tenant
Session mode in PgBouncer holds one backend connection per frontend connection. At 500 tenants with 20 concurrent users each, that is 10 000 PostgreSQL connections — well past the limit of any single instance. Use transaction mode and SET LOCAL.
When to Move Beyond PostgreSQL
PostgreSQL handles multi-tenancy well up to thousands of tenants. Beyond that, consider:
- Citus (distributed PostgreSQL): Shards tables by tenant_id across worker nodes. Same SQL, horizontal scale.
- Separate clusters per region: For data residency and latency. Use a global routing layer.
- Managed services: AWS Aurora, Google Cloud SQL, and Supabase all support RLS and connection pooling natively.
The goal is not to pick the perfect strategy on day one. The goal is to pick a strategy that works today and has a documented migration path for tomorrow.
The Bottom Line
Multi-tenancy is not a database feature — it is an architectural commitment that touches connection pooling, migrations, monitoring, compliance, and disaster recovery. Start with shared-schema and RLS for speed. Plan the migration to schema-per-tenant or database-per-tenant for your enterprise customers. And test isolation in CI, every single deploy.




