Filed underL03 · Cloud & DevOps
Published
Reading time23 min
Updated
Field notes · L03 Cloud & DevOps

Multi-tenant SaaS on PostgresRow-level security vs schema-per-tenant vs database-per-tenant

How to build multi-tenant SaaS on Postgres: RLS with session variables, PgBouncer pitfalls, migrations, noisy neighbours, residency and a decision matrix.

The short answer

For most B2B SaaS, put every tenant in shared tables with a tenant_id column and enforce isolation with Postgres row-level security (RLS). Set the tenant per transaction with set_config('app.tenant_id', $1, true) (the function form of SET LOCAL). Connect as a role that does not own the tables and does not have BYPASSRLS, and turn on FORCE ROW LEVEL SECURITY. Move the few tenants who need hard isolation, their own region or their own restore point into a database of their own. Schema-per-tenant is rarely the right default: you get most of the operational cost of separate databases and little of the isolation.

The rest of this post is the detail behind that answer: the exact policies, the connection-pooling traps that turn RLS into a data leak, how each model behaves under migrations and noisy neighbours, and a decision matrix plus an audit script you can run against your own database today.

All references are to PostgreSQL 18, the current stable major at the time of writing (19 is in beta), and PgBouncer 1.26.0, released on 23 September 2026.

01The three Postgres multi-tenancy models

Diagram
 Pooled (RLS)            Schema-per-tenant       Database-per-tenant
 ┌────────────────────┐  ┌────────────────────┐  ┌──────────┐ ┌──────────┐
 │ db: app            │  │ db: app            │  │ db: t1   │ │ db: t2   │
 │ invoices           │  │ t_acme.invoices    │  │ invoices │ │ invoices │
 │ ├ tenant_id=acme   │  │ t_globex.invoices  │  └──────────┘ └──────────┘
 │ ├ tenant_id=globex │  │ t_initech.invoices │
 │ └ policy: current  │  │ search_path picks  │  (same cluster, or one
 │   tenant only      │  │ the tenant         │  cluster per tenant)
 └────────────────────┘  └────────────────────┘
  • Pooled with RLS. One set of tables. Every tenant-owned row carries tenant_id. A policy on each table filters rows to the current tenant. The database enforces isolation, not your WHERE clauses.
  • Schema-per-tenant. One database, one schema per tenant, identical tables in each. The application picks the tenant by setting search_path or by writing schema-qualified names.
  • Database-per-tenant. One logical database per tenant, either packed onto shared clusters or with a dedicated instance per tenant. Isolation comes from the connection itself.

These are points on a line, not three separate tribes. Most mature SaaS platforms end up hybrid: a pooled tier for the long tail and siloed databases for the tenants who pay for it. Design for that from day one and the later move is a data copy, not a rewrite.

02How Postgres row-level security works for multi-tenancy

RLS attaches a predicate to a table. Postgres adds it to every query against that table, for every role that is subject to it. The PostgreSQL 18 documentation spells out the rules that matter here:

  • With RLS enabled and no policy defined, "a default-deny policy is used, meaning that no rows are visible or can be modified." Failing closed is what you want.
  • "Superusers and roles with the BYPASSRLS attribute always bypass the row security system." So do table owners, unless you use ALTER TABLE ... FORCE ROW LEVEL SECURITY.
  • Multiple policies combine with OR when they are permissive (the default) and with AND when they are restrictive.
  • "Referential integrity checks, such as unique or primary key constraints and foreign key references, always bypass row security." That is a covert channel. A tenant can learn whether a key exists by trying to insert it.

The second point is the one teams get wrong. If your application connects as the role that ran your migrations, it owns the tables. RLS is then silently off, and every test you wrote as that role passes.

A reference RLS setup

Use three roles. One owns the schema and runs migrations. One is the application, subject to RLS. One is a break-glass or back-office role with BYPASSRLS, used deliberately and audited.

sql
-- Roles
CREATE ROLE app_owner NOLOGIN;                  -- owns objects; migrations SET ROLE to it
CREATE ROLE app_user  LOGIN PASSWORD '...' NOBYPASSRLS;
CREATE ROLE app_admin LOGIN PASSWORD '...' BYPASSRLS;   -- support tooling only

