How do you keep tenants apart when they share one database?
How I let Postgres, not application code, keep tenants apart, so a forgotten tenant filter returns nothing instead of another customer's data: FORCE, non-owner roles, transaction-local settings, fail-closed policies, and tests that prove it.
The verdict, which the rest of this case earns: make the database enforce it, not only your code. With PostgreSQL row-level security (RLS) on every tenant table, FORCE ROW LEVEL SECURITY, an application role that doesn’t own the tables, and the tenant set per transaction, a query that forgets WHERE tenant_id = ? returns nothing instead of another customer’s data. Then prove it with tests that try to read across tenants. For many small tenants this beats a schema or a database per tenant; keep a separate database for the few that need their own region or capacity.
Case file
The case A customer sees someone else’s orders Suspects A careless handler, a rushed review, a new engineer Culprit One missing WHERE tenant_id = ?, with nothing in the database to catch itThe fix RLS with FORCE, a non-owner app role, tenant set per transactionEvidence The blogging platform and multi-tenant-event-driven-ref
The case #
A customer opens their dashboard and sees someone else’s orders. That’s the nightmare in any multi-tenant system, and it takes only one missing WHERE tenant_id = ? to cause it. The bug is easy to write, hard to spot in review, and cannot be rolled back once the data has been seen.
The usual suspects: a careless handler, a rushed review, a new engineer who didn’t know the convention. But blaming people doesn’t close the case. What I love about the solution here is that it turns the most common mistake into the safest one. You stop hoping everyone remembers the filter and let the database remember for you.
I use Postgres row-level security (RLS) so that a forgotten filter returns nothing instead of everything. This case walks through how I set it up in two codebases: the blogging platform I run, and a public reference project, multi-tenant-event-driven-ref. The SQL below is taken from them, trimmed.
Ruling out the alternatives: why RLS, not schema- or database-per-tenant #
The reference repo records this choice in ADR 0001. The short version:
| Shared tables + RLS | Schema per tenant | Database per tenant | |
|---|---|---|---|
| Cost of an extra tenant | About nothing | A schema | An instance |
| Migrations | Run once | Run N times; can drift | Fleet tooling, N times |
| Pooling | One pool | A pool per schema, or a reset search_path |
A pool per database |
| How it fails | A forgotten filter fails closed: the policy still applies | A leaked search_path queries the wrong schema |
Hardest to get wrong; most to operate |
| Pick it when | Many small tenants on the same code | Rarely (see below) | A tenant needs its own region, capacity or restore |
For many small tenants on the same code, shared tables win, and with RLS they win without giving up the safety net. The ADR lists the costs: noisy neighbours share capacity, per-tenant restore and residency need row-level tooling, and isolation depends on the policies being right.
A tenant that later needs its own region or capacity can get its own database behind the same code, with RLS kept as defence in depth (the same move that leads to cells). Schema-per-tenant is the suspect I’d rule out. It multiplies migrations without the operational isolation of a separate database.
The clue people miss: FORCE and a non-owner role #
This is the twist that catches people out. ENABLE ROW LEVEL SECURITY alone does not protect you from your own app. Postgres skips policies for the table owner, for superusers, and for any role with BYPASSRLS. If the app connects as the role that ran the migrations, RLS does nothing for it. The lock is on the door, and the app is holding the master key.
So there are always at least two roles. An owner runs migrations. Services connect as separate roles that own nothing and have no BYPASSRLS. The reference repo creates them like this (db/init/00_roles.sh):
CREATE ROLE orders_owner LOGIN PASSWORD 'owner-dev-only';
CREATE ROLE app_api LOGIN PASSWORD 'api-dev-only' NOBYPASSRLS;
CREATE ROLE app_relay LOGIN PASSWORD 'relay-dev-only' NOBYPASSRLS;
CREATE ROLE app_worker LOGIN PASSWORD 'worker-dev-only' NOBYPASSRLS;
Tenant data tables are then both enabled and forced (db/migrations/0001_init.sql):
ALTER TABLE orders ENABLE ROW LEVEL SECURITY;
ALTER TABLE orders FORCE ROW LEVEL SECURITY;
CREATE POLICY orders_api_select ON orders FOR SELECT TO app_api
USING (tenant_id = app_tenant_id());
CREATE POLICY orders_api_insert ON orders FOR INSERT TO app_api
WITH CHECK (tenant_id = app_tenant_id());
FORCE makes the owner subject to policies too. There is no owner policy on orders, so an owner session sees no orders at all. A test checks exactly that.
FORCE is a choice per table, not a rule. In the reference repo, tenants is not forced, because the owner provisions tenants. In the blogging platform, blogs is not forced, so that an owner-defined lookup function can find a blog by slug (more on that below). In both cases the service roles are not the owner, so the policies still apply to every query they make.
Tenant context: transaction-local, through one helper #
Policies need to know the current tenant. I keep it in a custom setting and read it through a small function:
CREATE FUNCTION app_tenant_id() RETURNS uuid
LANGUAGE sql STABLE AS
$$ SELECT NULLIF(current_setting('app.tenant_id', true), '')::uuid $$;
The app sets it with set_config(..., true). The third argument makes it transaction-local. It disappears at COMMIT or ROLLBACK.
That argument matters because of a quieter suspect: connection pools. A session-level SET app.tenant_id stays on the connection after the request ends. The next request that borrows that connection would start out as the previous tenant. With a transaction-local setting, the next transaction on that connection starts with no tenant.
All tenant queries go through one helper, so nobody sets the context by hand. In the reference API (api/src/db.ts):
await client.query('BEGIN');
await client.query("SELECT set_config('app.tenant_id', $1, true)", [tenantId]);
const result = await fn(client);
await client.query('COMMIT');
The Go worker has the same shape in inTenant, and the blogging platform has inTx, which sets an account id and a blog id in one statement. Where the tenant comes from matters as much as how it is set. In the reference API it comes from a verified JWT claim, never from a path, header or body. In the blogging platform it comes from the session or the host name, never from a form.
The reveal: NULL matches nothing #
Look again at app_tenant_id(). current_setting(..., true) returns NULL or an empty string when the setting is missing. NULLIF(..., '') turns empty into NULL. And tenant_id = NULL is never true.
So a code path that forgets to set the tenant does not see every row. It sees none. Inserts fail the WITH CHECK and error. A malformed value fails the uuid cast and errors too, instead of matching something by accident.
This is the property I care about most, and the one I find genuinely beautiful. SQL’s three-valued logic, so often a source of bugs, becomes the guard. Forgetting is the common bug. With this design, forgetting is safe.
Diagram source
sequenceDiagram
participant API as App (role app_api)
participant PG as PostgreSQL
API->>PG: BEGIN
API->>PG: set_config('app.tenant_id', tenant, true)
API->>PG: SELECT ... FROM orders (filter forgotten)
PG->>PG: policy adds tenant_id = app_tenant_id()
PG-->>API: only this tenant's rows
API->>PG: COMMIT (setting disappears)
API->>PG: SELECT ... FROM orders, no tenant set
PG-->>API: zero rows, NULL matches nothing
Narrow doors: SECURITY DEFINER and column grants #
Some doors have to open. Some lookups must happen before any tenant is known. A public blog page has a slug and needs the blog id. Login has an email and needs a password hash.
In the blogging platform, these are SECURITY DEFINER functions. They run with the owner’s rights and each answers exactly one question:
CREATE FUNCTION resolve_blog(p_slug text) RETURNS uuid
LANGUAGE sql STABLE SECURITY DEFINER SET search_path = public, pg_temp AS
$$ SELECT id FROM public.blogs WHERE slug = lower(p_slug) $$;
CREATE FUNCTION account_for_login(p_email text)
RETURNS TABLE (id uuid, password_hash text)
LANGUAGE sql STABLE SECURITY DEFINER SET search_path = public, pg_temp AS
$$ SELECT a.id, a.password_hash FROM public.accounts a WHERE a.email = p_email::citext $$;
SET search_path = public, pg_temp stops a caller from shadowing a table with their own object. EXECUTE is revoked from PUBLIC and granted only to the app role.
Column-level grants close the rest. The app role can insert an email and password hash, but it can only select id from accounts. Session lookups go through a definer function too. The app role can read token_hash, expires_at and last_seen_at on sessions, but not csrf_token. So even a bug that runs arbitrary SELECTs as the app role cannot dump every password hash (the password storage case covers what those hashes should be) or CSRF token. It can ask about one email or one token hash at a time.
The reference repo uses the same idea per service. The API can insert orders but has no grant to update or delete them. The worker can update only status and processed_at on orders, and cannot insert them. The outbox relay is cross-tenant by design, so it gets its own role. It can read the outbox and update two columns on it, and it has no access to orders.
Testing isolation, not only features #
Policies are code. They need tests that run against a real Postgres, as the service role. Mocks cannot test RLS.
The tests I find most useful, from the reference repo’s rls.test.ts and the blogging platform’s store tests, each try to commit the crime and confirm it fails:
- Unfiltered queries.
SELECT ... FROM orderswith noWHEREreturns only the current tenant’s rows. - No tenant set. Counts are zero and inserts are rejected with a row-level security error.
- Forged tenant on write. Tenant B inserting a row with tenant A’s id fails.
- Pool reuse. On one connection: set the tenant, commit, then query again and see zero rows. The same after a rollback.
await c.query('BEGIN');
await c.query("SELECT set_config('app.tenant_id', $1, true)", [tenantA]);
expect((await c.query('SELECT count(*)::int AS n FROM orders')).rows[0].n).toBeGreaterThan(0);
await c.query('COMMIT');
// Next "request" on the same pooled connection sees nothing.
expect((await c.query('SELECT count(*)::int AS n FROM orders')).rows[0].n).toBe(0);
- Simulated app bugs. In the blogging platform, one test pairs account A with blog B, as if a handler took the blog id from user input. The policies still refuse writes and hide drafts.
- The app role cannot turn it off.
ALTER TABLE ... DISABLE ROW LEVEL SECURITY,DROP POLICY, readingpassword_hash, andCREATE TEMP TABLEmust all fail.SET LOCAL row_security = offmust make the query error, not return unfiltered rows. - Role separation. The relay sees every tenant’s outbox but gets
permission deniedon orders. The owner, underFORCE, sees zero orders.
Investigating the investigators: mutation tests #
A test that never fails might not be testing anything, so test the tests with a mutation test: weaken a policy on purpose and confirm the suite goes red.
For example, change USING (tenant_id = app_tenant_id()) to USING (true), or drop FORCE, or grant the app role BYPASSRLS. Each of these should break at least one test. If a mutation leaves everything green, you have found a gap in the tests, not in the policies. Dropping FORCE is a good example: it only shows up in a test that queries as the owner, which is why the reference repo has one. Neither repo automates this yet. It is the next thing I would add: a CI job that applies a list of known-bad migrations, one at a time, and expects the isolation tests to fail for each.
A false sense of safety: what RLS does not protect against #
RLS guards against missing-filter bugs. It is not a defence against SQL injection.
The tenant setting is only a setting. The app role can call set_config, because it has to. An attacker who can run arbitrary SQL as the app role can call it too, set any tenant id they can guess, and read that tenant’s rows. RLS makes that harder. It does not make it impossible. Parameterised queries are still the defence against injection. The blogging platform’s store layer parameterises every query for that reason.
What RLS and the narrow grants do limit is the blast radius. An attacker cannot disable policies, read password hashes in bulk, or touch tables the role has no grant on.
Other limits worth stating plainly:
- Every new tenant table needs its policy in the same migration. The reference ADR makes this a review checklist item. A table without RLS is wide open to the app role.
- Indexes must lead with the tenant column. Policies add a predicate to every query. Without
(tenant_id, ...)indexes, that predicate costs you scans.
Remember this
ENABLEalone doesn’t bind the owner: useFORCEand a non-owner app role.- Set the tenant transaction-local, so pooled connections start with none.
- NULL matches nothing, so forgetting the tenant returns zero rows, not all of them.
What I’d do differently #
- Automate the mutation tests in CI rather than leave them as a manual check.
- Add a migration lint that fails when a table with a tenant column has no
ENABLEandFORCE, or no policies for the service roles.
None of this replaces careful application code. It means a single forgotten filter is a failed test, not a data leak.
Here the database itself holds the line. A few careful settings, a NULL that matches nothing and a handful of tests, and the scariest bug in multi-tenant software becomes a boring one. Case closed.
Comments
No comments yet.
Sign in to comment. We'll email you a link; no password needed.