Skip to main content
Postgres Row-Level Security for Multi-Tenant SaaS: A Practical Guide
Back to Blog

Postgres Row-Level Security for Multi-Tenant SaaS: A Practical Guide

One forgotten WHERE tenant_id clause can leak a customer's data. How to use PostgreSQL Row-Level Security to enforce tenant isolation in the database, with safe connection pooling, ORMs, performance tips and tests.

LuminaryEra Editorial
November 21, 202615 min read18 views

The short answer: PostgreSQL Row-Level Security (RLS) lets the database itself enforce which rows each tenant can see and change, so a forgotten WHERE tenant_id = … in application code can no longer leak another customer's data. Enable RLS on every tenant table, write policies that compare tenant_id with a per-request setting, connect as a role that doesn't own the tables (or use FORCE ROW LEVEL SECURITY), set the tenant with SET LOCAL or set_config(…, true) inside a transaction so it can't leak across pooled connections, and index tenant_id. Then test that cross-tenant access fails.

Most multi-tenant SaaS products start the same way. Every table gets a tenant_id column, every query gets a WHERE tenant_id = $1, and everyone agrees to be careful. It works, right up until the day someone adds a new report, a new admin endpoint or a new background job and forgets the filter. Nothing breaks. Tests pass. And one customer can now see another customer's invoices.

That class of bug is among the most damaging a SaaS company can ship, and it's hard to prevent with code review alone, because the mistake is an absence: a missing line, not a wrong one. Row-Level Security moves the rule into the database. Instead of trusting every query to remember the filter, Postgres applies it to every query automatically, including the ones written in a hurry next year.

This guide covers how RLS works, how to set it up for a typical tenant model, the connection-pooling trap that catches most teams, performance, testing, and the situations where RLS is the wrong tool. Examples are plain SQL with small application snippets in TypeScript.

The rules of Row-Level Security

Normally, Postgres permissions are all-or-nothing per table: if a role can SELECT from a table, it sees every row. RLS adds a second layer. Once you enable it on a table, every query against that table is filtered through policies: boolean expressions that decide, row by row, whether the current user may see or modify that row.

A few rules from the PostgreSQL documentation on row security are worth knowing before you write a single policy:

  • Default deny. If RLS is enabled on a table and no policy applies, no rows are visible or modifiable. Forgetting a policy fails closed, not open.
  • Superusers and BYPASSRLS roles always bypass RLS. Your application must not connect as one of them.
  • Table owners normally bypass RLS too, unless the table is altered with FORCE ROW LEVEL SECURITY. This is the most common reason "RLS isn't working."
  • USING and WITH CHECK do different jobs. USING decides which existing rows a command can see or act on; WITH CHECK decides which rows an INSERT or UPDATE is allowed to write. A policy with only USING implicitly applies the same expression as its WITH CHECK.
Diagram of a request flowing through Row-Level Security: the app opens a transaction, sets app.tenant_id with SET LOCAL, runs an ordinary query with no tenant filter, and Postgres applies the tenant policy so only that tenant's rows are returned; a second tenant's rows are filtered out by the database

Setting it up for a tenant model

Take a typical schema where every tenant-owned table has a tenant_id. The application will tell Postgres which tenant the current request belongs to using a custom setting, here called app.tenant_id, and the policies will compare against it.

-- A role for the application that does NOT own the tables and can't bypass RLS.
CREATE ROLE app_user LOGIN PASSWORD '...' NOSUPERUSER NOBYPASSRLS;
GRANT SELECT, INSERT, UPDATE, DELETE ON projects, invoices TO app_user;

ALTER TABLE projects ENABLE ROW LEVEL SECURITY;
ALTER TABLE invoices ENABLE ROW LEVEL SECURITY;

-- One policy per table: rows are visible and writable only for the current tenant.
CREATE POLICY tenant_isolation ON projects
  USING (tenant_id = current_setting('app.tenant_id', true)::bigint)
  WITH CHECK (tenant_id = current_setting('app.tenant_id', true)::bigint);

CREATE POLICY tenant_isolation ON invoices
  USING (tenant_id = current_setting('app.tenant_id', true)::bigint)
  WITH CHECK (tenant_id = current_setting('app.tenant_id', true)::bigint);

The second argument to current_setting, true, means "return null instead of raising an error if the setting is missing." Because tenant_id = NULL is never true, a request that forgot to set the tenant sees nothing. That's the behaviour you want: a bug produces empty results, not someone else's data.

The explicit WITH CHECK stops a subtle attack: without it, a tenant could insert a row with another tenant's tenant_id, or update one of their own rows to move it to another tenant. With it, any write that would produce a row outside the current tenant is rejected.

If your migrations role owns the tables