CREATE SCHEMA app AUTHORIZATION app_owner;
GRANT USAGE ON SCHEMA app TO app_user;

-- One function that defines "current tenant". Empty string and unset both become NULL,
-- and NULL = anything is never true, so a missing tenant returns zero rows.
CREATE FUNCTION app.current_tenant() RETURNS uuid
LANGUAGE sql STABLE
AS $$ SELECT nullif(current_setting('app.tenant_id', true), '')::uuid $$;

CREATE TABLE app.invoices (
  tenant_id   uuid        NOT NULL DEFAULT app.current_tenant(),
  id          uuid        NOT NULL DEFAULT gen_random_uuid(),
  customer_id uuid        NOT NULL,
  total_minor bigint      NOT NULL,
  created_at  timestamptz NOT NULL DEFAULT now(),
  PRIMARY KEY (tenant_id, id),
  FOREIGN KEY (tenant_id, customer_id) REFERENCES app.customers (tenant_id, id)
);
ALTER TABLE app.invoices OWNER TO app_owner;

ALTER TABLE app.invoices ENABLE ROW LEVEL SECURITY;
ALTER TABLE app.invoices FORCE  ROW LEVEL SECURITY;   -- owner is subject to it too

CREATE POLICY tenant_isolation ON app.invoices
  USING      (tenant_id = (SELECT app.current_tenant()))
  WITH CHECK (tenant_id = (SELECT app.current_tenant()));

GRANT SELECT, INSERT, UPDATE, DELETE ON app.invoices TO app_user;

A few deliberate choices in there:

  • current_setting('app.tenant_id', true). The second argument is missing_ok. Without it, a connection that never set the variable raises an error instead of returning nothing. The nullif(..., '') matters too. Once a custom setting has been set in a session, it reads back as an empty string after the transaction ends, not as unset. A bare ''::uuid cast raises an error. Some teams prefer that loud failure. We prefer zero rows plus an alert from the application layer. Pick one and test it.
  • (SELECT app.current_tenant()). Wrapping the call in a sub-select makes the planner evaluate it once per statement as an initPlan rather than once per row. Supabase's RLS guide recommends the same pattern for the same reason.
  • tenant_id leads the primary key and every foreign key. Composite foreign keys make it impossible for an invoice in tenant A to reference a customer in tenant B, even through a bug in a back-office script running as app_admin. RLS stops reads across tenants. Composite keys stop cross-tenant references, and they also give you the indexes the policy needs.
  • WITH CHECK. Without it, a tenant can UPDATE ... SET tenant_id = '<someone else>' and push rows out of its own view into another tenant's.

If you add policies later (for example, per-user visibility inside a tenant), make the tenant policy AS RESTRICTIVE so that it is always combined with AND. A permissive policy added in six months by someone who has never read this file would otherwise be combined with OR, and it would widen access.

Setting the tenant per transaction

The tenant must be set inside the same transaction as the queries, every time. In application code that means one helper that every request goes through:

ts
// node-postgres
import { Pool, PoolClient } from "pg";

export async function withTenant<T>(
  pool: Pool,
  tenantId: string,
  fn: (db: PoolClient) => Promise<T>,
): Promise<T> {
  const db = await pool.connect();
  try {
    await db.query("BEGIN");
    // set_config(name, value, is_local=true) == SET LOCAL, but it accepts a bind parameter.
    await db.query("SELECT set_config('app.tenant_id', $1, true)", [tenantId]);
    const out = await fn(db);
    await db.query("COMMIT");
    return out;
  } catch (err) {
    await db.query("ROLLBACK");
    throw err;
  } finally {
    db.release();
  }
}

Use set_config(..., true) rather than SET LOCAL app.tenant_id = '...'. SET is a utility command and does not accept bind parameters, so the literal form invites string interpolation. That is a SQL injection hole sitting directly on your isolation boundary.

Derive tenantId from the authenticated session on the server: a verified token claim or a server-side session lookup. Never take it from a header or a path parameter the client controls without checking membership.

03Connection pooling pitfalls: PgBouncer transaction mode, SET LOCAL and RDS Proxy

