A Postgres row level security multi-tenant setup makes the database add the tenant filter to every query on a table itself, so a forgotten WHERE tenant_id = … can't hand one customer another customer's rows. That guarantee holds only under four conditions:
- The app connects as a non-owner role without BYPASSRLS, on tables with
FORCE ROW LEVEL SECURITY. - Tenant context is set per transaction with
set_config(..., true). - Every policy has both
USINGandWITH CHECK. - Indexes lead with
tenant_id.
Teams usually miss the first one. If your app connects as the owner or migration role, Postgres skips the policies entirely. Nothing errors and every test passes, yet any tenant's data is one bad query from leaking.
RLS is a backstop the database enforces. It doesn't replace authorization in your application code.
Pick the tenancy model first
Shared-schema RLS only makes sense if your tenants belong in one schema. No policy can satisfy a contract that requires a customer's data to live in a specific region or be restorable on its own.
| Model | Isolation | Noisy neighbors | Migrations | Catalog and connections | Per-tenant backup/restore | Residency and compliance | Cost per tenant |
|---|---|---|---|---|---|---|---|
Shared schema, app-only filtering | Weakest: one missing WHERE leaks | Fully shared | One migration | Minimal, one pool | Filtered export only | Hard to prove to auditors | Lowest |
Shared schema + RLS | Enforced by the database per row | Fully shared | One migration | Minimal, one pool | Filtered export only | Auditable policies, one region | Lowest |
Schema per tenant | Strong via grants and search_path | Shared server | Repeated per schema, drift-prone at thousands | Catalog grows with every schema | Per-schema dump | Moderate, still one cluster | Low to moderate |
Database per tenant | Strongest | Separable | Fleet-wide rollout tooling | Pools multiply per database | Native | Any region per tenant | Highest |
App-only filtering, the ORM-scope or acts_as_tenant-style approach, is easier to debug and avoids the pooler pitfalls entirely. But it's only as safe as the least careful query anyone writes. Nile's account of replacing repeated app-level WHERE clauses with RLS shows how that pressure builds as a codebase grows.
For pooled, shared-schema B2B SaaS, RLS is the right default. Keep explicit tenant_id filters in your application queries anyway. They give the planner a plain predicate to work with and make query intent obvious in code review, while RLS catches the query that forgets one.
Choose database-per-tenant when strict data residency or per-tenant restore is a hard requirement. Schema-per-tenant sits in between, and its migration and catalog costs grow with every tenant you add.
Postgres row level security setup for multi-tenant apps
The app has to connect as a role that neither owns the tables nor carries BYPASSRLS. Start with three roles and give table ownership to the migrator alone.
-- Owns every table and runs migrations. The app never logs in as this role.CREATE ROLE app_owner LOGIN;-- The app's runtime role: not the owner, not a member of app_owner, no bypass.CREATE ROLE app_user LOGIN NOBYPASSRLS;-- Optional: jobs and reports only, on a separate connection pool.CREATE ROLE admin_bypass LOGIN BYPASSRLS;
-- Run as app_owner. projects is defined the same way, with UNIQUE (tenant_id, id).CREATE TABLE tasks ( id uuid NOT NULL DEFAULT gen_random_uuid(), tenant_id uuid NOT NULL REFERENCES tenants (id), project_id uuid NOT NULL, title text NOT NULL, deleted_at timestamptz, PRIMARY KEY (id), UNIQUE (tenant_id, id), FOREIGN KEY (tenant_id, project_id) REFERENCES projects (tenant_id, id));
ALTER TABLE tasks ENABLE ROW LEVEL SECURITY; -- no policies yet = default denyALTER TABLE tasks FORCE ROW LEVEL SECURITY; -- applies to the owner too
CREATE POLICY tenant_isolation ON tasks USING (tenant_id = nullif(current_setting('app.tenant_id', true), '')::uuid) WITH CHECK (tenant_id = nullif(current_setting('app.tenant_id', true), '')::uuid);
GRANT USAGE ON SCHEMA public TO app_user;GRANT SELECT, INSERT, UPDATE, DELETE ON tasks TO app_user;REVOKE TRUNCATE ON tasks FROM app_user;
-- Optional (PG 10+): restrictive policies are ANDed with the permissive one.-- CREATE POLICY hide_deleted ON tasks AS RESTRICTIVE FOR SELECT-- USING (deleted_at IS NULL);The composite foreign key means a task can only point at a project in its own tenant. A plain project_id reference wouldn't hold that line, because referential checks run without RLS.
The nullif handles a gotcha that only shows up on pooled connections. current_setting('app.tenant_id', true) returns NULL when the variable has never been set in a session. But once any transaction on that connection has run SET LOCAL, the variable reverts to an empty string afterward, and a bare ''::uuid throws invalid input syntax for type uuid. You end up with a policy that works on fresh connections and errors on reused ones, which is miserable to debug. With nullif, a missing tenant becomes NULL, tenant_id = NULL matches nothing, and the query returns zero rows.
Write WITH CHECK out even though Postgres falls back to the USING expression for a FOR ALL policy that omits it. That fallback stops protecting you once someone splits the policy per command or adds a second permissive policy, say one for shared templates. Permissive policies are ORed together, so a loose or mismatched check on any one of them lets a user insert rows under another tenant's ID or move a row across by updating its tenant_id. Identical expressions in both clauses rule that out.
RLS itself dates to 9.5. A restrictive policy can only narrow what a permissive one already grants, so it fits rules like hiding soft-deleted rows. If you enable hide_deleted, test your soft-delete UPDATE against it before shipping.
Passing tenant context through poolers and ORMs
Every tenant query has to run inside an explicit transaction that sets the tenant before anything touches a table:
BEGIN;SELECT set_config('app.tenant_id', $1, true);-- tenant queriesCOMMIT;Use set_config, not SET. SET is a utility command and can't take bind parameters, so you'd be building SQL strings around a tenant ID and inviting injection. set_config is an ordinary function, so the ID travels as $1.
The third argument, true, is is_local. It behaves like SET LOCAL: the value disappears at COMMIT or ROLLBACK. A plain SET sticks to the session, so the pool hands that connection to the next request still carrying tenant A's ID, and any code path that forgets to set its own context reads tenant A's rows. The local form leaves a forgotten context empty, which your policy turns into zero rows.
PgBouncer in transaction mode is safe only under this pattern. It assigns a server connection per transaction. An autocommit ORM that runs set_config as its own statement sets the value in a one-statement transaction that ends immediately, and the next query may land on a different backend with no tenant set. You get empty results with no error, or another tenant's data if someone used session-level SET.
// Framework-agnostic: adapt pool/client types to your driver.async function withTenant<T>( tenantId: string, // from the verified session, never a client-supplied header handler: (db: DbClient) => Promise<T>,): Promise<T> { const client = await pool.connect(); try { await client.query("BEGIN"); await client.query( "SELECT set_config('app.tenant_id', $1, true)", [tenantId], ); const result = await handler(client); // every tenant query uses this client await client.query("COMMIT"); return result; } catch (err) { await client.query("ROLLBACK"); throw err; } finally { client.release(); }}Each request holds a pooled connection for its full duration, so keep slow external API calls outside the wrapper.
ORMs need the same shape. Prisma's default client runs each query on its own, so use an interactive $transaction that calls set_config through $executeRaw first, or a client extension that wraps every operation that way. In Drizzle, put the work inside db.transaction. Django can use transaction.atomic in middleware; Rails can use an around_action that opens a transaction. Hook and extension APIs change between releases, so check your ORM's current docs before copying a pattern.
On Supabase, policies built on auth.uid() or auth.jwt() read claims the platform sets per request, and they're a reasonable alternative to your own session variable. Giving each tenant its own database role sounds cleaner, but one database user per tenant defeats connection pooling, which is why most pooled SaaS apps stick with the transaction-scoped variable.
What silently bypasses RLS
If app_user can still read every tenant's rows, the cause is usually one of these routes around your policies. Several have nothing to do with how carefully you wrote the policy.
| Cause | What happens | Fix |
|---|---|---|
Superuser or BYPASSRLS role | Policies are skipped entirely, even on forced tables. | Never let the app connect as one. Check SELECT rolsuper, rolbypassrls FROM pg_roles WHERE rolname = current_user; from the app's own connection. |
Table owner | The owner bypasses policies unless the table is forced. | Run ALTER TABLE ... FORCE ROW LEVEL SECURITY, and connect as a non-owner user, as AWS's RLS guidance recommends. |
Views | A view runs with its owner's privileges. A view owned by the migrator or a superuser returns every tenant's rows. | On PG 15+, create views WITH (security_invoker = true) or set that option on existing views. |
SECURITY DEFINER functions | RLS is evaluated as the function owner, not the caller. | Default to SECURITY INVOKER. If you need a definer function, filter on the tenant setting inside it and pin search_path. |
TRUNCATE | It empties the table for every tenant, because RLS doesn't apply. | REVOKE TRUNCATE ON ALL TABLES IN SCHEMA app FROM app_user; |
Foreign key checks | Referential checks ignore RLS, so a child row can point at another tenant's parent. | Use composite keys on (tenant_id, id), like the tasks → projects key in the schema above. |
Unique constraints | A duplicate-key error confirms that a value exists in another tenant. The Postgres docs acknowledge this covert channel. | Scope uniqueness to (tenant_id, …) where the business rules allow it, and use non-guessable keys. |
Querying a partition directly | The partition's own policies apply, not the parent's. | Enable, force and attach the same policy on every partition, or revoke direct access to partitions. |
Keeping policies fast
A tenant policy that compares an indexed tenant_id to a session setting costs almost nothing. Postgres merges the policy into the query's WHERE clause, and the planner treats it like any other equality filter. The cost comes from policies that do more than that comparison.
Membership-style policies are the usual culprit. If the policy runs a subquery against a memberships table to check whether the current user belongs to each row's tenant, every scan becomes a join you never wrote. Functions in a policy can also be re-evaluated per row. Wrap the call in a scalar subquery and the planner computes it once per query:
-- before: the function can run per rowUSING (tenant_id = nullif(current_setting('app.tenant_id', true), '')::uuid)
-- after: evaluated once per queryUSING (tenant_id = (SELECT nullif(current_setting('app.tenant_id', true), '')::uuid))Supabase recommends the same wrapping for auth.uid().
Your own predicates can get in the way too. Postgres applies policy conditions before any user condition that calls a function or operator not marked LEAKPROOF, so that function never sees rows the policy hides; the Postgres row security docs explain the ordering. The side effect is that such a predicate may not be usable as an index condition, and an index you built for it can sit idle.
Make tenant_id the leading column of composite indexes, such as (tenant_id, created_at) or (tenant_id, project_id). Every query carries the tenant filter, so that leading column is always usable, and the explicit WHERE tenant_id = $1 in your app queries hands the planner a plain parameter to match against it.
To check the result, run EXPLAIN as app_user inside a transaction that has set the tenant. A plan captured as a superuser or BYPASSRLS role won't include the policy at all.
Admin access, jobs, and backups
Cross-tenant work belongs on its own connection pool that logs in as admin_bypass. Don't put it on the app pool behind an app.is_admin flag your policies check. That flag lives in the same session state as the tenant ID, so one middleware bug or leaked setting turns an ordinary app connection into an admin one. A separate role with its own credentials confines the risk to the admin tool, reporting job or worker that actually needs it, and you can keep that password out of the web tier and audit its logins separately.
Migrations run as the migrator, which already owns the tables. Backups need similar care: pg_dump sets row_security = off and errors out if RLS would filter any rows, so run it as the owner or a BYPASSRLS role. Bulk imports hit a related wall, since COPY FROM errors on RLS tables for non-bypass roles. Route imports through a bypass job that checks every row's tenant_id before loading, because nothing in the database checks it on this path.
Most jobs don't need bypass at all. A worker handling one tenant's queue can connect as app_user and call set_config inside its transaction, the same way a web request does, and keep full RLS protection.
Testing and rolling out on production
Isolation isn't proven until a test connected the way your app connects tries to read another tenant's data and gets nothing back. Run these tests with app_user's real credentials, through the pooler if you can. A suite that connects as the owner proves nothing, because RLS never runs.
Tests that prove isolation
Seed two tenants, A and B. Open a transaction, call set_config('app.tenant_id', <A>, true), and assert four things:
- Selecting B's rows by ID returns zero rows.
- Inserting a row with B's
tenant_idfails with a row-level security violation. - Updating B's rows affects zero rows, and moving one of A's rows to B fails
WITH CHECK. - With no tenant set, every table returns zero rows rather than an error.
Add one test for pooled leaks: commit a transaction for tenant A, reuse the same connection without setting context, and confirm it sees nothing. pgTAP's is_empty and throws_ok express all of this cleanly, though plain assertions in your app's test runner work too.
Tests only cover the tables you remember to test. Add a CI guard that fails the build if any table with a tenant_id column is missing RLS or FORCE:
SELECT n.nspname AS schema_name, c.relname AS table_name, c.relrowsecurity, c.relforcerowsecurityFROM pg_class cJOIN pg_namespace n ON n.oid = c.relnamespaceJOIN information_schema.columns col ON col.table_schema = n.nspname AND col.table_name = c.relname AND col.column_name = 'tenant_id'WHERE c.relkind IN ('r', 'p') AND n.nspname NOT IN ('pg_catalog', 'information_schema') AND (NOT c.relrowsecurity OR NOT c.relforcerowsecurity);Run it as the migrator, because information_schema.columns hides tables the current role can't access. Any returned row should fail the build, including individual partitions, which carry their own flags.
A safe rollout order
This sequence follows the enable-first, force-later approach. Each step either can't change what the live app sees or can be reversed quickly.
- Backfill
tenant_idon every tenant table, then set itNOT NULL. You're done when a null count returns zero and every child row's tenant matches its parent's. - Add composite indexes and foreign keys. Build the indexes with
CREATE INDEX CONCURRENTLY. Add the FKs asNOT VALID, then runVALIDATE CONSTRAINT. If validation succeeds, no existing row points across tenants. - Create the roles. Check
pg_rolesto confirmapp_userhasrolbypassrls = false, and checkpg_tablesto confirm it owns nothing. - Enable RLS without FORCE and create the policies. The app still connects as the owner, so production behavior shouldn't change; watch error rates to confirm it doesn't. Mark the CI guard's FORCE check as expected to fail until step 6.
- Point staging at
app_user. Run the isolation suite and your normal integration tests. ThenEXPLAINyour hottest queries and confirm they use thetenant_id-leading indexes instead of sequential scans. - Switch production to
app_user, then enable FORCE. The CI guard should now pass cleanly. Watch for policy-violation errors and for endpoints that suddenly return empty results, which usually means a code path skipsset_config. To roll back, point the connection string at the old role while you fix the gap.
Sources
- Row Level Security for Tenants in Postgres · crunchydata.com
- Shipping multi-tenant SaaS using Postgres Row-Level Security · thenile.dev
- CVE 2024 10976 · postgresql.org
- PostgreSQL: Documentation: 18: 5.9. Row Security Policies · postgresql.org
Want more from ScriptHill in Google? Add us as a preferred source