Many setups run migrations as the same role the application uses, which means the application owns the tables and silently bypasses RLS. Fix it in one of two ways. Preferably, use separate roles: a migration role that owns the schema and an application role that only has the grants it needs. Alternatively, force RLS for owners too:

ALTER TABLE projects FORCE ROW LEVEL SECURITY;
ALTER TABLE invoices FORCE ROW LEVEL SECURITY;

Check which role your application actually connects as. Managed database providers often give you an owner role by default, and it's easy to deploy with it without noticing.

Setting the tenant per request, safely

Here's the trap that catches most teams. The obvious way to tell Postgres the tenant is SET app.tenant_id = '42'. But SET lasts for the whole database session, and with connection pooling, a session is shared by many requests one after another. If one request sets the tenant and the next request on the same pooled connection forgets to, the second request inherits the first one's tenant. With transaction-mode poolers such as PgBouncer, session settings can also end up on a completely different request's connection.

The safe pattern is to scope the setting to a transaction. SET LOCAL, or the function form set_config('app.tenant_id', $1, true) where the final true means "local to this transaction," disappears automatically when the transaction ends. Wrap every request's queries in a transaction that sets the tenant first:

import { Pool, type PoolClient } from "pg";

const pool = new Pool({ connectionString: process.env.DATABASE_URL }); // connects as app_user

export async function withTenant<T>(tenantId: string, fn: (db: PoolClient) => Promise<T>): Promise<T> {
  const client = await pool.connect();
  try {
    await client.query("BEGIN");
    // Transaction-local: cleared automatically at COMMIT or ROLLBACK, so it can't
    // leak to the next request that borrows this pooled connection.
    await client.query("SELECT set_config('app.tenant_id', $1, true)", [tenantId]);
    const result = await fn(client);
    await client.query("COMMIT");
    return result;
  } catch (err) {
    await client.query("ROLLBACK");
    throw err;
  } finally {
    client.release();
  }
}

// Usage: no tenant filter in the query; the database enforces it.
const invoices = await withTenant(session.tenantId, (db) =>
  db.query("SELECT id, total, status FROM invoices ORDER BY created_at DESC LIMIT 50"),
);

Two rules keep this safe. First, the tenant ID must come from your authenticated session, never from a request parameter the user controls. Second, make this helper the only way application code gets a database connection, so there's no path that skips setting the tenant. ORMs can usually be wired the same way through a transaction callback.

Using RLS with an ORM

Most applications don't write raw SQL for every query, so the tenant has to be set through whatever data layer you use. The principle is the same everywhere: open a transaction, set the tenant with a transaction-local setting as the first statement, and run every query for the request inside that transaction.

With Drizzle, for example, that looks like this:

import { sql } from "drizzle-orm";

export function withTenantDb<T>(tenantId: string, fn: (tx: typeof db) => Promise<T>) {
  return db.transaction(async (tx) => {
    await tx.execute(sql`select set_config('app.tenant_id', ${tenantId}, true)`);
    return fn(tx as unknown as typeof db);
  });
}

Prisma's interactive transactions support the same pattern with a raw statement at the start of the transaction callback. Whatever the ORM, check three things. Does every query in the request actually use the transaction client rather than the global one? Does the ORM hold the transaction on a single connection throughout? And does anything (a background job, a cache warmer, a script) query tenant tables outside this helper? Those are the places where a tenant gets dropped.

Some platforms build this pattern in. Supabase, for instance, is designed around Postgres RLS, with the authenticated user's identity available to policies, so most of the wiring above is done for you. The same rules about roles, policies and testing still apply.

Bringing an existing database under RLS

Adding RLS to a database that already has years of data needs a little care, mostly around making sure every row has a tenant before policies start filtering on it.

  1. Find tables without a reliable tenant_id. Child tables sometimes rely on a parent's tenant through a foreign key. Policies work best when every tenant-owned table carries its own tenant_id, so backfill it from the parent where necessary.
  2. Make it mandatory. Once backfilled, add NOT NULL, so no future row can be created without a tenant.
  3. Default it from the session setting. A column default such as DEFAULT current_setting('app.tenant_id')::bigint means inserts pick up the current tenant automatically, and the WITH CHECK policy still guards against mismatches.
  4. Enable RLS in a staging environment first, with production-like data, and run the full test suite plus the isolation tests. Code paths that never set a tenant will show up as empty results.
  5. Roll out table by table in production, starting with the most sensitive tables, and watch error rates and empty-result anomalies after each step.

Plan the order around background jobs and scripts. They're the code most likely to run without a request context, and they need an explicit decision: run per tenant with the tenant set, or use a separate, deliberately privileged role with its own audit trail.

Keep the WHERE clause anyway