This is where most real RLS incidents come from. Postgres connections are expensive, so you put a pooler in front. In PgBouncer's transaction mode, a server connection goes back to the pool at the end of each transaction and the next one may go to a different client.

The consequences for tenant context:

What the app does Direct connection PgBouncer pool_mode=transaction
SET app.tenant_id = 'A' (session) then queries Works Leaks. The server connection keeps A and the next client to borrow it reads tenant A's rows.
SET LOCAL / set_config(..., true) inside BEGIN ... COMMIT Works Works. The value is discarded at commit or rollback.
SET LOCAL with autocommit, no explicit BEGIN No effect, with a warning No effect. Queries run with no tenant set, so you get zero rows (if you built it fail-closed) or errors.
set_config in one autocommit statement, queries in the next Second statement has no tenant Same, and possibly on a different server connection.

The first row is the dangerous one, because it looks correct in development. Run the app against Postgres directly with one user and session-level SET behaves perfectly. In production behind a transaction pooler, under concurrency, it serves one customer's data to another. That is why the reference setup above is fail-closed. The only way to see another tenant's rows is to have their ID set. A stale session value is exactly that, and transaction-scoped settings are the fix.

Other pooler details worth knowing:

  • Prepared statements. PgBouncer has supported protocol-level named prepared statements in transaction mode since 1.21.0 via max_prepared_statements (changelog). If you are on an older version and your driver prepares statements, upgrade rather than disabling them.
  • search_path tracking. PgBouncer 1.26.0 now tracks every parameter PostgreSQL reports by default, "most notably ... search_path (on PostgreSQL 18 and above)". This matters for schema-per-tenant designs that switch tenants with SET search_path. Before this, that pattern was unsafe in transaction mode unless you configured tracking by hand. Even now, SET LOCAL search_path inside the transaction is the safer habit.
  • Amazon RDS Proxy. For PostgreSQL, the RDS Proxy pinning documentation lists "using SET commands" and "setting a parameter, or resetting a parameter to its default", including through set_config, as conditions that pin a client to one database connection. It also says plainly that "for PostgreSQL setting a variable leads to session pinning". The documentation does not make an exception for transaction-local scope, so assume set_config(..., true) inside a transaction pins too, and confirm it on your own proxy. Sequence functions such as nextval and session-level advisory locks are on the list as well; transaction-level advisory locks such as pg_advisory_xact_lock are exempt. Pinning keeps you safe from leaks but throws away multiplexing. If every request sets tenant context, expect most sessions to pin. Watch DatabaseConnectionsCurrentlySessionPinned, and consider running PgBouncer yourself if the pinning rate defeats the point of the proxy.

A minimal PgBouncer config for the pooled model:

ini
[databases]
app = host=10.0.1.10 port=5432 dbname=app

[pgbouncer]
listen_addr = 0.0.0.0
listen_port = 6432
auth_type = scram-sha-256
auth_file = /etc/pgbouncer/userlist.txt
pool_mode = transaction
default_pool_size = 20
max_client_conn = 5000
max_prepared_statements = 200
query_wait_timeout = 30

On the Postgres side, set guardrails on the application role so a runaway query or an abandoned transaction cannot hold a pooled connection for ever:

sql
ALTER ROLE app_user SET statement_timeout = '15s';
ALTER ROLE app_user SET idle_in_transaction_session_timeout = '30s';
ALTER ROLE app_user SET lock_timeout = '5s';

04Ways RLS silently stops applying

RLS fails open in a handful of places that have nothing to do with pooling. Each one has caught competent teams.

  1. Views. By default a view runs with the privileges of its owner. If app_owner owns both the view and the tables and you have not forced RLS, the view returns every tenant's rows. Since PostgreSQL 15 you can create views WITH (security_invoker = true) so that they run as the caller. Use that for every view the application can read.
  2. SECURITY DEFINER functions. They run as their owner. Anything that reads tenant tables inside one must filter by app.current_tenant() explicitly, or must be owned by a role that is subject to RLS.
  3. Materialised views. They have no RLS at all. Never expose one to app_user unless it is already scoped to a tenant, or put it behind a security-invoker view that filters on tenant_id.
  4. Partitions. Policies on a partitioned parent apply to queries through the parent. Querying a partition directly uses the partition's own RLS settings. Revoke direct access to partitions from app_user.
  5. Background jobs and analytics. Workers often connect as a privileged role "because it's internal". Give them app_user, have them set tenant context per job, and keep BYPASSRLS for named, audited tools.
  6. Uniqueness as an oracle. A global UNIQUE (email) tells tenant B that some tenant already has ceo@acme.com. Scope uniqueness to the tenant (UNIQUE (tenant_id, email)) unless the business rule really is global.

