Lesson 12 of 16 · Tenants: isolation and onboarding
Isolating tenant data
Keep every tenant's data private in a shared system. Carry the tenant from a verified token to the database, filter in code and enforce again in PostgreSQL with row-level security (a hands-on lab with real output), know the traps (table owners, superusers, connection pools), choose between shared tables, schema per tenant and database per tenant, add per-tenant keys, and test for cross-tenant leaks.
Why data isolation matters most
A slow neighbour is an annoyance. One customer seeing another customer's data is a security incident, a contract breach and often a regulatory report. In a pooled database, every query is one missing WHERE tenant_id = ... away from a leak. So data isolation needs defence in depth: several independent layers, any one of which stops the leak.
A hotel gives you a key card that opens only your room. Even if you walk to the wrong floor, the door won't open. The receptionist checked your ID once (the token), the card carries your room number (the tenant), and every door checks the card (the database policy), so one mistake by a cleaner doesn't open every room.
The layers
- Identity: the tenant comes from a claim in a verified token (for example
tenant: acme), never from a header or parameter the client can set. See Authentication at the edge, where a forgedx-tenant-idheader is overwritten by the verified claim. - Application: a data-access layer that always adds the tenant filter; no raw queries in handlers.
- Database: row-level security, so even a forgotten filter returns nothing from other tenants.
- Keys: per-tenant encryption keys for sensitive fields or files.
- Tests and detection: automated cross-tenant tests in CI; audit logs; alerts on anomalies.
Lab: row-level security in PostgreSQL
You need Docker. The output below is real (PostgreSQL 16).
docker run -d --name rls-lab -e POSTGRES_PASSWORD=labonly postgres:16-alpine
docker exec -it rls-lab psql -U postgres
Set up two roles (an owner for migrations, a separate role for the application), a shared table and a policy:
-- 1. One role owns the schema (migrations); the application uses another
CREATE ROLE app_owner LOGIN PASSWORD 'labonly';
CREATE ROLE app_user LOGIN PASSWORD 'labonly';
CREATE SCHEMA app AUTHORIZATION app_owner;
GRANT USAGE ON SCHEMA app TO app_user;
SET ROLE app_owner;
-- 2. A shared table: every row carries its tenant
CREATE TABLE app.identities (
id bigserial PRIMARY KEY,
tenant_id text NOT NULL,
email text NOT NULL
);
INSERT INTO app.identities (tenant_id, email) VALUES
('acme', 'ana@acme.test'), ('acme', 'bo@acme.test'), ('globex', 'gil@globex.test');
GRANT SELECT, INSERT, UPDATE, DELETE ON app.identities TO app_user;
GRANT USAGE ON SEQUENCE app.identities_id_seq TO app_user;
-- 3. Row-level security: a row is visible and writable only for the current tenant
ALTER TABLE app.identities ENABLE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON app.identities
USING (tenant_id = current_setting('app.tenant_id', true))
WITH CHECK (tenant_id = current_setting('app.tenant_id', true));
RESET ROLE;
Now connect as the application (in psql: \c postgres app_user) and try it:
-- A. No tenant set: nothing is visible (fails closed)
SELECT * FROM app.identities;
id | tenant_id | email
----+-----------+-------
-- B. Tenant acme, for this transaction only
BEGIN; SET LOCAL app.tenant_id = 'acme'; SELECT * FROM app.identities; COMMIT;
id | tenant_id | email
----+-----------+---------------
1 | acme | ana@acme.test
2 | acme | bo@acme.test
-- C. acme explicitly asks for globex's rows
BEGIN; SET LOCAL app.tenant_id = 'acme';
SELECT * FROM app.identities WHERE tenant_id = 'globex'; COMMIT;
id | tenant_id | email
----+-----------+-------
-- D. acme tries to write a row into globex
BEGIN; SET LOCAL app.tenant_id = 'acme';
INSERT INTO app.identities (tenant_id, email) VALUES ('globex', 'x@acme.test');
ERROR: new row violates row-level security policy for table "identities"
-- E. A buggy DELETE without WHERE, as acme
BEGIN; SET LOCAL app.tenant_id = 'acme'; DELETE FROM app.identities; COMMIT;
DELETE 2
-- F. globex's data survived
BEGIN; SET LOCAL app.tenant_id = 'globex'; SELECT * FROM app.identities; COMMIT;
id | tenant_id | email
----+-----------+-----------------
3 | globex | gil@globex.test
Step E is the point of the lab: the bug deleted only the current tenant's rows. Without RLS it would have deleted every tenant's data.
The traps
-- G. Connected as app_owner (the table owner), no tenant set
SELECT * FROM app.identities;
3 | globex | gil@globex.test ← the owner bypasses RLS
-- H. Make the policy apply to the owner too
ALTER TABLE app.identities FORCE ROW LEVEL SECURITY;
SELECT * FROM app.identities;
id | tenant_id | email ← now nothing without a tenant
----+-----------+-------
-- I. Who skips RLS regardless
SELECT rolname, rolsuper, rolbypassrls FROM pg_roles
WHERE rolname IN ('postgres', 'app_owner', 'app_user') ORDER BY 1;
rolname | rolsuper | rolbypassrls
-----------+----------+--------------
app_owner | f | f
app_user | f | f
postgres | t | t ← superusers always bypass
| Trap | Fix |
|---|---|
| The app connects as the table owner | Use a separate role for the app, or FORCE ROW LEVEL SECURITY |
The app connects as a superuser or a BYPASSRLS role |
Never. Give the app a plain role |
SET app.tenant_id (session) with a connection pool |
Use SET LOCAL inside a transaction, so the setting dies with it |
Forgetting the true in current_setting(..., true) |
Without it, an unset tenant raises an error instead of returning nothing; either is safe, just be consistent |
| Background jobs and admin tools | They also need a tenant per unit of work, or a separate, audited role |
| Policies on some tables only | Check in CI that every table with a tenant_id column has RLS enabled |
| Performance | Index tenant_id (usually first in composite indexes); the policy becomes an ordinary filter |
Clean up: docker rm -f rls-lab.
Shared tables, schema per tenant or database per tenant?
| Shared tables + RLS | Schema per tenant | Database per tenant | |
|---|---|---|---|
| Tenants per database | Millions | Hundreds to a few thousand | One |
| Migrations | Once | Once per schema (automate and parallelise) | Once per database |
| Per-tenant backup and restore | Hard (filter by tenant) | Medium | Easy |
| Moving a tenant (lesson 4) | Copy filtered rows | Copy one schema | Copy one database |
| Noisy neighbours | Shared everything | Shared server | Separate (if separate servers) |
| Typical use | Free and standard tiers | Mid-size B2B | Enterprise and regulated tiers |
Many products combine them: shared tables for small tenants, a dedicated database for enterprise tenants, with the routing layer (lesson 3) knowing which is which.
Per-tenant encryption keys
- Envelope encryption: data is encrypted with data keys, which are encrypted by a per-tenant key in a key service (AWS KMS, Azure Key Vault, HashiCorp Vault).
- A leaked data key exposes one tenant, not all of them.
- Crypto-shredding: at offboarding, destroying the tenant's key makes its data unreadable everywhere, including in backups you can't easily edit.
- Customer-managed keys (BYOK): enterprise tenants keep their key in their own account and can revoke it.
- Costs: key service limits and latency, so cache data keys briefly; a key-rotation process.
Testing for leaks
- Cross-tenant tests in CI: create tenants A and B, then, as A, try every API with B's IDs; every call must return 404 or 403, never B's data.
- Canary tenants: marker data in a test tenant; alert if it ever appears in another tenant's responses or exports.
- Audit logs: tenant ID, user, action and object for every data access.
- Schema checks: a CI rule that fails if a new table has a
tenant_idcolumn but no RLS policy.
Try it: extend the lab
- Add a second table
app.roles (tenant_id, name)and forget the policy. Show that acme can read globex's roles, then fix it. - As
app_user, runSET app.tenant_id = 'globex';(no LOCAL), then start a new transaction without setting a tenant. What do you see, and why is that dangerous with a connection pool? - Create an index on
(tenant_id, email)and compareEXPLAINoutput before and after for a tenant's query.
Going deeper
- Some teams set the tenant in a database function called at the start of every transaction by the data-access layer, and reject queries that arrive without one.
- Views and functions can leak across tenants if they run with the definer's rights; review
SECURITY DEFINERfunctions carefully. - Search indexes, caches, object storage, analytics pipelines and logs need tenant isolation too: prefix keys and paths with the tenant ID and filter every read.
Recap
- Data isolation needs layers: verified tenant claim, tenant-aware code, database row-level security, per-tenant keys, tests.
- RLS makes the database filter every statement, including a buggy
DELETE, by the current tenant. - Watch the traps: owners and superusers bypass RLS, and session settings leak through connection pools: use a plain role and
SET LOCAL. - Choose shared tables, schema per tenant or database per tenant by tier; add per-tenant keys for damage limits and crypto-shredding.
This site is a public version of my personal engineering knowledge hub. It intentionally excludes confidential company information and internal operational details.