With RLS in place, you might be tempted to remove tenant_id filters from your queries. Consider keeping them. They make query intent obvious to readers, they help the query planner choose good indexes, and they give you two independent layers: if one is ever misconfigured, the other still holds. RLS is a safety net under your application logic, not a replacement for thinking about tenancy.

Performance: mostly fine, with two caveats

A policy expression is effectively added to every query's WHERE clause, so RLS performance is mostly about whether that predicate can use an index.

  • Index tenant_id. Usually as the first column of composite indexes that match your common queries, such as (tenant_id, created_at). Without it, every query on a large table scans rows from every tenant before filtering.
  • Keep policies simple. A comparison against a setting is cheap. A policy that runs a subquery against a membership table for every row can be expensive. If you need membership checks, make sure the subquery is indexed, and consider resolving the user's tenant once per request instead.

Use EXPLAIN ANALYZE on real queries as the application role, with the tenant set, to see the actual plan. Plans can differ from what you see as a superuser, because superusers bypass RLS entirely.

Views, functions and other escape hatches

RLS applies to queries against tables, but a few Postgres features run with different privileges and can sidestep it if you're not careful.

  • Views by default run with the privileges of the view's owner. If the owner bypasses RLS, so does the view. On PostgreSQL 15 and later, create views with WITH (security_invoker = true) so they run with the caller's privileges and respect RLS.
  • SECURITY DEFINER functions run as their owner. They're sometimes needed, but treat each one as a deliberate hole in your tenancy model and review it carefully.
  • Admin and reporting tools that connect as an owner or superuser see everything. That's often correct for internal staff, but make it a conscious decision with its own access controls and audit logging.
  • Foreign keys and unique constraints are checked across all rows regardless of RLS. A unique constraint on email alone lets one tenant discover whether an email exists in another tenant's data. Scope uniqueness per tenant, for example UNIQUE (tenant_id, email).

Users within a tenant

Tenant isolation is the first layer. Many products also need rules inside a tenant: a member can see projects they belong to, an admin can see all of them. RLS can express these too, with additional settings for the user ID and role, or with policies that check a membership table:

CREATE POLICY members_see_their_projects ON projects
  FOR SELECT
  USING (
    tenant_id = current_setting('app.tenant_id', true)::bigint
    AND (
      current_setting('app.user_role', true) = 'admin'
      OR EXISTS (
        SELECT 1 FROM project_members m
        WHERE m.project_id = projects.id
          AND m.user_id = current_setting('app.user_id', true)::bigint
      )
    )
  );

