How-To Guide

How to Implement Row-Level Security in PostgreSQL

Enforce tenant and owner isolation with PostgreSQL row-level security: define policies, set the session context, and test that unscoped queries cannot leak.

On this page

  1. Introduction
  2. Enable RLS and write policies
  3. Set the session context per request
  4. Grant bypass only deliberately
  5. Test unscoped and cross-tenant access
  6. Common pitfalls
  7. Conclusion

Introduction

Application-level tenant filters depend on every query remembering to include the filter. One missed WHERE, one new endpoint, one raw query added in a hurry, and one tenant sees another’s data. Row-level security moves the filter into the database, where it applies to every query automatically. Even a query that forgets the filter returns only rows the policy allows.

This tutorial implements row-level security for a multi-tenant table: enable it, write policies for each operation, set the tenant in the session, and grant a deliberate bypass only to privileged roles. It ends with tests that connect as a tenant and attempt unscoped reads and cross-tenant writes. The examples use PostgreSQL, which has native row-level security.

Enable RLS and write policies

Enabling row security on a table makes it deny by default: with no policy, a non-owner role sees no rows. Then define policies. A policy is a boolean expression evaluated per row; a row is visible or writable only if a policy allows it. Use FOR SELECT, FOR INSERT, FOR UPDATE, FOR DELETE to scope per operation, and reference a session value such as current_setting(‘app.tenant_id’) in the expression.

Keep policies simple and indexed. The policy predicate is added to every query on the table, so its expression must be cheap and ideally match an index so the planner can use it. tenant_id = current_setting('app.tenant_id')::bigint is a simple equality that an index on tenant_id can serve. Avoid functions or subqueries in the predicate, which run per row and can defeat the index.

ALTER TABLE documents ENABLE ROW LEVEL SECURITY;

CREATE POLICY documents_tenant_select ON documents
  FOR SELECT USING (tenant_id = current_setting('app.tenant_id')::bigint);

CREATE POLICY documents_tenant_insert ON documents
  FOR INSERT WITH CHECK (tenant_id = current_setting('app.tenant_id')::bigint);

CREATE POLICY documents_tenant_update ON documents
  FOR UPDATE USING (tenant_id = current_setting('app.tenant_id')::bigint)
             WITH CHECK (tenant_id = current_setting('app.tenant_id')::bigint);

Set the session context per request

The policy reads a session value, so each request must set it before querying and must not leak it to the next request on a pooled connection. Set it at the start of the request and reset it at the end, or use a transaction-scoped setting with SET LOCAL so it reverts when the transaction ends. A connection pool that reuses connections between requests makes resetting essential, or one request could act under another tenant’s context.

Use a transaction-scoped setting for safety: SET LOCAL app.tenant_id = $1 inside the transaction, so it applies for that transaction and automatically reverts. This pairs with a transaction and a connection pool cleanly. Never set the value from untrusted input without validation; it should come from the authenticated session, not a request header the client controls.

async function withTenant<T>(tenantId: number, fn: (tx: unknown) => Promise<T>): Promise<T> {
  return db.transaction(async (tx) => {
    // transaction-scoped: reverts when the transaction ends, safe with pooling
    await tx.query('SELECT set_config($1, $2, true)', ['app.tenant_id', String(tenantId)]);
    return fn(tx);
  });
}

Grant bypass only deliberately

The table owner bypasses row security by default, and a role can be granted BYPASSRLS. Neither should be the application’s default, because it removes the protection. Run the application under a dedicated role without BYPASSRLS, and reserve bypass for migrations and a narrowly scoped admin path. Every use of bypass should be explicit and logged.

Audit that every tenant table has row security enabled and at least one policy per needed operation. A table that lost its policy, or was created without enabling RLS, silently exposes everything. A query listing tables with row security disabled in a tenant schema makes the gap visible, and a test can assert that no tenant table is unprotected.

-- find tenant tables without row security enabled
SELECT c.relname, c.relrowsecurity
FROM pg_class c
JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE c.relkind = 'r' AND n.nspname = 'public' AND NOT c.relrowsecurity;

Test unscoped and cross-tenant access

Connect as the application role, set the tenant to A, and run a query with no tenant predicate at all; assert it returns only tenant A’s rows. Then attempt to read a specific row belonging to tenant B by id and assert nothing returns. Attempt to insert a row with tenant_id of B and assert the WITH CHECK clause rejects it. Repeat for update and delete. This is the test that proves a forgotten application filter cannot leak.

Also test the pool-reset behavior: run a request as tenant A, return the connection to the pool, run a request as tenant B, and assert the second does not inherit A’s context. With SET LOCAL inside a transaction this holds automatically, but a test documents and enforces it. Finally, assert the admin bypass works only where intended.

psql -d app <<'SQL'
SET app.tenant_id = '1';
SELECT count(*) FROM documents;                       -- only tenant 1 rows
SELECT count(*) FROM documents WHERE tenant_id = 2;   -- expect 0
INSERT INTO documents (tenant_id, title) VALUES (2, 'x');  -- expect policy violation
SQL

Common pitfalls

Running the application as the table owner so RLS is bypassed, forgetting to set the session value so every query returns nothing or acts under a stale tenant, leaving the setting on a pooled connection across requests, policies that call functions or subqueries and defeat the index, and a tenant table created without RLS are the recurring mistakes. A dedicated role, transaction-scoped context, policy audit, and simple indexed predicates address them.

Conclusion

Row-level security moves tenant isolation into the database so a forgotten filter cannot leak. Enable it, write a policy per operation with a simple indexed predicate, set the tenant as a transaction-scoped session value, run the application under a non-owner role, and audit that every tenant table is protected. Self-check by connecting as a tenant and asserting unscoped reads and cross-tenant writes are blocked. Then isolation holds even when application code does not.

Sources: PostgreSQL: Row security policies, PostgreSQL: CREATE POLICY, OWASP: Authorization cheat sheet.

FAQ

Does RLS protect against SQL injection?
It limits the damage. An injected query still runs under the current session's policies, so it cannot read other tenants' rows even if it ignores the application's tenant filter. RLS is a strong backstop but not a substitute for parameterized queries.
Why did my query return nothing after enabling RLS?
The table owner bypasses RLS by default, but an application role that is not the owner sees only rows its policies allow. If the session variable the policy reads is unset, the predicate is NULL and no rows match. Set the context per request.

Related Examples