Introduction
Every multi-tenant application eventually faces the same uncomfortable question: how confident are you that a single missing WHERE tenant_id = ... clause will never expose one customer's data to another? Application-level filtering is easy to write and easy to forget. It also has a failure mode that is impossible to test exhaustively, because every new query, background job, raw SQL snippet, and ad-hoc reporting script is another opportunity to break isolation silently.
PostgreSQL row level security (RLS) moves that guarantee into the database engine. Instead of trusting every query to remember its filter, you declare a policy once and Postgres attaches the predicate to every statement that touches the table. A developer who forgets the tenant filter cannot leak data, because the missing filter is supplied by the database itself.
This guide is a hands-on implementation walkthrough. You will learn how RLS actually works, how to propagate tenant context through a connection pool safely, how to write policies that fail closed, what performance costs to expect, and the deployment details that trip up teams in production. The examples use PostgreSQL 15+ and Node.js with pg, but the SQL layer applies identically to Prisma, Drizzle, TypeORM, Django, Laravel, and any other stack that speaks Postgres.
By the end, you will have a design where tenant isolation is a database invariant rather than a code review checklist item.
Table of Contents
- Introduction
- Core Concepts
- Architecture Overview
- Step-by-Step Guide
- Real-World Examples
- Production Code Examples
- Comparison Table: Isolation Strategies
- Best Practices
- Common Mistakes
- Performance Tips
- Security Considerations
- Deployment Notes
- Debugging Tips
- FAQ
- Conclusion
Core Concepts
Row level security is a per-table feature that changes how the query planner resolves statements. When RLS is enabled on a table, Postgres adds a hidden predicate to every SELECT, UPDATE, DELETE, and INSERT ... RETURNING against that table based on the policies you have defined for the role executing the statement. If no policy matches, the result set is empty — not an error, just nothing.
Policies
A policy is a named rule attached to a table that describes which rows a role may see or modify. A policy has four moving parts: the operation it applies to (or ALL), the roles it applies to, a USING expression, and a WITH CHECK expression. Multiple permissive policies for the same operation are combined with OR, which is how you express things like "the owning tenant or a platform admin". Restrictive policies, declared with AS RESTRICTIVE, are combined with AND and act as additional guards.
USING versus WITH CHECK
This distinction is the single most misunderstood part of RLS. USING decides which existing rows a statement is allowed to see or touch. WITH CHECK validates the row values that a statement is about to write. For a SELECT, only USING matters. For a DELETE, only USING matters. For an INSERT, only WITH CHECK matters. For an UPDATE, both matter: USING selects the rows that may be updated and WITH CHECK validates the new row after the update. If you define only USING on an update policy, Postgres reuses the USING expression as the check for the new row, which is usually what you want for tenant columns you never change.
Roles and the runtime user
RLS evaluates policies against the current user of the session, which is normally the role in your connection string. This is why a multi-tenant application should connect as a dedicated low-privilege role such as app_runtime that owns no tables and has no BYPASSRLS attribute. Table owners, superusers, and any role granted BYPASSRLS skip policies entirely unless the table is marked FORCE ROW LEVEL SECURITY.
Session state as tenant context
Policies need to know which tenant the request belongs to. The portable way to pass that information is a namespaced session setting, for example app.tenant_id, written with SET LOCAL or set_config(name, value, is_local) at the start of a transaction. Because it is local to the transaction, the value is discarded automatically at commit or rollback, and the pooled connection cannot carry stale tenant state into the next request.
Fail closed by construction
When current_setting('app.tenant_id', true) is called with the second argument set to true, Postgres returns NULL instead of raising an error if the setting was never written. Comparing a column against NULL yields NULL, which is not true, so the policy hides every row. That behaviour is deliberate and valuable: forgetting to set tenant context results in an empty dataset, never an accidental cross-tenant read.
The planner's security barrier
From the planner's perspective, RLS predicates are a security barrier. The planner cannot push conditions from inside a subquery or a function out through the policy expression, and it cannot reorder around it. This is exactly what makes RLS trustworthy, and it is also the source of most performance surprises, which is why the indexing and plan-caching discussion later in this guide matters.
Architecture Overview
A production RLS architecture has four layers that must all agree with each other.
Layer one — identity. Authentication resolves a request to a user, and that user record carries a non-null tenant_id. The tenant identifier is never read from a request body, query string, or client-supplied header. It comes from the verified session or token claims only.
Layer two — the request wrapper. A thin database helper opens a transaction, writes the tenant identifier into app.tenant_id with set_config(..., true), hands the transaction-scoped client to the caller, and commits or rolls back. Everything that touches tenant data flows through this helper — HTTP handlers, queue workers, cron jobs, webhooks, admin tools.
Layer three — the policies. Each tenant-scoped table has policies for SELECT, INSERT, UPDATE, and DELETE that compare the row's tenant_id column to the session setting. Tables are marked FORCE ROW LEVEL SECURITY so that even the owning migration role is subject to them.
Layer four — the database role. The application connects as app_runtime, which has USAGE on the schema, table-level SELECT/INSERT/UPDATE/DELETE grants, and nothing else. Migrations run as a separate owner role. This separation means a compromised or buggy application role cannot alter policies, truncate audit tables, or reach system catalogs it does not need.
The critical property of this design is that tenant context is scoped to a transaction, not to a connection or a process. That makes it compatible with short-lived serverless handlers, long-running workers, and connection poolers operating in transaction mode. It also means the isolation guarantee survives framework changes: if a new ORM is introduced next quarter, it inherits the same guarantee as long as it uses the same wrapper.
Step-by-Step Guide
The steps below assume an existing Postgres database and an application that already knows which tenant a request belongs to.
Step 1 — Create a dedicated runtime role
Never run application traffic as the database owner. Create a role with no table ownership and no BYPASSRLS, then grant only the DML privileges it needs.
CREATE ROLE app_runtime LOGIN PASSWORD 'change-me-strong' NOSUPERUSER NOCREATEDB NOCREATEROLE NOBYPASSRLS;GRANT USAGE ON SCHEMA public TO app_runtime;GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO app_runtime;ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO app_runtime;GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO app_runtime;Step 2 — Add tenant_id to every tenant-scoped table
RLS needs a column to compare against. Add a non-null tenant_id foreign key to each tenant-owned table, and index it as the leading column of your composite indexes. Tables that are genuinely global, such as country codes or plan definitions, do not need RLS.
CREATE TABLE orders ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), tenant_id uuid NOT NULL REFERENCES tenants(id) ON DELETE CASCADE, customer_email text NOT NULL, total_cents integer NOT NULL CHECK (total_cents >= 0), status text NOT NULL DEFAULT 'pending', created_at timestamptz NOT NULL DEFAULT now());CREATE INDEX orders_tenant_created_idx ON orders (tenant_id, created_at DESC);Step 3 — Enable and force row level security
Enabling RLS is one statement per table. Forcing it is a second statement that closes the owner loophole. Do both, and do them in the same migration so no window exists where a table is visible without protection.
ALTER TABLE orders ENABLE ROW LEVEL SECURITY;ALTER TABLE orders FORCE ROW LEVEL SECURITY;Step 4 — Write one policy per operation
Explicit per-operation policies are easier to audit than a single FOR ALL policy, because each one states its intent. The pattern below reads the tenant from a stable helper function, which we define in the next step.
CREATE POLICY orders_select ON orders FOR SELECT TO app_runtime USING (tenant_id = app.current_tenant_id());CREATE POLICY orders_insert ON orders FOR INSERT TO app_runtime WITH CHECK (tenant_id = app.current_tenant_id());CREATE POLICY orders_update ON orders FOR UPDATE TO app_runtime USING (tenant_id = app.current_tenant_id()) WITH CHECK (tenant_id = app.current_tenant_id());CREATE POLICY orders_delete ON orders FOR DELETE TO app_runtime USING (tenant_id = app.current_tenant_id());Step 5 — Wrap the session variable in a STABLE function
Calling current_setting() directly inside every policy works, but wrapping it in an immutable-looking accessor marked STABLE gives the planner a value it can evaluate once per query as an initplan rather than once per row. It also centralises the NULLIF guard so an empty-string setting cannot cause a cast error.
CREATE SCHEMA IF NOT EXISTS app;CREATE OR REPLACE FUNCTION app.current_tenant_id()RETURNS uuidLANGUAGE sqlSTABLEAS $$ SELECT NULLIF(current_setting('app.tenant_id', true), '')::uuid;$$;Because the function returns NULL when the setting is absent, and because tenant_id = NULL is never true, the policy denies everything by default. That is the fail-closed behaviour you want.
Step 6 — Set tenant context inside a transaction
At the start of every unit of work, call set_config('app.tenant_id', $1, true) with parameter binding. Never interpolate the identifier into SQL text. The third argument makes the setting transaction-local, so it disappears at commit.
BEGIN;SELECT set_config('app.tenant_id', '3f8c1b1e-6f0a-4c0e-9a51-4d9d4c7a2b10', true);SELECT id, total_cents FROM orders ORDER BY created_at DESC LIMIT 20;COMMIT;Step 7 — Verify with a role switch
Before shipping, prove the policy works by switching to the runtime role and confirming that a query for another tenant returns nothing, and that an insert with a foreign tenant_id is rejected.
BEGIN;SET LOCAL ROLE app_runtime;SELECT set_config('app.tenant_id', '3f8c1b1e-6f0a-4c0e-9a51-4d9d4c7a2b10', true);SELECT count(*) FROM orders; -- only this tenant's rowsINSERT INTO orders (tenant_id, customer_email, total_cents)VALUES ('99999999-9999-9999-9999-999999999999', 'x@example.com', 100); -- must failROLLBACK;If that insert succeeds, your policy is missing a WITH CHECK, or you are still connected as the owner. Both are common and both are serious.
Real-World Examples
B2B SaaS with shared schema. A project management tool stores every workspace's projects, tasks, and comments in shared tables. Workspace isolation is enforced by RLS, and a background worker that sends digest emails iterates over tenants, opening one transaction per tenant. If the worker crashes halfway, no email is sent with another workspace's task list, because the query that fetched the tasks could not see them.
Regulated fintech reporting. An analyst-facing dashboard needs cross-tenant aggregate numbers but must never expose individual customer rows. The application role has RLS with tenant policies plus a restrictive policy that denies raw reads from the analyst service role entirely. Analysts query a separate SECURITY DEFINER view that returns only pre-aggregated metrics, and the definer function itself validates the caller's entitlements before running.
Support tooling with elevation. Customer support staff need temporary read access to a specific tenant while a ticket is open. Rather than granting a BYPASSRLS role, the tool writes both app.tenant_id and app.support_audit_id into the session, and an additional permissive policy on audit-logged tables permits reads when the audit identifier is present. Every such session is written to an append-only audit table that the runtime role can insert into but not modify.
User-level privacy inside a tenant. A healthcare tenant wants clinical notes visible only to the assigned clinician. The policy combines tenant scoping with a row-owner check: tenant_id = app.current_tenant_id() AND (created_by = app.current_user_id() OR app.has_role('clinical_lead')). The same mechanism scales from tenant isolation down to per-record permissions without changing the architecture.
Production Code Examples
The SQL above only helps if every query path uses it. The following examples show the transaction wrapper and how to integrate it with common stacks.
A Node.js transaction wrapper
const { Pool } = require('pg');const pool = new Pool({ connectionString: process.env.DATABASE_URL, max: 20, idleTimeoutMillis: 30_000, statement_timeout: 10_000,});const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;async function withTenant(tenantId, work) { if (typeof tenantId !== 'string' || !UUID_RE.test(tenantId)) { throw new Error('Invalid tenant identifier'); } const client = await pool.connect(); try { await client.query('BEGIN'); await client.query('SELECT set_config($1, $2, true)', [ 'app.tenant_id', tenantId, ]); const result = await work(client); await client.query('COMMIT'); return result; } catch (err) { try { await client.query('ROLLBACK'); } catch (rollbackErr) { err.rollbackError = rollbackErr.message; } throw err; } finally { client.release(); }}module.exports = { pool, withTenant };Three details matter here. The identifier is validated before it reaches the database, so a malformed value cannot produce a confusing cast error inside a policy. set_config is parameterised, so the tenant identifier is never concatenated into SQL. And client.release() runs in a finally block, so a thrown error cannot leak a connection with an open transaction.
Express route using the wrapper
const express = require('express');const { withTenant } = require('./db');const app = express();app.get('/api/orders', async (req, res, next) => { const tenantId = req.user?.tenantId; if (!tenantId) return res.status(401).json({ error: 'unauthorized' }); try { const orders = await withTenant(tenantId, async (client) => { const { rows } = await client.query( 'SELECT id, customer_email, total_cents, status, created_at FROM orders ORDER BY created_at DESC LIMIT 50' ); return rows; }); res.json({ orders }); } catch (err) { next(err); }});Notice that the query has no tenant filter. It does not need one, and adding one would be redundant. The tenant predicate arrives from the policy, which means a developer writing a new endpoint cannot forget it.
Prisma interactive transaction
import { PrismaClient } from '@prisma/client';const prisma = new PrismaClient();export async function withTenant(tenantId, work) { return prisma.$transaction( async (tx) => { await tx.$executeRaw`SELECT set_config('app.tenant_id', ${tenantId}, true)`; return work(tx); }, { timeout: 15_000, maxWait: 5_000 } );}const orders = await withTenant(tenantId, (tx) => tx.order.findMany({ orderBy: { createdAt: 'desc' }, take: 50 }));The $executeRaw tagged template binds the tenant identifier as a parameter, so this remains injection-safe. The setting is written inside an interactive transaction, which Prisma pins to a single connection for its duration, so the SET LOCAL semantics hold.
Worker loop that processes many tenants
const { withTenant } = require('./db');async function runDigestForAllTenants(tenantIds) { for (const tenantId of tenantIds) { try { await withTenant(tenantId, async (client) => { const { rows } = await client.query( 'SELECT id, customer_email FROM orders WHERE status = $1 LIMIT 100', ['pending'] ); if (rows.length === 0) return; await sendDigest(tenantId, rows); }); } catch (err) { logger.error({ tenantId, err: err.message }, 'digest failed'); } }}Each tenant gets its own transaction, so one tenant's failure cannot roll back another's work, and no loop iteration can read another tenant's rows even if the query text is identical.
Automated isolation test
const assert = require('node:assert/strict');const { withTenant } = require('./db');test('tenant A cannot read tenant B orders', async () => { const tenantBOrderId = await createOrderAsTenantB(); const rows = await withTenant(TENANT_A_ID, (client) => client.query('SELECT id FROM orders WHERE id = $1', [tenantBOrderId]) .then((r) => r.rows) ); assert.equal(rows.length, 0);});test('insert with foreign tenant_id is rejected', async () => { await assert.rejects( withTenant(TENANT_A_ID, (client) => client.query( 'INSERT INTO orders (tenant_id, customer_email, total_cents) VALUES ($1, $2, $3)', [TENANT_B_ID, 'x@example.com', 500] ) ) );});Tests like these are cheap to write and they protect the one property that matters most. Run them in CI against a real Postgres instance, not a mock.
Comparison Table: Isolation Strategies
RLS is one of four common ways to isolate tenants in a relational database. Each has a different cost profile, and many mature systems combine two of them.
| Strategy | Isolation guarantee | Operational complexity | Cross-tenant queries | Best suited for |
|---|---|---|---|---|
| Application-level filtering | Depends on every query being correct | Low at first, grows with codebase size | Easy | Small products, single-team codebases, prototypes |
| Row level security | Enforced by the database for all queries | Moderate: policies, role separation, testing | Easy for privileged roles, awkward for the runtime role | Shared-schema SaaS with many tenants and many query paths |
| Schema per tenant | Strong at the namespace level | High: migrations must fan out to every schema | Requires unioning across schemas | Dozens to low hundreds of tenants with compliance needs |
| Database per tenant | Strongest, with separate credentials and backups | Very high: provisioning, pooling, migrations, monitoring | Requires a separate analytics pipeline | Enterprise customers with contractual isolation or residency requirements |
A pragmatic combination used widely in production is shared schema with RLS for the long tail of self-serve tenants, plus database-per-tenant for a small number of enterprise contracts. The application code can stay identical because the tenant context mechanism does not change.
Best Practices
- Force RLS on every tenant table.
ENABLEplusFORCEcloses the owner loophole. WithoutFORCE, the owner role silently ignores every policy you wrote. - Separate the owner and runtime roles. Migrations and application traffic should never share credentials. This single decision contains the blast radius of most application bugs.
- Write explicit policies per operation. A single
FOR ALLpolicy hides intent and makes auditing harder. Four short policies are easier to review than one long one. - Always pair tenant policies with a
WITH CHECK. A policy that filters reads but allows writing rows with an arbitrarytenant_idis worse than no policy, because it looks secure. - Keep tenant context transaction-local. Use
set_config(name, value, true)orSET LOCAL. Never use a plainSETon a pooled connection. - Validate identifiers before they enter SQL. A malformed uuid produces a cast error deep inside a policy, which surfaces as an opaque 500 for the whole request.
- Test isolation as a first-class suite. Every new tenant-scoped table needs a cross-tenant read test and a cross-tenant write test.
- Document the tables that are deliberately global. A short list of shared reference tables in your migration README prevents accidental policy gaps later.
Common Mistakes
Enabling RLS but forgetting to grant privileges. A policy narrows access; it does not grant it. If the runtime role has no SELECT grant on the table, queries fail with a permission error that looks nothing like an RLS problem. Both layers are required.
Granting BYPASSRLS to the application role to fix a bug. This is the fastest way to silently disable your entire isolation model. A role with BYPASSRLS is not an RLS role; it is an unrestricted role wearing a misleading name.
Using a plain SET instead of SET LOCAL. On a pooled connection, a plain SET persists after the transaction ends. The next request that reuses that connection inherits the previous request's tenant and can read its data. This is the most dangerous RLS mistake because it only appears under load.
Forgetting FORCE ROW LEVEL SECURITY. In development, engineers often connect as the table owner, where policies are ignored. Everything appears to work until production traffic hits the runtime role and every query returns different results.
Writing policies that reference unindexed columns. A policy on owner_email = current_setting('app.email') forces a scan of every row in the table before filtering. Policies should key on well-indexed columns, and in tenant systems that almost always means the leading column of the primary composite index.
Assuming views and materialized views are protected. A regular view runs with the permissions of its owner unless you set security_invoker, which can bypass RLS on the underlying tables. Materialized views have no RLS at all. Either avoid exposing them or route access through functions that enforce the same rules.
Skipping the migration window. Adding a non-null tenant_id to a large existing table requires a backfill, and adding RLS before the backfill completes locks out rows. Plan the sequence: add the column, backfill, add the constraint, enable RLS.
Performance Tips
RLS adds a predicate to every query, so it affects plans. In practice the overhead is small when the policy is written well, and severe when it is not.
Index the tenant column first. A composite index beginning with tenant_id lets the planner satisfy both the policy predicate and your business filters in one index scan. On an orders table that means (tenant_id, created_at DESC) rather than (created_at DESC).
Wrap the setting accessor in a STABLE function. Using a STABLE SQL function in the policy allows Postgres to treat it as an initplan that is evaluated once per query. Calling current_setting() directly in a complex multi-table query can lead to repeated evaluation as part of the security barrier.
Watch out for correlated subqueries in policies. A policy expression like tenant_id IN (SELECT tenant_id FROM memberships WHERE user_id = app.current_user_id()) is powerful but expensive, because it may run per row. Materialise the user's accessible tenant identifiers in the session, or cache memberships in a small table joined through an indexed column.
Keep transactions short. RLS does not change locking semantics, but because context is transactional, long transactions hold the tenant setting for their duration. A read-only reporting transaction that runs for minutes also pins a connection.
Measure with EXPLAIN (ANALYZE, BUFFERS) as the runtime role. Plans taken as the owner hide the policy predicate entirely. Run the explain inside a transaction that sets the role and the tenant, otherwise you are optimising a different query than the one users execute.
Consider a partial index for hot tenants. If a few tenants dominate row counts, indexes on (tenant_id, created_at) already handle it. If you have specific query shapes for large tenants, partial indexes filtered by tenant are worth benchmarking rather than assuming.
Security Considerations
Never trust client-supplied tenant identifiers. The tenant must come from the authenticated session, and the wrapper should refuse any identifier that is not a valid uuid belonging to a tenant the user is a member of. RLS is a backstop, not a substitute for authorisation.
Protect the SECURITY DEFINER functions you do write. A definer function runs with the owner's privileges, so it can bypass RLS by design. Pin search_path explicitly inside the function body, revoke EXECUTE from PUBLIC, and grant it only to the roles that need it. An unpinned search path in a definer function is a well-known privilege escalation vector.
Avoid tenant identifiers in URLs and logs. Log the tenant id for debugging, but treat it as sensitive metadata. Structured logs with per-tenant retention policies make incident response much easier.
Audit the policy surface, not just the code. Query pg_policies in CI and fail the build if a table that should be tenant-scoped has no policies, or if a policy grants access to PUBLIC. Policy drift is invisible in application repositories because policies live in the database.
Encrypt at rest and in transit anyway. RLS prevents logical leakage through queries. It does not protect against a stolen backup, an exposed replica, or a compromised credential. TLS to the database plus storage encryption remain mandatory.
Review replication and read replicas. RLS applies to queries, and policy evaluation follows the role used for the query, including on replicas. Confirm that read-only services connect with the same restricted role rather than a superuser connection kept for convenience.
Deployment Notes
Ship policies with migrations. Keep table creation, RLS enablement, and policy definitions in the same migration file. Splitting them across releases creates windows where a table exists without protection.
Order migrations carefully on existing tables. For a large table: add a nullable tenant_id, backfill in batches, add the foreign key with NOT VALID then VALIDATE CONSTRAINT, set NOT NULL after the backfill, then enable and force RLS. Each step is independently reversible, which matters during an incident.
Use a distinct connection string per role. Application runtime, migration runner, analytics, and admin tooling should each have their own credentials in your secret manager. Never reuse the migration credential for application traffic.
Check pooler compatibility. Transaction-mode connection poolers such as PgBouncer are compatible with SET LOCAL and set_config(..., true) because the setting is scoped to the transaction. Session-mode pooling is also fine. The unsafe combination is a plain SET with transaction-level pooling, because the statement may execute on a different backend than the one the setting landed on.
Verify the role after deploy. Add a startup assertion that queries SELECT current_user, current_setting('is_superuser') and fails loudly if the application is unexpectedly connected as a superuser or a BYPASSRLS role. This has caught real production misconfigurations.
Plan a maintenance window for policy changes. Adding a policy takes a lock on the table. On busy tables, use CREATE POLICY with awareness of the brief lock, and test the timing against a production-sized dataset.
Debugging Tips
Symptom: every query returns zero rows. The tenant setting is missing or NULL. Confirm inside the same transaction with SELECT current_setting('app.tenant_id', true);. If it returns NULL, the wrapper was bypassed — check for a code path that grabbed a raw pool client.
Symptom: queries work in development, fail in production. You are probably connected as the table owner locally. Compare current_user and session_user in both environments, and confirm FORCE ROW LEVEL SECURITY is set.
Symptom: inserts fail with a policy violation. Read the error text, which names the policy and the table. Then inspect the policy's WITH CHECK: it usually compares against a tenant value the client sent rather than the session value.
Symptom: intermittent cross-tenant reads under load. Classic plain-SET leakage. Search the codebase for SET app. and set_config without the true third argument, and for any code that sets the tenant outside a transaction block.
Symptom: slow queries after enabling RLS. Take EXPLAIN (ANALYZE, BUFFERS) as the runtime role with the tenant set, and compare it to the same query as the owner. A sequential scan in the RLS plan usually means a missing index on tenant_id.
Useful inspection queries. SELECT * FROM pg_policies WHERE tablename = 'orders'; lists your policies. SELECT relname, relrowsecurity, relforcerowsecurity FROM pg_class WHERE relnamespace = 'public'::regnamespace; shows which tables are protected. Run both during incident triage before reading application code.
FAQ
Does row level security work with PgBouncer and other connection poolers?
Yes, as long as the tenant context is transaction-scoped. SET LOCAL and set_config('app.tenant_id', $1, true) are discarded at commit or rollback, so a pooled connection never carries another request's tenant. Transaction-mode pooling is safe with this pattern; a plain session-level SET is not.
Why does my query return zero rows even though the data exists?
Almost always because app.tenant_id was not set inside the transaction, so current_setting('app.tenant_id', true) returned NULL and the policy matched nothing. Verify the setting inside the same transaction, and check whether the code path used a raw pool client instead of your tenant-aware wrapper.
Do table owners and superusers bypass row level security?
By default, yes. Superusers and roles with BYPASSRLS always skip policies, and table owners skip them unless you run ALTER TABLE ... FORCE ROW LEVEL SECURITY. That is why forcing RLS and connecting as a non-owner runtime role are both required.
Can I use RLS with Prisma, Drizzle, TypeORM, or Laravel?
Yes, because policies are enforced by Postgres regardless of the ORM. The integration work is limited to making sure every unit of work runs inside a transaction where set_config is called, and that no raw connection bypasses that wrapper. Prisma supports this through interactive transactions with $executeRaw.
Do I need a tenant_id column on every single table?
Only on tables that hold tenant-owned data. Genuinely global reference tables such as countries, currencies, or plan definitions do not need it. Everything else — join tables, audit tables, files, notifications — should carry the tenant identifier and a policy, including tables that are only reachable through another table.
How do I give platform admins cross-tenant read access?
Prefer a separate role with its own permissive policy over granting BYPASSRLS. For example, add a policy that permits access when app.admin_mode is set by a service that has already verified elevated entitlements, and write every such session to an audit table. Never widen the runtime role's policies to accommodate an internal tool.
Does RLS hurt query performance?
In most tenant-scoped workloads the cost is negligible when the policy compares an indexed column against a stable function. Problems appear when policies reference unindexed columns, embed correlated subqueries, or compare against values that are evaluated per row. Measure with EXPLAIN (ANALYZE, BUFFERS) as the runtime role with tenant context set.
Can RLS enforce user-level permissions, not just tenant isolation?
Yes. Policies are arbitrary boolean expressions, so they can combine tenant scoping with ownership checks, role lookups, or sharing rules. Keep the expressions cheap by storing the current user identifier in the session alongside the tenant, and index the columns the policy compares against.
Are views and materialized views protected by RLS?
Not automatically. A regular view executes with its owner's privileges unless you set security_invoker, which can bypass policies on the underlying tables. Materialized views are not subject to RLS at all, because they store their own rows. Expose sensitive data through functions or invoker-rights views that enforce the same rules.
How should I test RLS policies?
Run integration tests against a real Postgres instance using the actual runtime role. For each tenant-scoped table, assert that a tenant cannot read another tenant's rows and cannot insert or update a row with a foreign tenant_id. Also add a CI check that queries pg_policies and fails if a tenant table has no policies.
Conclusion
Row level security is not a feature you enable and forget. It is an architecture decision that moves your most important invariant — tenant isolation — from application code into the database, where it can be enforced consistently across HTTP handlers, queue workers, background jobs, and whatever internal tool someone writes next quarter.
The pieces are small and each one is simple: a dedicated runtime role, a tenant_id column on owned tables, ENABLE plus FORCE ROW LEVEL SECURITY, one explicit policy per operation, a stable helper function, and a transaction wrapper that sets context with set_config(..., true). The discipline is in applying the wrapper everywhere and testing isolation like a product requirement.
Start with a single table. Write the policies, wire one endpoint through the wrapper, and add the two isolation tests. Once that path is green, expanding to the rest of the schema is mostly mechanical — and from that point forward, a missing WHERE clause stops being a data breach waiting to happen and becomes a query that simply returns nothing.