05RLS performance: what it costs and how to keep it cheap

A well-written tenant policy costs about as much as the WHERE tenant_id = ? you would otherwise have written by hand, because that is what it becomes. The cost shows up when the policy cannot use an index, or when the policy stops the planner from using one.

  • Index for the policy. Every tenant table should have tenant_id as the leading column of its primary key and of its hot secondary indexes: (tenant_id, created_at), (tenant_id, customer_id) and so on. A single-column index on customer_id is close to useless once the policy adds tenant_id = $x.
  • Leakproof functions. The planner will not push a qualifier from your query below the security barrier unless the function behind it is marked LEAKPROOF. The docs explain the reason: a non-leakproof function could leak values from rows the policy would have filtered out, for example through an error message. Most built-in equality operators are leakproof. Some text-matching and custom functions are not, which can turn an index scan into "scan the tenant's rows, then filter". Check with EXPLAIN (ANALYZE, BUFFERS) as app_user with tenant context set, never as a superuser. A superuser bypasses RLS, so you would be measuring a plan production never runs.
  • Skewed tenants. Pooled tables have very uneven tenants. One customer with 40% of the rows and ten thousand with a few hundred each is a common shape. With prepared statements, Postgres may switch to a generic plan after five executions. That plan can suit small tenants and be terrible for the large one. If you see bimodal latency by tenant, try plan_cache_mode = force_custom_plan for the affected role or statement before anything more drastic.
  • Partition when tables get large. Hash partitioning on tenant_id keeps each partition's indexes small and makes vacuum manageable. List-partitioning your largest tenants into their own partitions gives you a cheap halfway house before full siloing. PostgreSQL 19's improved partition merge and split support (per the beta announcements) should make reshaping that layout less painful.

We are not going to quote a percentage for "RLS overhead". It depends entirely on whether the plan changes. If it does not, the cost is noise. If it does, the cost can be orders of magnitude. Measure your own top 20 statements by total time from pg_stat_statements, with and without the policy, as app_user.

06Schema-per-tenant: where it helps and where it hurts

Schema-per-tenant looks attractive. Tenants are visibly separate, pg_dump -n t_acme exports one customer, and you can customise a table for one tenant. In practice:

  • Catalogue growth. Every table, index, sequence and TOAST table is a row in pg_class, and Postgres caches catalogue entries per backend. A worked example: 2,000 tenants × 80 tables × roughly 5 relations per table (heap, TOAST, about 3 indexes) ≈ 800,000 relations. Planning, pg_dump, autovacuum scheduling and backend memory all scale with that. This is not a hard limit, but it is a cost you pay on every connection.
  • Migrations run N times. One ALTER TABLE becomes 2,000. Each can fail on its own, which leaves you with a fleet at mixed schema versions. That is the same operational problem as database-per-tenant, without the isolation benefits.
  • Isolation is weaker than it looks. Every schema shares one role namespace, one buffer cache, one WAL stream, one max_connections and one restore point. A mistake in search_path is a cross-tenant query. To get real separation you still need RLS or a role per tenant.
  • Pooling. With PgBouncer 1.26 and PostgreSQL 18, search_path is tracked in transaction mode. On older stacks it is not, and SET search_path in transaction mode is a leak.

Where it does fit: a modest number of tenants (dozens to low hundreds), real per-tenant schema customisation, and a plan to scale out with Citus schema-based sharding, which since Citus 12 can turn each schema into a distributed shard that is placed as one unit. If none of those apply, you probably don't need it.

07Database-per-tenant: isolation at a price