Policies for the same command and role combine with OR by default (they're "permissive"), so think carefully when you have several. Postgres also supports AS RESTRICTIVE policies, which must all pass; they're a good way to guarantee the tenant check always applies on top of any other rules.

That said, there's a judgement call here. Tenant isolation is a simple, stable rule that suits the database well. Fine-grained, frequently changing business permissions can become hard to reason about inside policies. Many teams use RLS for the tenant boundary and keep detailed role logic in application code.

RLS for AI features and search

Tenant boundaries matter even more once you add AI features. A retrieval system that embeds documents from every customer into one table must never retrieve another tenant's chunks into a prompt, and asking the model to "only use this customer's data" is not a security control. If your vectors live in Postgres, as described in the guide to vector search with pgvector, the same RLS policies protect similarity searches automatically. The same applies to stored agent memories, covered in the guide to AI agent memory: scope them in the database, not in the prompt.

One performance note for vector search: approximate indexes apply filters after scanning the index, so a tenant filter on a shared index can return fewer results than requested for small tenants. Iterative index scans, or per-tenant partial indexes for large tenants, address this.

Testing that isolation actually holds

RLS is only as good as your confidence in it, so test it directly. These tests should run against a real Postgres instance, as the application role, not as a superuser:

  • Cross-tenant reads return nothing. Create data for tenant A, set the tenant to B, and assert that every table returns no tenant A rows.
  • Cross-tenant writes fail. As tenant B, try to update or delete tenant A's rows (expect zero rows affected) and to insert a row with tenant A's ID (expect a policy violation).
  • Missing tenant returns nothing. Run queries without setting the tenant and assert empty results.
  • No leakage across pooled connections. Run requests for different tenants back to back on a single connection and confirm that the setting doesn't carry over.
  • Every tenant table has RLS. A test that queries the catalogue for tables with a tenant_id column where RLS isn't enabled catches new tables that someone forgot to protect.
-- Tables with a tenant_id column but RLS not enabled (should return no rows).
SELECT c.relname
FROM pg_class c
JOIN pg_attribute a ON a.attrelid = c.oid AND a.attname = 'tenant_id'
JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE c.relkind = 'r' AND n.nspname = 'public' AND NOT c.relrowsecurity;

Run that last query in CI. It turns "remember to enable RLS on new tables" from a convention into a check.

Cases where RLS is the wrong tool

RLS suits the common "shared database, shared schema" model. It's less useful, or unnecessary, when:

  • Each tenant has its own database or schema. Isolation comes from the separation itself, at the cost of more operational work as tenants grow.
  • Your queries go through a data access layer that already enforces scoping in a single place you trust, and the extra complexity isn't justified. Even then, RLS is cheap insurance for high-risk tables.
  • You need cross-tenant analytics. Run those through a separate role or a separate analytics store, deliberately, rather than weakening policies for everyone.

Auditing and debugging policies

Once RLS is in place, you'll want to see what's actually configured, and you'll occasionally need to work out why a query returns fewer rows than expected.

The system view pg_policies lists every policy with its table, command, roles and expressions, which makes it easy to review in one place:

SELECT tablename, policyname, cmd, permissive, roles, qual, with_check
FROM pg_policies
WHERE schemaname = 'public'
ORDER BY tablename, policyname;

When a query returns nothing unexpectedly, work through a short list. Is the tenant setting present inside the transaction? Run SELECT current_setting('app.tenant_id', true) in the same transaction to check. Is the query running as the role you think? SELECT current_user answers that. Do the rows actually have the expected tenant_id, including the right type, since comparing a text setting with a numeric column needs an explicit cast? And is a restrictive policy combining with the permissive one in a way you didn't intend?

It also helps to log the tenant ID and the database role with every request in your application logs. If a customer reports missing data, you can confirm which tenant the request ran as without reproducing it. For support staff who genuinely need to see a customer's data, build an explicit, audited path, such as a support tool that sets the customer's tenant for a single session and records who did it and why, rather than handing out a role that bypasses RLS.

Finally, treat policy changes like schema changes: put them in migrations, review them, and run the isolation tests against every change. A policy edited by hand in production is the database equivalent of an untested hotfix. Keeping policies in version control also gives auditors and security reviewers a single, readable record of exactly how tenant data is separated, which is often a question in enterprise sales and compliance reviews.

A rollout plan for an existing app

  1. Create a dedicated application role without ownership or BYPASSRLS, and switch the app to it.
  2. Add the transaction-scoped tenant helper and route all database access through it.
  3. Enable RLS and add policies table by table, starting with the most sensitive data. Default deny means mistakes show up as empty results in testing rather than leaks.
  4. Add FORCE ROW LEVEL SECURITY wherever the application role might own tables.
  5. Add the isolation tests and the CI catalogue check.
  6. Review views, SECURITY DEFINER functions and unique constraints for bypasses.
  7. Keep your existing WHERE tenant_id filters as a second layer.

Frequently asked questions

What is Row-Level Security in PostgreSQL?

Row-Level Security is a PostgreSQL feature that filters which rows a role can see or modify, using policies attached to a table. Once enabled, every query against the table is checked against those policies automatically, and if no policy applies, no rows are visible or modifiable.

Why is my RLS policy not working?

The most common reason is that the application connects as the table owner, a superuser, or a role with BYPASSRLS, all of which bypass policies by default. Use a separate application role, or apply FORCE ROW LEVEL SECURITY to the table. Also check that the tenant setting is actually set inside the same transaction as the query.

How do I use RLS with connection pooling?

Set the tenant inside a transaction with SET LOCAL or set_config with its local flag set to true, so the setting is cleared when the transaction ends. Plain SET lasts for the whole session and can leak to the next request that reuses the pooled connection.

Does Row-Level Security slow down queries?

Usually not much, as long as the policy is a simple comparison and tenant_id is indexed, typically as the leading column of composite indexes. Complex policies with per-row subqueries can be slower. Check real plans with EXPLAIN ANALYZE while connected as the application role.

What is the difference between USING and WITH CHECK in a policy?

USING controls which existing rows a command can see or act on. WITH CHECK controls which rows an INSERT or UPDATE is allowed to write. Setting both to the tenant comparison prevents users from reading other tenants' rows and from writing rows into another tenant.

The takeaway

In a multi-tenant app, the most dangerous query is the one that forgot its tenant filter, and you can't review your way to certainty that nobody ever will. Row-Level Security makes the database refuse to return another tenant's rows no matter what the application asks for. Set it up with a non-owner role, transaction-scoped tenant settings and indexed policies, prove it with tests, and that whole class of bug stops being possible.

Share this article
LuminaryEra Editorial
Editorial

Author at LuminaryEra

The LuminaryEra editorial desk publishes long-form, hands-on guides on AI-assisted development, large language models, developer tools and web engineering. Articles are researched and drafted with the help of AI tools, link to their sources, and are corrected when readers report errors.

View all articles