What Multi-Tenancy Actually Solves
Multi-tenancy means one running deployment of your application serves many logically separate customers, while the code, the runtime and the infrastructure are shared. The economic argument is unremarkable but real: a single-tenant deployment of Postgres, Redis, a queue worker and an image origin costs roughly the same whether it serves 3 users or 3,000. At a few hundred tenants, per-tenant infrastructure becomes the largest line item in your cloud bill — and it is a line item that grows ahead of your revenue.
The reason most SaaS teams adopt it early is not cost but operational surface area. Every deployment you run is a thing that can page at 03:00. Ten tenants on one deployment means ten rollouts a month; a thousand tenants on a thousand deployments means a configuration problem you will not win. Google's SRE book makes the same argument in a different context: engineering time is consumed disproportionately by maintenance load, and maintenance load scales with the number of independently operated systems.
What multi-tenancy does not give you is isolation for free. Isolation is the part you build, and it is the part that ends up in your incident channel. Two tenants reading each other's invoices surfaces as a support ticket from a competitor, and it surfaces it in public. Treat tenant isolation as a security feature with a threat model, not as a query filter you remember to add.
The Three Tenancy Models
| Dimension | Shared schema | Schema per tenant | Database per tenant |
|---|---|---|---|
| Isolation strength | Weakest — one leaked predicate crosses tenants | Strong — namespace boundary | Strongest — physical boundary |
| Blast radius of a bug | All tenants | One schema | One tenant |
| Migrations | Once, standard migration runner | Fan out to every tenant schema, resumable | Fan out to every database, resumable |
| Cross-tenant analytics | Trivial single query | Union across schemas | Federate or replicate to a warehouse |
| Per-tenant backup/restore | Hard | Awkward — must dump one schema | Native, one database per backup |
| Connection count | One pool | One pool, multi-schema | Multiplies — the real trap |
| Works at | Tens of thousands of tenants | Hundreds of tenants | Tens of tenants, mostly enterprise |
| Operational cost at scale | Lowest | Medium | Highest |
Read that last row carefully, because it contradicts what most architecture diagrams imply. The three models are ordered by isolation strength, and inverse-ordered by the difficulty of operating them past a certain tenant count. Choosing the strongest isolation up front is not the conservative choice; on a large book of business it is the expensive one.
Strategy 1: Shared Database, Shared Schema
Every tenant shares one database and one set of tables. A tenant_id column on every row identifies ownership, and every query is expected to filter on it. This is where essentially every product should start.
sqlCREATE TABLE tenants ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), slug text NOT NULL UNIQUE, name text NOT NULL, plan text NOT NULL DEFAULT 'starter', created_at timestamptz NOT NULL DEFAULT now() ); CREATE TABLE documents ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), tenant_id uuid NOT NULL REFERENCES tenants(id) ON DELETE CASCADE, title text NOT NULL, body text NOT NULL DEFAULT '', status text NOT NULL DEFAULT 'draft', created_by uuid NOT NULL, created_at timestamptz NOT NULL DEFAULT now(), archived_at timestamptz ); -- Every query path is an index path. Without these, cross-tenant row counts -- keep growing and your only defence is hoping the planner picks them. CREATE INDEX documents_tenant_created_idx ON documents (tenant_id, created_at DESC) WHERE archived_at IS NULL; -- Composite FK: a child row cannot reference a parent owned by another tenant. ALTER TABLE documents ADD CONSTRAINT documents_owner_consistent FOREIGN KEY (tenant_id, created_by) REFERENCES tenant_users (tenant_id, id);
That last constraint is worth more than it looks. It makes it impossible to attach a document to a user in another tenant, which closes a whole class of cross-tenant bug at the schema level instead of at the code-review level. We add tenant_id as the leading column of every foreign key, every composite index and every unique constraint. The cost is a wider key; the benefit is that the database, not a developer's memory, is the thing enforcing the boundary.
Why the "just remember the WHERE clause" approach leaks
The failure mode is not hypothetical. It happens when a report query, an admin export, or a health check joins a table you did not think about:
sql-- Looks harmless. Is not. SELECT d.title, u.email FROM documents d JOIN tenant_users u ON u.id = d.created_by WHERE d.status = 'published'; -- No tenant predicate. Returns every tenant's documents to whoever called it.
You can review for this forever and it will still ship. Or you can make the database refuse. The mechanism is Postgres row-level security, described next, and in our view it should be enabled on every multi-tenant table regardless of which of the three strategies you end up on.
Row-Level Security as the Safety Net
Postgres row-level security lets you attach a policy to a table so the database itself filters rows for every SELECT, INSERT, UPDATE and DELETE. Postgres applies these rules by default to every query, including queries from the application role. That "by default" is the whole point: the predicate lives next to the data, not in 400 query strings.
sqlALTER TABLE documents ENABLE ROW LEVEL SECURITY; -- FORCE makes the policy apply to the table owner too. Without it, a -- migration connection that owns the table bypasses every policy. ALTER TABLE documents FORCE ROW LEVEL SECURITY; CREATE POLICY documents_tenant_isolation ON documents USING (tenant_id = current_setting('app.tenant_id', true)::uuid) WITH CHECK (tenant_id = current_setting('app.tenant_id', true)::uuid); -- RLS does NOT cascade to members. A separate policy is mandatory. ALTER TABLE document_revisions ENABLE ROW LEVEL SECURITY; CREATE POLICY document_revisions_tenant_isolation ON document_revisions USING (tenant_id = current_setting('app.tenant_id', true)::uuid) WITH CHECK (tenant_id = current_setting('app.tenant_id', true)::uuid);
Two details that cause real outages:
ENABLEis not enough. By default the table owner bypasses RLS. Table owners are exactly what your migration tool connects as. UseFORCE ROW LEVEL SECURITYso nothing, including your deploy user, escapes the policy.- Policies do not cascade. Table A having a policy tells you nothing about table B. In a schema with 60 tenant-scoped tables you need 60 policies, and the Postgres docs on row security are explicit that
USINGandWITH CHECKare separate clauses —USINGalone protects reads and silently lets a tenant write rows into another tenant.
The connection must then announce which tenant it is acting for, once per transaction:
sqlBEGIN; SET LOCAL app.tenant_id = '7f3c9a12-0b4e-4a1f-9d2c-5e8a1b6c4d20'; SELECT count(*) FROM documents; -- automatically scoped to that tenant COMMIT;
SET LOCAL rather than SET is deliberate: it resets at COMMIT, so a pooled connection cannot leak one tenant's identity into the next request that grabs it.
Strategy 2: Schema per Tenant
Each tenant gets its own namespace inside one database. The DDL is identical, so you generate it:
sqlCREATE SCHEMA tenant_7f3c9a12 AUTHORIZATION tenant_7f3c9a12; CREATE TABLE tenant_7f3c9a12.documents ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), title text NOT NULL, body text NOT NULL DEFAULT '', status text NOT NULL DEFAULT 'draft', created_at timestamptz NOT NULL DEFAULT now() ); -- Only the owning tenant's role can touch this schema at all. This is the part -- shared-schema cannot give you: a grant-level boundary, not a row predicate. REVOKE ALL ON SCHEMA tenant_7f3c9a12 FROM PUBLIC; GRANT USAGE ON SCHEMA tenant_7f3c9a12 TO tenant_7f3c9a12; -- Deploying a migration to 400 tenant schemas: serial, resumable, observable. DO $$ DECLARE s record; BEGIN FOR s IN SELECT nspname FROM pg_namespace WHERE nspname LIKE 'tenant_%' LOOP BEGIN EXECUTE format('ALTER TABLE %I.documents ADD COLUMN IF NOT EXISTS reviewed_at timestamptz', s.nspname); EXCEPTION WHEN others THEN RAISE WARNING 'migration failed on %: %', s.nspname, SQLERRM; END; END LOOP; END $$;
The loop is deliberately IF NOT EXISTS and wrapped per schema. A migration that aborts on tenant 217 of 400 leaves you with no record of which half ran, and you will find out during an incident. Log failures, continue, and re-run the migration until the warning count is zero.
Strategy 3: Database per Tenant
Maximum isolation: one database per tenant, one role per tenant, and the possibility of placing a tenant's data in another region. The cost is not money, it is connection management.
The connection pool problem
Postgres defaults to max_connections = 100 (see the connection resource settings in the server docs). A Node app with a modest pool of 10 connections per instance, running 3 instances, needs 30 connections to serve a single database. Per-tenant databases do not create more capacity — they create more independent client pools. At 200 tenants the naive architecture wants 6,000 connections against servers that will accept 100, and because each connection costs a backend process the OS must schedule, the ceiling arrives long before the memory does.
There are three fixes, and you need at least one:
Option A — PgBouncer in transaction mode. All tenants multiplex through a small pool. It works because transaction pooling is compatible with SET LOCAL, which is exactly why the SET LOCAL choice above pays off here:
ini[pgbouncer] listen_addr = 0.0.0.0 listen_port = 6432 auth_type = scram-sha-256 ; Server connections are capped regardless of how many tenants exist. default_pool_size = 20 max_client_conn = 1000 reserve_pool_size = 5 ; Transaction mode is what makes multi-database routing possible at all. pool_mode = transaction ignore_startup_parameters = extra_float_digits,options
Option B — a tenant connection router. One pool per host, not per tenant, with the database name chosen at connect time:
typescriptimport { Pool } from "pg"; const pools = new Map<string, Pool>(); function poolFor(tenant: { dbHost: string; dbName: string }): Pool { const key = tenant.dbHost + "/" + tenant.dbName; let pool = pools.get(key); if (!pool) { pool = new Pool({ host: tenant.dbHost, database: tenant.dbName, max: 8, // per database, not per application instance idleTimeoutMillis: 30_000, statement_timeout: 5_000, }); pool.on("error", (err) => console.error("idle client error", err)); pools.set(key, pool); } return pool; } export async function withTenant<T>( tenant: { dbHost: string; dbName: string; id: string }, fn: (client: import("pg").PoolClient) => Promise<T>, ): Promise<T> { const client = await poolFor(tenant).connect(); try { await client.query("BEGIN"); await client.query("SET LOCAL app.tenant_id = $1", [tenant.id]); const result = await fn(client); await client.query("COMMIT"); return result; } catch (err) { await client.query("ROLLBACK"); throw err; } finally { client.release(); } }
Option C — shard, don't isolate. Put 50 tenants on one database and give up per-tenant databases until a specific customer demands them. This is the option most teams should pick, and they rarely do because it feels like a compromise rather than a decision.
Migrating From Shared Schema to Separate Databases
You will not pick the final model on day one, and that is correct. Most products start shared and end up with a split: shared for the long tail, database-per-tenant for the handful of enterprise accounts with contractual or regulatory requirements. The migration path is a four-step funnel, and it is reversible at every step.
Step 1 — add the column and backfill. On a large table, add nullable, backfill in batches to avoid a long lock, then add the constraint:
sqlALTER TABLE documents ADD COLUMN IF NOT EXISTS tenant_id uuid; -- Backfill 50k rows at a time so you never hold a lock for minutes. UPDATE documents SET tenant_id = (SELECT id FROM tenants WHERE slug = 'legacy') WHERE tenant_id IS NULL AND id IN (SELECT id FROM documents WHERE tenant_id IS NULL LIMIT 50000); -- Only after the backfill reports zero NULLs. ALTER TABLE documents ALTER COLUMN tenant_id SET NOT NULL; ALTER TABLE documents ADD CONSTRAINT documents_tenant_fk FOREIGN KEY (tenant_id) REFERENCES tenants(id);
Step 2 — turn on RLS now. Do this before any routing work. RLS on the shared schema is both the safety net for step 4 and, if you stop there, a perfectly good final state.
Step 3 — dual-write for a whitelisted set of tenants. Add a tenants.isolated flag and route reads and writes for flagged tenants to their own database. Keep the shared rows for one full billing cycle so rollback is a flag flip.
Step 4 — move the data. Per tenant, inside a transaction:
sqlBEGIN; CREATE EXTENSION IF NOT EXISTS dblink; -- Run from the shared database against the target. SELECT dblink_connect('target', 'host=db-7f3c9a12.internal dbname=tenant_7f3c9a12 user=migrator'); SELECT dblink_exec('target', $q$ CREATE TABLE documents (LIKE public.documents INCLUDING ALL); $q$); -- Copy in keyset-paginated batches; OFFSET paging degrades badly on big tables. INSERT INTO documents (id, tenant_id, title, body, status, created_by, created_at) SELECT * FROM public.documents WHERE tenant_id = '7f3c9a12-...' AND id > $last_id ORDER BY id LIMIT 10000; SELECT dblink_disconnect('target'); COMMIT;
Then verify row counts and a checksum of the identity columns before flipping isolated to true. A move with no verification is an outage you discover at the customer's next login.
Resolving the Tenant From the Request
Whatever the storage model, the request must be mapped to a tenant before any query runs. Subdomain (acme.yourapp.com) reads nicest for customers and forces wildcard TLS on the edge. Path prefix (yourapp.com/app/acme) is simplest and works fine on a single certificate. Custom domains are what enterprise buyers ask for, and they need per-tenant certificate provisioning plus a Host-header lookup in the edge.
typescriptexport async function resolveTenant(req: Request): Promise<Tenant> { const host = new URL(req.url).host; // strips :port const tenant = await tenantsByHost.find(host); if (!tenant) throw new NotFoundError("unknown host"); // Auth and tenancy are independent claims. A valid session for tenant A // presented against tenant B must be rejected here, before any query. const session = await auth.verify(req.headers.get("authorization")); if (!session.memberships.some((m) => m.tenantId === tenant.id)) { throw new ForbiddenError("not a member of this tenant"); } return tenant; }
That second half is the check teams skip. Resolving the host is not authorisation — a user can hold a valid session for their own tenant and paste someone else's hostname into the URL.
Test Isolation Explicitly
Do not assume isolation because the queries look right. Write tests that try to break it, and run them in CI on every merge:
typescripttest("a user cannot read another tenant's document by direct id", async () => { const victimDoc = await seedDocument({ tenantId: TENANT_B }); const session = await signInAsUserIn(TENANT_A); const res = await session.get(`/api/documents/${victimDoc.id}`); // 404, not 403. A 403 confirms the id exists, which is itself a leak. expect(res.status).toBe(404); }); test("RLS blocks cross-tenant writes even from the app role", async () => { const res = await db.query( `INSERT INTO documents (tenant_id, title, created_by) VALUES ($1, 'stolen', $2) RETURNING id`, [TENANT_B, userInTenantA], ); expect(res.rowCount).toBe(0); // rejected by WITH CHECK, not by app code });
Returning 404 rather than 403 for another tenant's resource is a deliberate choice. A 403 tells an attacker the object id is real, which turns an enumeration problem into a much cheaper attack.
Choosing One
Start shared with row-level security and composite keys. You get the cheapest model, an enforced isolation boundary, and a clean migration path. Add schema-per-tenant only when a specific customer's compliance review demands a namespace boundary. Reserve database-per-tenant for accounts whose contract or regulator requires it — and accept that you will be maintaining a split routing layer, which is a real ongoing cost and not a one-off migration expense.
If you want the isolation mechanics worked through end to end on a concrete product, our SaaS development service covers where these models sit relative to billing, provisioning and entitlement logic. The phases that produce this architecture are laid out in the software development process, and a worked example of the resulting data model is in how to design a database schema. If you are weighing this against a build-in-house decision, what a software development company actually does is the honest version.