A database per tenant gives you the strongest isolation Postgres offers short of separate hardware. You get per-tenant point-in-time recovery (with a cluster per tenant), per-tenant extensions and versions, a clean DROP DATABASE for offboarding, and a credible answer to "is our data physically separate?"

The costs are real:

  • Connections. PgBouncer pools per database-and-user pair. Worked example: 500 tenant databases × default_pool_size = 20 = up to 10,000 server connections if every pool fills. No single Postgres cluster should run that many. You either shrink pools (and queue at the pooler) or spread tenants across many clusters. PgBouncer 1.26's new pool_idle_timeout, which closes pools that are not in use, helps with the long tail.
  • Instances. If you want one managed instance per tenant, check quotas early. Amazon RDS defaults to 40 DB instances per region, 20 in ap-south-1 (RDS quotas). You can raise it, but it tells you the default use case is not thousands of instances.
  • Cost floor. Every dedicated instance has a minimum size, backup storage and monitoring. That is fine for a tenant paying enterprise prices and ruinous for a free tier.
  • Cross-tenant queries. Product analytics, billing and support tooling now need a fan-out query layer or a warehouse fed by CDC from every database.

08Migrations at scale across tenants

Pooled (RLS) Schema-per-tenant Database-per-tenant
Migrations per change 1 N N
Partial-failure state None (single transaction or expand/contract) Mixed versions across schemas Mixed versions across databases
Lock blast radius All tenants at once One tenant per statement One tenant per statement
Rollout control Feature flags Canary by schema Canary by database

The pooled model's weakness is the flip side of its strength. One ALTER TABLE that takes an ACCESS EXCLUSIVE lock on a hot table stalls every tenant. Use expand/contract migrations with lock timeouts, CREATE INDEX CONCURRENTLY, ADD COLUMN without volatile defaults, and a lock_timeout on the migration session so it gives up instead of queueing behind long transactions.

For schema- and database-per-tenant, you need a migration orchestrator, not a migration tool. At minimum: a control-plane table recording each tenant's schema version, idempotent migrations, rollout in rings (internal tenants, then 5%, then everyone, the same idea as progressive delivery with feature flags), bounded concurrency and automatic halt on error rate. A sketch:

bash
#!/usr/bin/env bash
# Illustrative: roll migration V42 across tenant databases in rings, 8 at a time.
set -euo pipefail
RING="${1:?ring name}"
psql "$CONTROL_DB" -At -c \
  "select dsn from tenants where ring = '$RING' and schema_version < 42" |
xargs -P 8 -I{} sh -c '
  psql "{}" -v ON_ERROR_STOP=1 -c "SET lock_timeout = '\''5s'\''" -f migrations/V42.sql &&
  psql "$CONTROL_DB" -c "update tenants set schema_version = 42 where dsn = '\''{}'\''" ||
  echo "FAILED {}" >&2
'

In production, this lives in a proper job runner with retries and a dashboard of tenants by version. The shape stays the same.

09Noisy neighbours in shared Postgres

In the pooled and schema models, tenants share CPU, I/O, buffer cache, WAL and connections. Postgres has no per-tenant resource governor. What you can do:

  • Make tenants visible. pg_stat_statements aggregates by query text, not by tenant. Add a tenant tag to every statement with an SQL comment (the sqlcommenter format is widely supported, and can also carry the traceparent from distributed tracing), and log slow queries with it. "Which tenant is burning the database?" should take one query to answer.
  • Bound the damage per statement. Role-level statement_timeout, work_mem and idle_in_transaction_session_timeout, as above. Give exports and reporting a separate role with longer timeouts that points at a read replica.
  • Rate-limit at the application. Per-tenant concurrency limits in front of the database are cheaper and fairer than anything you can do inside it.
  • Have an exit. The real fix for a whale is to move it. Keep a tenant-to-database routing table from day one, even when every row points at the same cluster. Moving a tenant is then a copy (logical replication filtered by tenant_id with row filters, available since PostgreSQL 15), a short write freeze and a routing flip.

10Compliance and data residency

RLS is an access-control mechanism, not a residency mechanism. Rows in one table live in one cluster, in one region. If a customer contractually requires EU-only storage, a tenant_id policy does not help. You need a regional cell: a separate deployment (database, application and backups) in that region, with tenants assigned to cells by a global routing layer. That is a different problem from active-active vs active-passive multi-region failover, though the routing layer looks similar.

