Nov 27, 2026
Your query forgot the tenant — and the user saw someone else's data
Every multi-tenant SaaS has the same sentence buried in it: WHERE tenant_id = ?. One forgotten clause and one shop sees another shop's customers. The fix isn't more careful code — it's making the database enforce the boundary.
Every multi-tenant app I have built has the same line in it somewhere, repeated a hundred times:
await prisma.orders.findMany({ where: { tenantId } });
It works until the day someone forgets the where. A new endpoint, a report query, a background job, a join where the filter landed on the wrong side. Nothing errors. The page renders, the rows are on it, and the rows belong to somebody else's shop.
That is what makes this bug different from the others I have written about. A slow query complains. A crashed job alerts. A leaked tenant fails silently, and the first person to notice it is usually a customer, not you. The query was valid, the data was real, and the wrong person saw it. By the time you find it in the logs, the damage is already done — you cannot un-show someone another business's orders.
The problem is not that developers are careless. The problem is that the boundary lives in application code, which means it has to be remembered in every query, by every developer, forever, including the ones who join the team next year. A rule that depends on never being forgotten will be forgotten. The fix is to move the boundary somewhere it cannot be forgotten: into the database.
Row-level security: the database filters, not the app
PostgreSQL has had row-level security since version 9.5. A policy on a table is a condition the database applies to every query on that table, including the ones you forgot about. The application stops being the thing that enforces isolation and becomes the thing that says who it is.
ALTER TABLE orders ENABLE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON orders
USING (tenant_id = NULLIF(current_setting('app.tenant_id', true), '')::uuid)
WITH CHECK (tenant_id = NULLIF(current_setting('app.tenant_id', true), '')::uuid);
USING decides which rows a query can see, update, or delete. WITH CHECK decides which rows it can write — it stops one tenant from inserting a row with another tenant's id, or moving one of its own rows into another tenant. Write both, even though Postgres reuses the USING expression for writes when WITH CHECK is missing. Explicit intent is what a test can assert.
The NULLIF part is the bit that matters most. current_setting('app.tenant_id', true) returns an empty string when nothing is set, and NULLIF turns that into NULL. tenant_id = NULL is never true, so a request that forgot to set its tenant sees zero rows — never all rows. A missing tenant fails closed. That is the whole point: the default outcome of a mistake is an empty page, not a leak.
The three traps that undo the policy
A policy on its own is not enough. There are three ways to have RLS enabled and still leak data, and I have seen all three in the wild.
The owner bypasses it. RLS does not apply to the table owner or to superusers. If your app connects with the same user that ran the migrations — which is the default in most small projects — the policy exists and filters nothing. Two fixes, and you want both: FORCE ROW LEVEL SECURITY, which applies the policy to the owner too, and a separate runtime role that cannot escape it.
ALTER TABLE orders FORCE ROW LEVEL SECURITY;
CREATE ROLE app_user LOGIN PASSWORD '...' NOSUPERUSER NOBYPASSRLS;
GRANT SELECT, INSERT, UPDATE, DELETE ON orders TO app_user;
Migrations run as the owner. The app runs as app_user. If a deployment ever wires the wrong connection string in, the app still cannot read across tenants — it can only read what the policy allows. The one exception to watch for is a role with BYPASSRLS, which ignores every policy the way a superuser does. Check it in a startup guard: if the app role is a superuser, can bypass RLS, or owns tables, refuse to boot.
The tenant leaks across requests. Connection pools reuse sessions, and a session setting outlives the request that set it. If you set the tenant with a plain SET, the next request that borrows that connection inherits the previous tenant. Set it transaction-local instead:
await prisma.$transaction(async (tx) => {
await tx.$executeRaw`SELECT set_config('app.tenant_id', ${tenantId}, true)`;
// every query in here sees only this tenant's rows
return tx.orders.findMany();
});
The true in set_config is what makes the value die with the transaction. Without it, one pooled connection quietly serves the wrong shop.
A second policy undoes the first. Permissive policies combine with OR, so adding a broad policy for an admin view silently widens every other policy on the table. Every policy you add is a hole you have to justify. Keep the count small, name them after what they allow, and review them the way you review auth middleware — because that is what they are.
Test it by breaking it on purpose
The tests that matter here are not the ones that check a tenant sees its own rows. Those pass on a broken setup too — an app connecting as the table owner passes every "tenant A sees tenant A" test while leaking everything to tenant B.
Write the negative tests: tenant A must get zero rows from tenant B's table, must fail to insert a row with tenant B's id, and must get zero rows when no tenant is set at all. Then break the schema on purpose — drop a policy, connect as the owner, remove the FORCE — and check the suite notices. A passing isolation suite is weak evidence; a suite that fails when the protection is removed is the evidence. I run the same check on every table that holds tenant data, not just the obvious ones: a cache keyed only by the question, a report table, an audit log — anything that forgot the tenant column leaks the same way a query does.
There is a cost, and it is worth naming honestly. RLS adds planning overhead to every query on a protected table, policies have to be maintained alongside the schema, and debugging a query that returns nothing is harder when the filter is invisible. For a single-tenant app, none of this is worth it. But the moment two businesses share one database, the question is not whether you can afford the overhead. It is whether you can afford the alternative: a boundary that holds only as long as nobody forgets it, on a Friday, in a new endpoint, in a codebase that keeps growing.
The app should say who it is. The database should decide what that identity can see. Everything else is a WHERE clause waiting to be forgotten.