Skip to content

Row-level security for multi-tenant PostgreSQL

Enforce tenant isolation in PostgreSQL with row-level security — policies, FORCE RLS, session variables, performance considerations, and bypass roles.

Multi-tenant SaaS typically hangs every row off a tenant_id column and trusts the application to filter by it on every query. One missed WHERE tenant_id = ? and tenant A reads tenant B’s data. PostgreSQL’s row-level security (RLS) pushes that filter into the database: a policy attached to the table evaluates on every SELECT, INSERT, UPDATE, DELETE, and the user can’t see or change rows the policy excludes. This article covers the production pattern — policies, session-variable-based tenant context, the FORCE option, and the planner cost.

How to verify

Confirm RLS is enabled and look at the policies:

psql -d app -c "SELECT tablename, rowsecurity, forcerowsecurity
                FROM pg_tables WHERE schemaname='public';"
psql -d app -c "SELECT * FROM pg_policies WHERE schemaname='public';"
psql -d app -c "SET app.current_tenant = 'tenant-uuid-here';
                EXPLAIN ANALYZE SELECT * FROM orders LIMIT 5;"

The EXPLAIN should show the policy’s filter inlined into the plan — Filter: (tenant_id = current_setting('app.current_tenant')::uuid).

What’s happening

ALTER TABLE foo ENABLE ROW LEVEL SECURITY flips a bit on the table. Once enabled, all queries by non-bypass users see only rows where at least one policy returns true. CREATE POLICY defines what counts — typically a predicate against a session variable, a current_user check, or a join to a role table.

The session variable pattern is the most common in multi-tenant SaaS:

  1. App connects to Postgres (typically through PgBouncer).
  2. App sets SET LOCAL app.current_tenant = 'tenant-uuid' at the start of the transaction.
  3. Every query in that transaction is scoped by RLS to rows where tenant_id = current_setting('app.current_tenant')::uuid.
  4. Transaction commits; the SET LOCAL is gone.

FORCE ROW LEVEL SECURITY is the safety net: by default the table owner bypasses RLS. With FORCE, even the owner is subject to policies. The right default is to enable AND force, then create explicit bypass roles for ops/maintenance.

The procedure

  1. Enable and force RLS on the tenanted table:

    ALTER TABLE orders ENABLE ROW LEVEL SECURITY;
    ALTER TABLE orders FORCE ROW LEVEL SECURITY;
  2. Create the policy:

    CREATE POLICY tenant_isolation ON orders
      USING (tenant_id = current_setting('app.current_tenant', true)::uuid)
      WITH CHECK (tenant_id = current_setting('app.current_tenant', true)::uuid);

    USING controls visibility (SELECT, UPDATE, DELETE row source). WITH CHECK controls what new rows can be inserted/updated to — without it, an attacker could UPDATE a row to a different tenant_id. The second true argument to current_setting returns NULL instead of erroring when unset.

  3. Wire the app:

    BEGIN;
    SET LOCAL app.current_tenant = $tenant_uuid;
    SELECT * FROM orders WHERE created_at > now() - interval '7 days';
    COMMIT;

    SET LOCAL is transaction-scoped — required for transaction-mode pooling. A regular SET leaks across transactions on the same backend, which in PgBouncer transaction mode would send your tenant context to whichever client hits the backend next.

  4. Create a bypass role for ops:

    CREATE ROLE ops_admin BYPASSRLS NOLOGIN;
    GRANT ops_admin TO real_admin_user;

    BYPASSRLS is the escape hatch — use for migrations, audits, and incident response. Never grant to the app user.

  5. Audit policy coverage. A table with RLS enabled but no policy returns zero rows to non-bypass users — easy to miss. A query to find tables in a half-configured state:

    SELECT t.schemaname, t.tablename
    FROM pg_tables t
    LEFT JOIN pg_policies p ON t.schemaname = p.schemaname AND t.tablename = p.tablename
    WHERE t.rowsecurity = true AND p.polname IS NULL;
  6. Test before deploying. Use SET ROLE to simulate the app user and verify both that legitimate queries return data and that cross-tenant queries return nothing.

Common pitfalls

  • Without FORCE, the table owner (often the migration user) bypasses RLS — your tests pass but production is wide open. Always FORCE.
  • current_setting without the second true argument throws if the variable isn’t set, which surfaces during cold-start of an app where the first transaction forgets to SET LOCAL. The true makes the policy evaluate to NULL (false-ish) instead.
  • RLS adds the policy predicate to every query — the planner can usually push it into an index, but only if you have (tenant_id, ...) as a leading index column. Without that index, RLS turns every query into a seq scan. Audit indexes.
  • WITH CHECK is silently optional — leave it off and a tenant can UPDATE rows to belong to another tenant.
  • Logical replication and CDC tools may or may not honour RLS depending on the role they connect as. Check explicitly.

In the engagements we run, RLS plus session-variable tenant context plus a (tenant_id, ...) leading index on every tenanted table is the default for any multi-tenant SaaS we operate. We pair it with Citus sharding for harder isolation when needed, and with pgAudit when regulators require it. The RLS layer is a defence-in-depth — the app should still filter by tenant_id, but RLS guarantees correctness when (not if) the app forgets. For the operating model behind a multi-tenant Postgres footprint, see managed operations.