Other compliance-driven questions and how each model answers them:

Requirement Pooled (RLS) Schema-per-tenant Database-per-tenant
"Is our data logically isolated?" Yes, enforced by policy. Show the audit queries below. Yes, by namespace. Yes, by connection.
"Is our data physically separate?" No No Only with a dedicated cluster.
Tenant-specific restore Hard: restore elsewhere, extract by tenant_id Moderate: restore elsewhere, pg_dump -n Easy with a cluster per tenant
Erasure on offboarding DELETE across every table, plus backups age out DROP SCHEMA ... CASCADE DROP DATABASE
Customer-managed keys App-level envelope encryption per tenant Same Per-instance storage encryption keys possible
Residency Regional cells Regional cells Place the instance in the region

For erasure in the pooled model, per-tenant application-layer encryption with crypto-shredding (destroying the tenant's key) is the most defensible answer for data that persists in backups. Whether that satisfies a particular regulator or contract is a question for your counsel, not your DBA.

11Decision matrix: RLS vs schema-per-tenant vs database-per-tenant

Score your situation against each row. If most of your answers land in one column, that is your default. Treat the right-hand column as the tier for tenants who need it, not as a reason to abandon the pooled model for everyone.

Factor Pooled (RLS) Schema-per-tenant Database-per-tenant
Tenant count Hundreds to millions Dozens to low hundreds Tens to low thousands (packed); tens (dedicated)
Revenue per tenant Any, including free tier Mid High enough to cover an instance floor
Isolation requirement Logical, enforced by DB Logical, by namespace Physical or contractual
Per-tenant schema customisation No Yes Yes
Per-tenant restore / PITR No Partial Yes (dedicated cluster)
Data residency per tenant Via regional cells Via regional cells Native
Migration effort Lowest High High
Cross-tenant analytics Trivial Awkward Needs a warehouse
Noisy-neighbour risk Highest High Lowest
Pooling complexity Low (one pool) Medium High (pool per DB)
Main failure mode Context leak via pooler or owner role search_path mistakes, catalogue bloat Fleet drift, connection sprawl

What we would actually do for a new B2B SaaS: pooled RLS for everyone, a routing table from day one, composite (tenant_id, …) keys everywhere, and a documented path to move a tenant into a dedicated database when a contract or a load profile demands it. We would not start with schema-per-tenant unless per-tenant customisation is a core product feature.

12RLS hardening checklist and audit queries

This is the part to copy into your runbook. Run the queries in CI against a migrated database and fail the build on any output.

1. Tenant tables without RLS enabled and forced

sql
SELECT n.nspname AS schema, c.relname AS table,
       c.relrowsecurity      AS rls_enabled,
       c.relforcerowsecurity AS rls_forced
FROM pg_class c
JOIN pg_namespace n ON n.oid = c.relnamespace
JOIN pg_attribute a ON a.attrelid = c.oid
                   AND a.attname = 'tenant_id' AND NOT a.attisdropped
WHERE c.relkind IN ('r', 'p')
  AND n.nspname NOT IN ('pg_catalog', 'information_schema')
  AND (NOT c.relrowsecurity OR NOT c.relforcerowsecurity);

2. Tenant tables with RLS on but no policy (default-deny: safe, but probably a bug)

sql
SELECT n.nspname, c.relname
FROM pg_class c
JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE c.relrowsecurity
  AND NOT EXISTS (SELECT 1 FROM pg_policy p WHERE p.polrelid = c.oid);

3. Login roles that bypass RLS

sql
SELECT rolname FROM pg_roles
WHERE rolcanlogin AND (rolsuper OR rolbypassrls)
ORDER BY rolname;

Expected output: your break-glass role and your managed provider's admin role. Nothing else.

4. Is the application role the table owner?

sql
SELECT c.relname
FROM pg_class c
JOIN pg_roles r ON r.oid = c.relowner
WHERE r.rolname = 'app_user' AND c.relkind IN ('r', 'p', 'v', 'm');

Expected output: none.

5. Views that run as their owner

sql
SELECT n.nspname, c.relname
FROM pg_class c
JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE c.relkind = 'v'
  AND n.nspname NOT IN ('pg_catalog', 'information_schema')
  AND NOT coalesce(c.reloptions @> ARRAY['security_invoker=true'], false);

6. A behavioural test (run as app_user through the same pooler as production):

sql
BEGIN;
SELECT count(*) FROM app.invoices;                      -- expect 0: no tenant set
SELECT set_config('app.tenant_id', :'tenant_a', true);
INSERT INTO app.invoices (tenant_id, customer_id, total_minor)
VALUES (:'tenant_b', :'cust_b', 100);                   -- expect: new row violates row-level security policy
ROLLBACK;

Pair this with a concurrency test in your integration suite. Fire interleaved requests for two tenants through PgBouncer in transaction mode with a pool size of 1, and assert that no response contains the other tenant's IDs. That test catches the session-SET leak that unit tests never will.

Checklist

  • App connects as a non-owner role with NOBYPASSRLS
  • Every tenant table has RLS ENABLE + FORCE, a policy with USING and WITH CHECK
  • Tenant set only via set_config(..., true) inside an explicit transaction
  • Tenant ID comes from verified server-side identity, never raw client input
  • tenant_id leads every PK, FK and hot index; uniqueness scoped per tenant
  • All app-readable views are security_invoker; no exposed materialised views
  • SECURITY DEFINER functions reviewed and filter by tenant explicitly
  • Workers and cron jobs use app_user with per-job tenant context
  • Audit queries 1–5 run in CI; concurrency leak test runs against the real pooler
  • EXPLAIN checks on top statements done as app_user, not a superuser
  • Tenant routing table exists, even if every row points to one cluster

13Where this crosses into other layers

Tenancy is a database decision that every other layer inherits. Security owns the threat model and the evidence auditors ask for. That is where the audit queries above end up. Data needs a pipeline that keeps tenant_id through CDC into the warehouse, or analytics becomes the place isolation quietly breaks. Search and AI features need the same care: permission-aware RAG has to enforce document access rules during retrieval. Software owns the one withTenant path every request goes through. Strategy owns which tenants get a dedicated database and what that tier costs, and tenant isolation is a fair question in any technical due diligence checklist. Making the choice in only one of those layers is how teams end up with RLS in the database and a reporting job that connects as the owner.

14FAQ

Does PgBouncer transaction mode work with Postgres row-level security? Yes, as long as tenant context is transaction-scoped. Use set_config('app.tenant_id', $1, true) or SET LOCAL inside an explicit BEGIN … COMMIT. Session-level SET leaks across clients in transaction mode and must never be used for tenant context.

Is SET LOCAL safe against SQL injection? SET LOCAL cannot take bind parameters, so building it with string interpolation is risky. SELECT set_config('app.tenant_id', $1, true) does the same thing and accepts a parameter. Use that.

How much slower is Postgres RLS? For a simple tenant_id = current_tenant() policy backed by an index that leads with tenant_id, the difference is usually negligible, because the plan is the same one you would get from a hand-written filter. It gets expensive when the policy forces a different plan: missing indexes, non-leakproof functions or complex sub-queries in the policy. Measure as the application role.

Can I use RLS with an ORM like Prisma, Django or Rails? Yes, if the ORM lets you run the set_config call and your queries on the same connection inside one transaction. Most do, through an interactive transaction or a connection-checkout hook. The usual trap is an ORM that uses autocommit by default, so the setting and the query run in separate transactions.

When should I move a tenant to its own database? When a contract requires physical separation or a specific region, when the tenant needs its own restore point (and remember your backups don't exist until you've restored them), or when its load measurably degrades other tenants and rate limits do not fix it. Keep a routing table so the move is a migration, not a rewrite.

Does schema-per-tenant give better security than RLS? Not by itself. All schemas share roles, memory, WAL and backups, and one wrong search_path is a cross-tenant read. If isolation is the goal, RLS with forced policies and a non-owner role is stronger and easier to audit. If physical separation is the goal, use separate databases.

If this is the layer that hurts, we should talk.

Tell us which layer hurts →