# Multi-Tenant SaaS with PostgreSQL: Row-Level Security and Schemas

> Multi-tenant PostgreSQL: shared schema vs schema vs database per tenant, RLS policies, pooling-safe context, migrations, isolation tests, and ORM integration.

Source: https://www.derar.dev/blog/multi-tenant-saas-postgres-row-level-security-2026 · Published 2026-11-11 · Updated 2026-11-14 · By Derar Sattouf

Every B2B SaaS eventually faces the same question: how do we keep customer A's data away from customer B? The honest answer on most teams is "every query has a `WHERE tenant_id = ?` and we hope nobody forgets one". It works until the day a new developer writes a report query, or an ORM relation loads a child table without the filter, or a background job runs without a tenant context. The resulting bug is not a crash. It is a data breach.

PostgreSQL gives you a way to make the database enforce the rule: **row-level security (RLS)**. Combined with a good tenancy model, composite keys, a pooling-safe way to carry the tenant identity, tests that actively try to cross the boundary, and a migration strategy that scales, RLS turns tenant isolation from a convention into an invariant.

There are three tenancy models. A shared schema with a `tenant_id` column is the default choice and scales to many small tenants. Schema per tenant is the middle ground, but it gets painful past a few thousand tenants. Database per tenant gives the strongest isolation at the highest operational cost. Many products end up hybrid: pooled for most tenants, siloed for large or regulated customers.

RLS makes the database enforce tenant isolation: `ALTER TABLE ... ENABLE ROW LEVEL SECURITY` plus a policy `USING (tenant_id = current_setting('app.tenant_id')::uuid)`. Add `WITH CHECK` so writes cannot create or move rows into another tenant. Table owners and superusers bypass RLS by default, as do roles with `BYPASSRLS`. So use `FORCE ROW LEVEL SECURITY` and have the application connect as a non-owner, non-superuser role with no `BYPASSRLS`. Run migrations with a different role.

Carry the tenant identity with `SET LOCAL` (or `set_config(..., true)`) inside a transaction. That is safe with PgBouncer in transaction pooling mode. Plain `SET` is not: it leaks to the next client on that connection. Fail closed, too. If `app.tenant_id` is unset, queries should return nothing, not everything, so use `current_setting('app.tenant_id', true)` with a null-safe policy and test the unset case. Then test isolation actively: a cross-tenant suite that inserts data for two tenants and tries reads, writes, joins, updates and deletes as each, run in CI against a real Postgres.

Design keys for tenancy: composite primary and foreign keys `(tenant_id, id)`, tenant-leading indexes, and per-tenant unique constraints like `UNIQUE (tenant_id, slug)`. RLS has a performance cost that is usually small if the policy is simple, wrapped in `(SELECT ...)`, and backed by `tenant_id`-leading indexes; verify with `EXPLAIN (ANALYZE, BUFFERS)`. Use a separate role for admin and cross-tenant jobs (analytics, billing, support), with audited access. Plan per-tenant export, restore and deletion before you need them: in a shared schema these are queries and jobs, not `pg_dump` of a database. Migrations multiply with schema or database per tenant; with a shared schema they are one migration but must be zero-downtime, so use expand and contract. Last, RLS is a safety net, not a substitute for authorization in the application. Use both.

The SQL here targets PostgreSQL 15 and later, and was written with PostgreSQL 17 and 18 in mind. Where a feature depends on the version (for example `security_invoker` views, added in 15), the text says so. Check details against the [PostgreSQL documentation](https://www.postgresql.org/docs/current/ddl-rowsecurity.html) for your version. For reading query plans, see [Postgres Query Performance with EXPLAIN ANALYZE](https://www.derar.dev/blog/postgres-query-performance-explain-analyze-2026). For the migration mechanics that become critical at scale, see [Zero-Downtime Postgres Migrations](https://www.derar.dev/blog/zero-downtime-postgres-migrations-2026).

It's a long post, so read by need. Choosing an architecture for a new SaaS? Start with the tenancy models and data model sections. Adding RLS to an existing shared-schema app? Read the RLS, tenant context and policies sections, then the rollout plan near the end. If RLS returns nothing or runs slowly, go to the tenant context, Next.js and performance sections; if you use PgBouncer or a serverless Postgres pooler, the context section is the one that matters. The ORM section covers Prisma, Drizzle, Django and Laravel, and the complete working example near the end ties everything together. If an AI agent is generating your migrations, point it at the context rules, the migrations section and the checklist: never remove `FORCE`, never run as owner.

## Tenancy models and trade-offs

### The three models

```text
Model A: Shared database, shared schema ("pool")
  one database
    one schema (public)
      invoices(tenant_id, id, ...)    <- every row tagged with its tenant

Model B: Shared database, schema per tenant ("bridge")
  one database
    schema tenant_acme: invoices(id, ...)
    schema tenant_globex: invoices(id, ...)

Model C: Database per tenant ("silo")
  database acme:   invoices(id, ...)
  database globex: invoices(id, ...)
```

### Comparison

| Criterion | A: Shared schema + tenant_id | B: Schema per tenant | C: Database per tenant |
| --- | --- | --- | --- |
| Isolation strength | Logical (RLS, app code) | Logical (search_path, grants) | Strong (separate catalogs, can be separate clusters) |
| Cross-tenant leak risk | Highest if unprotected; low with RLS | Medium (wrong search_path) | Lowest |
| Tenants supported | Millions of rows, tens of thousands of tenants and beyond | Hundreds to low thousands; catalog bloat past that | Tens to hundreds per cluster; fleets for more |
| Migrations | Once | Per schema (N times) | Per database (N times) |
| Connection pooling | Easy; one pool | Awkward; search_path per connection | Hard; per-database pools or a proxy |
| Per-tenant backup and restore | Logical export by tenant_id; PITR restores everyone | `pg_dump -n` per schema; selective restore is easy | Easy and independent (even PITR per tenant) |
| Noisy neighbor control | Hard; shared everything | Hard; shared resources | Best; separate resources possible |
| Per-tenant customization (extra columns, indexes) | Painful | Possible | Easy |
| Data residency (EU tenant stays in EU) | Needs separate clusters anyway | Needs separate clusters | Natural |
| Cost per tenant | Lowest | Low to medium | Highest |
| Operational complexity | Lowest | Medium | Highest |
| Onboarding a tenant | Insert a row | Create schema and run migrations | Create database and run migrations |

### How to choose

| Situation | Recommendation |
| --- | --- |
| Many small tenants (self-serve, thousands to millions of users) | Model A with RLS |
| A moderate number of mid-size tenants with different schema needs | Model B, or A if schemas are identical |
| Regulated tenants (health, finance, government) or strict contractual isolation | Model C for those, possibly in their own region |
| Mixed customer base | **Hybrid**: pool for the long tail, silo for whales and regulated accounts, behind one routing layer |
| Heavy per-tenant analytics or exports | A with read replicas, or move hot tenants to their own database |
| Very early stage | Model A with RLS from day one, because retrofitting later is the expensive part |

A pragmatic evolution path: **start with A plus RLS**, keep a `tenants` table with a `placement` column (`pool`, `dedicated_db`), and route connections by placement. This keeps migration to model C possible without rewriting the application, because the tenant context is already carried everywhere.

### Why not "just filter in the app"?

| App-only filtering | RLS |
| --- | --- |
| Every query must remember the predicate | Predicate applied by the database to every query |
| Raw SQL, reports, ORMs, scripts and admin tools each re-implement it | One policy per table |
| A missed filter is a silent breach | A missed filter returns nothing (fail closed) |
| Hard to audit | Policies are inspectable in the catalog (`pg_policies`) |
| Zero database overhead | Small overhead; indexable |

Use both: the application still authorizes (roles within a tenant, feature flags), and RLS guarantees the tenant boundary.

## Data model foundations

Whatever the model, define tenant identity once.

```sql
CREATE EXTENSION IF NOT EXISTS pgcrypto;  -- gen_random_uuid() is built in since PG13; shown for older habits

CREATE TABLE tenants (
  id          uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  slug        text NOT NULL UNIQUE CHECK (slug ~ '^[a-z0-9-]{3,40}$'),
  name        text NOT NULL,
  plan        text NOT NULL DEFAULT 'free',
  placement   text NOT NULL DEFAULT 'pool' CHECK (placement IN ('pool', 'dedicated_db')),
  status      text NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'suspended', 'deleting')),
  created_at  timestamptz NOT NULL DEFAULT now()
);
```

### Composite keys keep relations inside a tenant

The most common cross-tenant leak that RLS alone does not prevent: **a foreign key pointing at another tenant's row**. If `invoice_items.invoice_id` references `invoices.id` and ids are globally unique, nothing stops a row in tenant A from pointing at an invoice of tenant B. Make the tenant part of the key.

```sql
CREATE TABLE customers (
  tenant_id  uuid NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
  id         uuid NOT NULL DEFAULT gen_random_uuid(),
  email      text NOT NULL,
  name       text NOT NULL,
  created_at timestamptz NOT NULL DEFAULT now(),
  PRIMARY KEY (tenant_id, id),
  UNIQUE (tenant_id, email)               -- uniqueness is per tenant, not global
);

CREATE TABLE invoices (
  tenant_id   uuid NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
  id          uuid NOT NULL DEFAULT gen_random_uuid(),
  customer_id uuid NOT NULL,
  number      text NOT NULL,
  total_cents bigint NOT NULL CHECK (total_cents >= 0),
  status      text NOT NULL DEFAULT 'draft',
  created_at  timestamptz NOT NULL DEFAULT now(),
  PRIMARY KEY (tenant_id, id),
  UNIQUE (tenant_id, number),
  FOREIGN KEY (tenant_id, customer_id) REFERENCES customers (tenant_id, id)  -- cannot cross tenants
);

CREATE TABLE invoice_items (
  tenant_id   uuid NOT NULL,
  id          uuid NOT NULL DEFAULT gen_random_uuid(),
  invoice_id  uuid NOT NULL,
  description text NOT NULL,
  amount_cents bigint NOT NULL,
  PRIMARY KEY (tenant_id, id),
  FOREIGN KEY (tenant_id, invoice_id) REFERENCES invoices (tenant_id, id) ON DELETE CASCADE
);
```

Why `(tenant_id, id)` as the primary key rather than `id` alone:

1. **Referential integrity across tenants becomes impossible**, enforced by the database, independent of RLS and application code.
2. **Index locality.** Rows of one tenant are clustered by key in the index, which is what most queries want.
3. **Partitioning and sharding readiness.** A tenant-leading key is a natural partition or shard key (Citus, native hash partitioning).

Cost: wider keys and the need to pass `tenant_id` in every join and foreign key. Most ORMs support composite keys, with varying ergonomics (see the ORM and framework integration section). If your ORM fights composite keys, keep a surrogate unique `id` and add a `UNIQUE (tenant_id, id)` constraint that foreign keys can reference. That gives the same protection.

```sql
-- Alternative: globally unique id plus a tenant-scoped unique constraint to anchor FKs
CREATE TABLE projects (
  id         uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  tenant_id  uuid NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
  name       text NOT NULL,
  UNIQUE (tenant_id, id)
);
CREATE TABLE tasks (
  id         uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  tenant_id  uuid NOT NULL,
  project_id uuid NOT NULL,
  title      text NOT NULL,
  FOREIGN KEY (tenant_id, project_id) REFERENCES projects (tenant_id, id)
);
```

### Index rules for the shared schema

| Rule | Reason |
| --- | --- |
| Lead every index with `tenant_id` for tenant-scoped queries | RLS adds `tenant_id = X`; the planner uses the leading column |
| Unique constraints include `tenant_id` | Per-tenant uniqueness (`UNIQUE (tenant_id, slug)`) |
| Partial indexes for hot subsets, still with `tenant_id` first | `CREATE INDEX ON invoices (tenant_id, created_at) WHERE status = 'open'` |
| Global uniqueness only where it is truly global | Example: custom domains, login emails if one account spans tenants |
| Avoid indexes with no `tenant_id` unless used for cross-tenant admin queries | They get used by scans that RLS then filters, wasting IO |

```sql
CREATE INDEX invoices_tenant_created_idx ON invoices (tenant_id, created_at DESC);
CREATE INDEX invoices_tenant_status_idx  ON invoices (tenant_id, status) WHERE status <> 'paid';
```

Index design and plan reading are covered in [Postgres Query Performance with EXPLAIN ANALYZE](https://www.derar.dev/blog/postgres-query-performance-explain-analyze-2026).

### Users and membership

A person may belong to several tenants. Keep identity separate from membership.

```sql
CREATE TABLE users (
  id        uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  email     text NOT NULL UNIQUE,
  created_at timestamptz NOT NULL DEFAULT now()
);

CREATE TABLE memberships (
  tenant_id uuid NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
  user_id   uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
  role      text NOT NULL CHECK (role IN ('owner', 'admin', 'member', 'viewer')),
  PRIMARY KEY (tenant_id, user_id)
);
```

`users` is a global table (no RLS on tenant, or a policy based on the user). Resolving "which tenants may this user act as" is done by the application before it sets the tenant context.

## Row-level security in depth

### The basics

```sql
ALTER TABLE invoices ENABLE ROW LEVEL SECURITY;
ALTER TABLE invoices FORCE ROW LEVEL SECURITY;

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

What each piece does:

| Piece | Meaning |
| --- | --- |
| `ENABLE ROW LEVEL SECURITY` | Turns on policy evaluation for the table. With RLS enabled and **no policies**, all non-owner access is denied (default deny) |
| `FORCE ROW LEVEL SECURITY` | Applies policies to the **table owner** as well. Without it the owner bypasses RLS |
| `USING (expr)` | Rows visible for `SELECT`, and rows that may be targeted by `UPDATE` and `DELETE` |
| `WITH CHECK (expr)` | Rows that may be written: new rows from `INSERT`, and the new version of rows from `UPDATE`. A violation raises an error |
| `current_setting('app.tenant_id', true)` | Reads a custom setting; the `true` (missing_ok) returns NULL when it was never set instead of raising an error |
| `(SELECT ...)` wrapper | Lets the planner evaluate the setting once as an init plan instead of per row |

If `app.tenant_id` is NULL, `tenant_id = NULL` is not true, so **no rows are visible and no rows can be written**. That is the fail-closed behavior you want. Note one trap: if the setting was set in the session earlier and reset to an empty string, the `::uuid` cast of `''` raises an error. Handle that with `NULLIF`:

```sql
-- Robust tenant accessor: returns NULL when unset or empty
CREATE OR REPLACE FUNCTION app_current_tenant() RETURNS uuid
LANGUAGE sql STABLE PARALLEL SAFE AS $$
  SELECT NULLIF(current_setting('app.tenant_id', true), '')::uuid
$$;

DROP POLICY IF EXISTS tenant_isolation ON invoices;
CREATE POLICY tenant_isolation ON invoices
  USING      (tenant_id = (SELECT app_current_tenant()))
  WITH CHECK (tenant_id = (SELECT app_current_tenant()));
```

### Policy semantics you must know

1. **Permissive policies combine with OR; restrictive policies combine with AND.** By default policies are `PERMISSIVE`. If you add a second permissive policy "for admins", rows pass if either passes. To add a mandatory extra condition (for example "tenant is not suspended"), use `AS RESTRICTIVE`.
2. **Policies are per command and per role.** `FOR SELECT`, `FOR INSERT`, `FOR UPDATE`, `FOR DELETE`, `FOR ALL`, and `TO role_name`.
3. **`INSERT` uses only `WITH CHECK`**; `SELECT` and `DELETE` use only `USING`; `UPDATE` uses both (`USING` to find the row, `WITH CHECK` on the new row). If an `UPDATE` policy has no `WITH CHECK`, `USING` is applied to the new row too, but be explicit.
4. **`UPDATE` and `DELETE` also need `SELECT` visibility** when their `WHERE` clause reads columns, and `INSERT ... ON CONFLICT DO UPDATE` requires both insert and update policy checks. Test upserts explicitly.
5. **`RETURNING` requires `SELECT` policy access** to the returned rows.

```sql
-- A restrictive policy: block writes to suspended tenants regardless of other policies
CREATE POLICY no_writes_when_suspended ON invoices
  AS RESTRICTIVE
  FOR INSERT TO app_user
  WITH CHECK (
    NOT EXISTS (SELECT 1 FROM tenants t WHERE t.id = invoices.tenant_id AND t.status <> 'active')
  );
```

Policies that query other tables cost more and can recurse; keep tenant isolation policies trivial (`tenant_id = current tenant`) and enforce business rules elsewhere.

### Bypass rules, the part that bites

| Role or situation | RLS applies? |
| --- | --- |
| Superuser | **No**, always bypasses |
| Role with `BYPASSRLS` attribute | **No** |
| Table owner | **No**, unless `FORCE ROW LEVEL SECURITY` |
| Other roles | Yes |
| Referential integrity checks (foreign key lookups, cascades) | **Bypass RLS** internally |
| `pg_dump` | Disables RLS by default for the dumping role if it can (`--enable-row-security` to apply it) |
| Views | By default run with the **view owner's** privileges, so RLS is evaluated as the owner and may be bypassed. Use `WITH (security_invoker = true)` on PG15+ |
| `SECURITY DEFINER` functions | Execute as the function owner, so RLS applies as that owner (bypassed if owner is superuser or table owner without FORCE) |
| Materialized views | Not protected by RLS on the base tables when queried; they store data. Avoid for tenant data or add RLS to the matview itself |

Consequences:

- **Never connect the application as the table owner or a superuser.** Create a dedicated, unprivileged login role.
- **Run migrations as a separate owner role**, and grant the app role only what it needs.
- **Foreign key checks bypass RLS**, which is why the **composite foreign key** `(tenant_id, x)` from the data model section matters: otherwise an attacker (or bug) could probe for the existence of another tenant's key through error messages.
- **Views**: add `security_invoker = true` and also keep `SECURITY DEFINER` functions rare and careful, with `SET search_path` pinned.

### Role setup

```sql
-- Owner of schema objects (used by migrations only)
CREATE ROLE app_owner NOLOGIN;
-- Login role for migrations, member of app_owner
CREATE ROLE migrator LOGIN PASSWORD 'REPLACE_ME' IN ROLE app_owner;
-- Runtime role for the application: NOSUPERUSER, NOBYPASSRLS (defaults, stated explicitly)
CREATE ROLE app_user LOGIN PASSWORD 'REPLACE_ME' NOSUPERUSER NOBYPASSRLS NOCREATEDB NOCREATEROLE;
-- Separate role for cross-tenant jobs; use sparingly and audit it
CREATE ROLE app_admin LOGIN PASSWORD 'REPLACE_ME' NOSUPERUSER BYPASSRLS;

-- Ownership
ALTER SCHEMA public OWNER TO app_owner;
-- (tables created by migrator inherit ownership through role membership when using SET ROLE app_owner;
--  or run migrations with SET ROLE app_owner / ALTER DEFAULT PRIVILEGES as below)

-- Privileges for the runtime role
GRANT USAGE ON SCHEMA public TO app_user;
ALTER DEFAULT PRIVILEGES FOR ROLE app_owner IN SCHEMA public
  GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO app_user;
ALTER DEFAULT PRIVILEGES FOR ROLE app_owner IN SCHEMA public
  GRANT USAGE, SELECT ON SEQUENCES TO app_user;
```

In production, passwords should come from a secrets manager or be replaced by IAM authentication; see [Secrets Management in 2026](https://www.derar.dev/blog/secrets-management-vault-sops-workload-identity-2026).

Quick audit of your RLS posture:

```sql
-- Which tables hold tenant_id but lack RLS? (should return zero rows)
SELECT c.relname
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 n.nspname = 'public' AND c.relkind = 'r'
  AND NOT (c.relrowsecurity AND c.relforcerowsecurity);

-- Which roles can bypass RLS?
SELECT rolname, rolsuper, rolbypassrls FROM pg_roles WHERE rolsuper OR rolbypassrls;

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

Run the first query in CI. It turns "forgot to enable RLS on the new table" into a failing build.

## Carrying the tenant context: SET LOCAL and connection pooling

The policy reads `app.tenant_id`. The application must set it per request, safely.

### Three ways to set it

| Statement | Scope | Safe with transaction pooling? |
| --- | --- | --- |
| `SET app.tenant_id = '...'` | Session (the whole connection until reset) | **No**: value persists on the pooled connection and leaks to the next client |
| `SET LOCAL app.tenant_id = '...'` | Current transaction only; reverts at COMMIT or ROLLBACK | **Yes** |
| `SELECT set_config('app.tenant_id', '...', true)` | Third argument `true` = local to the transaction (same as SET LOCAL) | **Yes**, and it accepts bind parameters |

`SET LOCAL` cannot take a bind parameter (it is a utility statement), so concatenating a value into it is an injection risk. **Use `set_config` with a parameter**:

```sql
BEGIN;
SELECT set_config('app.tenant_id', $1, true);   -- $1 bound by the driver
-- ... all queries for this request ...
COMMIT;
```

### Why this matters with PgBouncer and other poolers

PgBouncer in **transaction pooling** mode assigns a server connection to a client only for the duration of a transaction, then returns it to the pool. Session state (`SET`, advisory locks, prepared statements in older versions, `LISTEN`) does not follow the client. Two consequences:

```text
Client A: SET app.tenant_id = 'A';  (autocommit; transaction ends immediately)
Client B: gets the same server connection; runs SELECT * FROM invoices;
          -> still sees tenant A's setting  (data leak)   [session-level SET]

Client A: BEGIN; SELECT set_config('app.tenant_id','A',true); ...; COMMIT;
Client B: gets the same server connection; setting reverted at COMMIT  [safe]
```

Rules:

1. **Every request that touches tenant data runs in a transaction that begins with `set_config(..., true)`.**
2. **Never use session-level `SET` for tenant context** when any pooler (PgBouncer, RDS Proxy, Supavisor, Neon pooler, pgcat, Pgpool) sits between the app and the database.
3. **Fail closed when the context is missing.** A query run without a transaction or without the setting sees nothing, because the policy compares to NULL.
4. **Do not rely on `server_reset_query`** (which only applies in session pooling mode, and is not run in transaction mode).
5. Keep transactions short: you now hold the connection for the entire request transaction. Do not call external APIs inside it.
6. **Prepared statements and PgBouncer**: transaction pooling historically broke protocol-level prepared statements; recent PgBouncer versions support them with `max_prepared_statements`. Verify your PgBouncer version and driver settings.

A PgBouncer snippet:

```ini
; pgbouncer.ini (fragment)
[databases]
app = host=db.internal port=5432 dbname=app

[pgbouncer]
pool_mode = transaction
max_client_conn = 2000
default_pool_size = 20
; protocol-level prepared statements in transaction mode (PgBouncer 1.21+; verify your version)
max_prepared_statements = 200
auth_type = scram-sha-256
```

### Setting the context in different languages

```ts
// node-postgres: one transaction per request, tenant context first
import { Pool } from "pg";

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

export async function withTenant<T>(
  tenantId: string,
  fn: (client: import("pg").PoolClient) => Promise<T>,
): Promise<T> {
  const client = await pool.connect();
  try {
    await client.query("BEGIN");
    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();
  }
}
```

```python
# psycopg 3
import psycopg
from contextlib import contextmanager

@contextmanager
def tenant_tx(pool, tenant_id: str):
    with pool.connection() as conn:
        with conn.transaction():
            conn.execute("SELECT set_config('app.tenant_id', %s, true)", (tenant_id,))
            yield conn
```

```php
// PDO
function withTenant(PDO $pdo, string $tenantId, callable $fn) {
    $pdo->beginTransaction();
    try {
        $stmt = $pdo->prepare("SELECT set_config('app.tenant_id', :t, true)");
        $stmt->execute(['t' => $tenantId]);
        $result = $fn($pdo);
        $pdo->commit();
        return $result;
    } catch (Throwable $e) {
        $pdo->rollBack();
        throw $e;
    }
}
```

Validate that `tenantId` is a UUID **before** it reaches the database. It should come from a verified source (session, signed token, resolved host) and never straight from a request header the client controls.

### Alternatives to a setting variable

| Alternative | Idea | Trade-off |
| --- | --- | --- |
| Role per tenant (`SET ROLE tenant_x`) with policies based on `current_user` | Real database identity per tenant | Role explosion; poor with poolers; hard at scale |
| JWT claims as settings (Supabase style: `request.jwt.claims`) | Policy reads claims from a transaction-local setting set by the API layer | Works well when the platform sets it for you; same transaction-scoping rules apply |
| Session variable with a session pooler | Simpler | Only safe if each client gets a dedicated connection for its lifetime |

## Putting it together: policies for every table

A repeatable pattern so no table is forgotten:

```sql
CREATE OR REPLACE FUNCTION enable_tenant_rls(tbl regclass) RETURNS void
LANGUAGE plpgsql AS $$
BEGIN
  EXECUTE format('ALTER TABLE %s ENABLE ROW LEVEL SECURITY', tbl);
  EXECUTE format('ALTER TABLE %s FORCE ROW LEVEL SECURITY', tbl);
  EXECUTE format('DROP POLICY IF EXISTS tenant_isolation ON %s', tbl);
  EXECUTE format(
    'CREATE POLICY tenant_isolation ON %s
       USING (tenant_id = (SELECT app_current_tenant()))
       WITH CHECK (tenant_id = (SELECT app_current_tenant()))', tbl);
END $$;

SELECT enable_tenant_rls('customers');
SELECT enable_tenant_rls('invoices');
SELECT enable_tenant_rls('invoice_items');
```

Special tables:

```sql
-- memberships: a user may see their own memberships across tenants (for the tenant switcher),
-- but only members with admin role may modify within the current tenant.
ALTER TABLE memberships ENABLE ROW LEVEL SECURITY;
ALTER TABLE memberships FORCE ROW LEVEL SECURITY;

CREATE POLICY memberships_read_own ON memberships FOR SELECT
  USING (user_id = NULLIF(current_setting('app.user_id', true), '')::uuid
         OR tenant_id = (SELECT app_current_tenant()));

CREATE POLICY memberships_write_in_tenant ON memberships FOR ALL
  USING (tenant_id = (SELECT app_current_tenant()))
  WITH CHECK (tenant_id = (SELECT app_current_tenant()));

-- tenants table: the current tenant can read its own row; creation goes through an admin path
ALTER TABLE tenants ENABLE ROW LEVEL SECURITY;
ALTER TABLE tenants FORCE ROW LEVEL SECURITY;
CREATE POLICY tenants_read_self ON tenants FOR SELECT
  USING (id = (SELECT app_current_tenant()));
```

Per-command policies are sometimes better when reads and writes differ, for example read-only roles inside a tenant:

```sql
CREATE POLICY invoices_select ON invoices FOR SELECT
  USING (tenant_id = (SELECT app_current_tenant()));

CREATE POLICY invoices_modify ON invoices FOR ALL
  USING (tenant_id = (SELECT app_current_tenant())
         AND NULLIF(current_setting('app.role', true), '') IN ('owner', 'admin', 'member'))
  WITH CHECK (tenant_id = (SELECT app_current_tenant())
         AND NULLIF(current_setting('app.role', true), '') IN ('owner', 'admin', 'member'));
```

Intra-tenant roles (viewer versus admin) can live in RLS as shown, but keep that logic in the application unless you want the database to enforce it; mixing too much into policies makes them slow and hard to reason about.

## Noisy neighbors, quotas and fairness

In a shared schema one tenant's heavy query affects everyone. RLS gives isolation of **data**, not of **resources**.

| Problem | Mitigations |
| --- | --- |
| Expensive query by one tenant | `statement_timeout` per request (`SET LOCAL statement_timeout = '5s'`); `idle_in_transaction_session_timeout`; query review and pagination limits |
| Connection hogging | Pooler limits; per-tenant concurrency limit in the app (semaphore or queue); separate pools for background jobs |
| Large imports and exports | Run in queues with per-tenant concurrency of one; use read replicas for exports |
| Storage growth | Per-tenant quotas tracked in a table or by periodic aggregation; enforce at the app level |
| Lock contention | Keep transactions short; avoid cross-tenant batch updates; use `SKIP LOCKED` for queues |
| Autovacuum and bloat dominated by a big tenant | Partition hot tables by `tenant_id` hash or move the whale to a dedicated database |
| Hot rows or sequences shared by all | Per-tenant counters with advisory locks or per-tenant sequences tables; avoid a single global counter |

```sql
-- Per-request guardrails, set in the same transaction as the tenant context
SELECT set_config('app.tenant_id', $1, true);
SET LOCAL statement_timeout = '5s';
SET LOCAL lock_timeout = '2s';
SET LOCAL idle_in_transaction_session_timeout = '10s';
```

```sql
-- Per-tenant daily usage and quota enforcement (application checks before expensive actions)
CREATE TABLE tenant_usage (
  tenant_id uuid NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
  day       date NOT NULL,
  api_calls bigint NOT NULL DEFAULT 0,
  storage_bytes bigint NOT NULL DEFAULT 0,
  PRIMARY KEY (tenant_id, day)
);
```

### Moving a noisy tenant out

With a `placement` column and a routing layer, you can migrate a large tenant to its own database:

1. Provision the dedicated database with the same schema and RLS.
2. Copy the tenant's data with logical replication or a batched copy filtered by `tenant_id`.
3. Put the tenant into read-only mode briefly, catch up, flip `placement` to `dedicated_db`.
4. Verify counts and checksums, then delete from the pool after a retention period.

```sql
-- Logical replication of one tenant's rows (PG15+ supports row filters on publications)
CREATE PUBLICATION pub_tenant_acme FOR TABLE
  customers WHERE (tenant_id = '00000000-0000-0000-0000-00000000acme'::uuid),
  invoices  WHERE (tenant_id = '00000000-0000-0000-0000-00000000acme'::uuid);
```

(The UUID above is a placeholder that illustrates shape; real UUIDs are hex only.) Row filters require the filter column to be part of the replica identity for updates and deletes; verify the restrictions for your version in the logical replication docs.

## Backup, restore, export and deletion per tenant

Shared schema means **one physical backup for all tenants**. That is great for disaster recovery and awkward for tenant-level requests.

| Need | Shared schema | Schema per tenant | Database per tenant |
| --- | --- | --- | --- |
| Disaster recovery (everything) | PITR, base backups | Same | Same per cluster |
| Restore one tenant to a point in time | Restore PITR to a scratch cluster, extract the tenant's rows, merge back carefully | Restore to scratch, `pg_dump -n` that schema | Restore that database alone |
| Export tenant data (portability, offboarding) | Query by `tenant_id` into files | `pg_dump -n tenant_x` | `pg_dump` the database |
| Delete tenant data (right to erasure, churn) | Batched deletes by `tenant_id`, plus caches, search, object storage, backups policy | `DROP SCHEMA ... CASCADE` | `DROP DATABASE` |

### Exporting a tenant (shared schema)

```bash
# Export one tenant's rows as CSV through a role that has RLS applied (the app role with context)
psql "$DATABASE_URL" <<'SQL'
BEGIN;
SELECT set_config('app.tenant_id', '3f6b1d2e-0c1a-4b7e-9a55-1f2f3a4b5c6d', true);
\copy (SELECT * FROM invoices) TO 'invoices.csv' WITH CSV HEADER
\copy (SELECT * FROM customers) TO 'customers.csv' WITH CSV HEADER
COMMIT;
SQL
```

Because RLS is applied, the export cannot contain another tenant's rows, even if someone edits the query carelessly. That is a nice property for a feature that is dangerous when wrong.

### Deleting a tenant (GDPR erasure and offboarding)

Deletion has more targets than the primary database:

```text
Tenant deletion checklist
  [ ] Mark tenant status = 'deleting' (blocks logins and writes)
  [ ] Export data for the customer if contractually required
  [ ] Delete rows in dependency order, in batches (shared schema)
  [ ] Delete object storage prefix (files, uploads, exports)
  [ ] Delete search index and vector embeddings
  [ ] Purge caches (Redis keys by tenant prefix), queues, scheduled jobs
  [ ] Delete from analytics, logs where personal data appears, and third-party processors
  [ ] Revoke API keys, webhooks, SSO configuration
  [ ] Backups: document retention window (backups age out), or use per-tenant encryption keys (crypto-shredding)
  [ ] Record a deletion receipt (tenant ID, time, scope) without personal data
```

```sql
-- Batched delete to avoid long locks and huge WAL spikes (run as app_admin or with the tenant context)
DO $$
DECLARE
  rows_deleted int;
BEGIN
  LOOP
    DELETE FROM invoice_items
    WHERE ctid IN (
      SELECT ctid FROM invoice_items WHERE tenant_id = '3f6b1d2e-0c1a-4b7e-9a55-1f2f3a4b5c6d' LIMIT 5000
    );
    GET DIAGNOSTICS rows_deleted = ROW_COUNT;
    EXIT WHEN rows_deleted = 0;
    COMMIT;
  END LOOP;
END $$;
```

`COMMIT` inside a `DO` block works in PostgreSQL 11 and later when the block is not inside an outer transaction. If you rely on `ON DELETE CASCADE` from `tenants`, a single delete of the tenant row can cascade across millions of rows in one transaction; for large tenants, delete children in batches first.

Backups still contain the data after deletion. Regulators generally accept documented retention windows for backups when restores do not reintroduce deleted data. Document a **restore-time re-deletion procedure** (replay a deletion ledger after any restore). Verify legal requirements with your counsel.

### Per-tenant encryption (crypto-shredding)

For highly sensitive columns, encrypt with a per-tenant data key held in a KMS. Deleting the key renders all copies, backups included, unreadable. The costs are complexity, no ability to index or search encrypted columns, and key management overhead. Use it for the genuinely sensitive fields (documents, notes, personal data), not for every column.

## Migrations at scale

### Shared schema: one migration, but make it safe

The migration runs once against one database, but the tables are huge and shared by every customer, so locks affect everyone. Apply the **expand and contract** pattern and non-blocking DDL; the details are in [Zero-Downtime Postgres Migrations](https://www.derar.dev/blog/zero-downtime-postgres-migrations-2026). Tenant-specific considerations:

| Task | Safe approach |
| --- | --- |
| Add a nullable column | `ALTER TABLE ... ADD COLUMN` is metadata-only (also with a constant default on modern versions) |
| Add `tenant_id` to an existing table | Add nullable, backfill in batches by tenant, add `NOT VALID` constraint and `VALIDATE` later, then `SET NOT NULL` (use a validated `CHECK` first to avoid a full scan under lock on older versions) |
| Add an index | `CREATE INDEX CONCURRENTLY` with `tenant_id` first |
| Add RLS policy | Takes brief locks; test on a staging copy with production-sized data; add policy before enabling `FORCE` to avoid locking out the app (see the rollout plan near the end) |
| Backfill | Loop in small batches, per tenant, with sleeps; monitor replication lag |
| Rename or change types | Expand and contract with dual writes |

```sql
-- Adding tenant_id to a legacy table safely
ALTER TABLE legacy_orders ADD COLUMN tenant_id uuid;                       -- fast, nullable
-- backfill in batches (application or script) from the owning account:
UPDATE legacy_orders o SET tenant_id = a.tenant_id
FROM accounts a
WHERE o.account_id = a.id AND o.tenant_id IS NULL AND o.id IN (
  SELECT id FROM legacy_orders WHERE tenant_id IS NULL LIMIT 10000
);
ALTER TABLE legacy_orders ADD CONSTRAINT legacy_orders_tenant_nn CHECK (tenant_id IS NOT NULL) NOT VALID;
ALTER TABLE legacy_orders VALIDATE CONSTRAINT legacy_orders_tenant_nn;     -- scans without blocking writes
ALTER TABLE legacy_orders ALTER COLUMN tenant_id SET NOT NULL;             -- fast when a validated CHECK exists (PG12+)
CREATE INDEX CONCURRENTLY legacy_orders_tenant_idx ON legacy_orders (tenant_id, created_at);
```

### Schema or database per tenant: migrations as a fleet operation

Here every migration runs N times. Design the runner like a deployment system.

| Concern | Practice |
| --- | --- |
| Tracking | A central `tenant_migrations` table (tenant, version, status, started, finished, error) or the migration tool's per-schema table |
| Ordering | Migrate in waves: canary tenants first, then batches, with a stop-on-error threshold |
| Compatibility | The app must work with the schema at version N and N+1 during rollout (expand and contract, again) |
| Failures | A tenant stuck on an old version must not take the app down; the app reads the tenant's schema version and uses a compatible code path, or blocks that tenant only |
| Concurrency | Limit parallelism to protect the cluster; per-tenant locks to avoid double-runs |
| Idempotency | Migrations safe to re-run; use `IF NOT EXISTS` carefully and test it |
| New tenant | Create from the latest baseline schema snapshot plus pending migrations |
| Drift detection | Periodically compare each tenant's schema to the expected one (hash of `information_schema`) |

```ts
// A fleet migration runner sketch (TypeScript, node-postgres). Adapt to your migration tool.
import { Pool } from "pg";

type Tenant = { id: string; schema: string };

export async function migrateAll(tenants: Tenant[], migrate: (client: any, schema: string) => Promise<void>) {
  const admin = new Pool({ connectionString: process.env.MIGRATOR_URL, max: 4 });
  const results: { tenant: string; ok: boolean; error?: string }[] = [];
  const queue = [...tenants];

  async function worker() {
    while (queue.length) {
      const t = queue.shift()!;
      const client = await admin.connect();
      try {
        await client.query("SELECT pg_advisory_lock(hashtext($1))", [t.schema]);
        await client.query(`SET search_path TO ${client.escapeIdentifier(t.schema)}`);
        await migrate(client, t.schema);
        results.push({ tenant: t.id, ok: true });
      } catch (e: any) {
        results.push({ tenant: t.id, ok: false, error: String(e.message) });
      } finally {
        await client.query("SELECT pg_advisory_unlock(hashtext($1))", [t.schema]).catch(() => {});
        client.release();
      }
      const failures = results.filter((r) => !r.ok).length;
      if (failures > 3) { queue.length = 0; } // stop the wave if too many tenants fail
    }
  }
  await Promise.all(Array.from({ length: 4 }, worker));
  return results;
}
```

Catalog limits: thousands of schemas each with dozens of tables mean hundreds of thousands of relations, which slows `pg_dump`, planning (`search_path` lookups), autovacuum and backups. This is the main reason schema-per-tenant tops out in the low thousands.

### Extra safety rules for RLS migrations

- **Never disable RLS in a migration "temporarily"** on a live system; the window is a breach window.
- **Migrations run as the owner (`migrator`/`app_owner`)**, never as the app role, and never rely on owner bypass for data fixes without logging them.
- **A CI check** that fails if any table with `tenant_id` lacks `FORCE ROW LEVEL SECURITY` and a policy (the query in the RLS section).
- Code-review rule: any new table either has `tenant_id` plus the RLS helper call, or has a written justification to be global.

## Testing tenant isolation

Tests are what make RLS trustworthy. Write adversarial tests against a **real Postgres** (Testcontainers or a CI service container), connecting as the **runtime role**, not as a superuser. Tests that run as the owner pass trivially because the owner bypasses RLS.

### What to test

| Test | Expectation |
| --- | --- |
| Read as tenant A | Only A's rows |
| Read with no tenant context | Zero rows (fail closed) |
| Read with a malformed or empty tenant ID | Error or zero rows, never all rows |
| Insert a row with tenant B's ID while in tenant A | Error (WITH CHECK violation) |
| Update a row to change its `tenant_id` | Error |
| Update or delete B's row by primary key as A | Zero rows affected |
| Insert a child row referencing B's parent while in A | Foreign key error (composite FK) |
| Join across tables | No B rows appear |
| Aggregate (`count(*)`, `sum`) | Counts only A's rows |
| `INSERT ... ON CONFLICT DO UPDATE` on a conflicting B key | Does not update B's row, no information leaked |
| Views and functions | Respect isolation (`security_invoker`, no definer leaks) |
| New table introduced in the last migration | Has RLS enabled and forced |
| Context leakage after COMMIT | A new transaction without context sees nothing, including through a pooler |
| Concurrent requests with different tenants | No cross-contamination (shared connections reused) |

### Test suite in TypeScript with Vitest

```ts
// tests/tenant-isolation.test.ts
import { describe, it, expect, beforeAll, afterAll } from "vitest";
import { Pool } from "pg";

const admin = new Pool({ connectionString: process.env.TEST_ADMIN_URL });   // owner: seeds data
const app = new Pool({ connectionString: process.env.TEST_APP_URL });       // app_user: subject of the tests

const A = "11111111-1111-1111-1111-111111111111";
const B = "22222222-2222-2222-2222-222222222222";

async function asTenant<T>(tenant: string | null, fn: (q: (sql: string, p?: any[]) => Promise<any>) => Promise<T>) {
  const c = await app.connect();
  try {
    await c.query("BEGIN");
    if (tenant) await c.query("SELECT set_config('app.tenant_id', $1, true)", [tenant]);
    const out = await fn((sql, p) => c.query(sql, p));
    await c.query("ROLLBACK");
    return out;
  } catch (e) {
    await c.query("ROLLBACK");
    throw e;
  } finally {
    c.release();
  }
}

beforeAll(async () => {
  await admin.query(`INSERT INTO tenants (id, slug, name) VALUES ($1,'tenant-a','A'), ($2,'tenant-b','B') ON CONFLICT DO NOTHING`, [A, B]);
  await admin.query(`INSERT INTO customers (tenant_id, id, email, name) VALUES
    ($1, gen_random_uuid(), 'a@example.test', 'Cust A'),
    ($2, gen_random_uuid(), 'b@example.test', 'Cust B')`, [A, B]);
});

afterAll(async () => {
  await admin.query("DELETE FROM tenants WHERE id IN ($1,$2)", [A, B]);
  await admin.end(); await app.end();
});

describe("row level security", () => {
  it("shows only the current tenant's rows", async () => {
    const rows = await asTenant(A, (q) => q("SELECT email FROM customers"));
    expect(rows.rows.map((r: any) => r.email)).toEqual(["a@example.test"]);
  });

  it("fails closed without a tenant context", async () => {
    const rows = await asTenant(null, (q) => q("SELECT * FROM customers"));
    expect(rows.rowCount).toBe(0);
  });

  it("blocks inserting rows for another tenant", async () => {
    await expect(
      asTenant(A, (q) => q("INSERT INTO customers (tenant_id, email, name) VALUES ($1, 'x@example.test', 'X')", [B])),
    ).rejects.toThrow(/row-level security/);
  });

  it("blocks moving a row to another tenant", async () => {
    await expect(
      asTenant(A, (q) => q("UPDATE customers SET tenant_id = $1", [B])),
    ).rejects.toThrow(/row-level security/);
  });

  it("cannot update or delete another tenant's rows", async () => {
    const upd = await asTenant(A, (q) => q("UPDATE customers SET name = 'pwned' WHERE email = 'b@example.test'"));
    expect(upd.rowCount).toBe(0);
    const del = await asTenant(A, (q) => q("DELETE FROM customers WHERE email = 'b@example.test'"));
    expect(del.rowCount).toBe(0);
  });

  it("does not leak the tenant context to the next transaction on the same connection", async () => {
    const c = await app.connect();
    try {
      await c.query("BEGIN");
      await c.query("SELECT set_config('app.tenant_id', $1, true)", [A]);
      await c.query("COMMIT");
      const r = await c.query("SELECT count(*)::int AS n FROM customers");
      expect(r.rows[0].n).toBe(0);
    } finally { c.release(); }
  });

  it("every table with tenant_id has RLS enabled and forced", async () => {
    const r = await admin.query(`
      SELECT c.relname 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 n.nspname = 'public' AND c.relkind = 'r' AND NOT (c.relrowsecurity AND c.relforcerowsecurity)`);
    expect(r.rows).toEqual([]);
  });

  it("app role cannot bypass RLS", async () => {
    const r = await admin.query("SELECT rolsuper, rolbypassrls FROM pg_roles WHERE rolname = 'app_user'");
    expect(r.rows[0]).toEqual({ rolsuper: false, rolbypassrls: false });
  });
});
```

### Canary rows and property-based checks

Seed each tenant with **canary values** (a unique string such as `CANARY-tenantB-9f3c`) in every text column that can be searched, and have the test suite assert that canaries of tenant B never appear in any API response while acting as tenant A. For API-level tests, generate the matrix from your route list: for each endpoint, call it as tenant A with tenant B's resource IDs and expect 404.

### Test in the layers above the database

Also test search indexes, caches, background jobs and file storage keys for tenant scoping, because RLS only protects PostgreSQL. A tenant-prefixed cache key (`t:<tenant>:...`) and object keys (`tenants/<tenant>/...`) are the equivalents.

```sql
-- Verify planner behavior and policy in a psql session as the app role
SET ROLE app_user;
SELECT set_config('app.tenant_id', '11111111-1111-1111-1111-111111111111', false);
EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM invoices WHERE created_at > now() - interval '30 days';
RESET ROLE;
```

## ORM and framework integration

The pattern is the same everywhere: **one transaction per request, set the tenant with `set_config(..., true)` first, then run queries on that same connection.** The risk is ORMs that run each query on whichever pooled connection is free. If the setting is not on the same connection and transaction as the query, the query sees nothing (fail closed) or, worse, someone else's context if you used session-level SET.

### Prisma

Prisma runs queries through its own connection pool; to keep context and queries together, use an interactive transaction or a client extension that wraps each operation.

```ts
// lib/db.ts
import { PrismaClient } from "@prisma/client";

const base = new PrismaClient({ datasourceUrl: process.env.DATABASE_URL }); // app_user

export function tenantClient(tenantId: string) {
  return base.$extends({
    query: {
      $allModels: {
        async $allOperations({ args, query }) {
          // Wrap each operation in a transaction that sets the tenant first
          const [, result] = await base.$transaction([
            base.$executeRaw`SELECT set_config('app.tenant_id', ${tenantId}, true)`,
            query(args),
          ]);
          return result;
        },
      },
    },
  });
}
```

This pattern (batch transaction with `set_config` followed by the operation) is the commonly documented approach; Prisma's extension and transaction APIs evolve, so verify against the current Prisma docs. For multi-statement units of work, prefer an explicit interactive transaction:

```ts
export async function withTenant<T>(tenantId: string, fn: (tx: Prisma.TransactionClient) => Promise<T>) {
  return base.$transaction(async (tx) => {
    await tx.$executeRaw`SELECT set_config('app.tenant_id', ${tenantId}, true)`;
    return fn(tx);
  });
}

// usage
const invoices = await withTenant(tenantId, (tx) => tx.invoice.findMany({ take: 50, orderBy: { createdAt: "desc" } }));
```

Notes: Prisma's schema supports composite ids (`@@id([tenantId, id])`) and composite relations (`@relation(fields: [tenantId, customerId], references: [tenantId, id])`). Migrations (RLS policies, `FORCE`, roles) go in custom SQL migration files, because Prisma's schema language does not model policies. Use a separate `DIRECT_URL` as the migrator role. Remember `$queryRawUnsafe` and `$executeRawUnsafe` stay dangerous.

### Drizzle

Drizzle exposes `pgPolicy` helpers for declaring RLS in the schema in recent versions (verify the current API), and plain SQL works everywhere.

```ts
// db.ts
import { drizzle } from "drizzle-orm/node-postgres";
import { sql } from "drizzle-orm";
import { Pool } from "pg";
import * as schema from "./schema";

const db = drizzle(new Pool({ connectionString: process.env.DATABASE_URL }), { schema });

export async function withTenant<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);
  });
}
```

```ts
// schema.ts (composite primary key and tenant-scoped uniqueness)
import { pgTable, uuid, text, bigint, timestamp, primaryKey, unique, index, foreignKey } from "drizzle-orm/pg-core";

export const customers = pgTable("customers", {
  tenantId: uuid("tenant_id").notNull(),
  id: uuid("id").notNull().defaultRandom(),
  email: text("email").notNull(),
  name: text("name").notNull(),
}, (t) => [
  primaryKey({ columns: [t.tenantId, t.id] }),
  unique().on(t.tenantId, t.email),
]);

export const invoices = pgTable("invoices", {
  tenantId: uuid("tenant_id").notNull(),
  id: uuid("id").notNull().defaultRandom(),
  customerId: uuid("customer_id").notNull(),
  number: text("number").notNull(),
  totalCents: bigint("total_cents", { mode: "number" }).notNull(),
  createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
}, (t) => [
  primaryKey({ columns: [t.tenantId, t.id] }),
  unique().on(t.tenantId, t.number),
  foreignKey({ columns: [t.tenantId, t.customerId], foreignColumns: [customers.tenantId, customers.id] }),
  index("invoices_tenant_created_idx").on(t.tenantId, t.createdAt),
]);
```

The array-returning third argument form is the newer Drizzle table API; older versions used an object. Verify against your installed version.

### Django

Django has no built-in RLS, but the context approach is simple: wrap each request in `transaction.atomic()` and set the config on the same connection.

```python
# tenancy/middleware.py
from django.db import connection, transaction

class TenantMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        tenant_id = resolve_tenant_id(request)          # from verified host or session; validated UUID
        if tenant_id is None:
            return self.get_response(request)           # no context: RLS returns nothing
        with transaction.atomic():
            with connection.cursor() as cur:
                cur.execute("SELECT set_config('app.tenant_id', %s, true)", [str(tenant_id)])
            return self.get_response(request)
```

Caveats: `ATOMIC_REQUESTS = True` wraps views in a transaction but your middleware must set the config **inside** it, on the same connection; with `CONN_MAX_AGE` and persistent connections, transaction-local settings are still safe. With PgBouncer transaction pooling, set `DISABLE_SERVER_SIDE_CURSORS = True`. Define RLS in `RunSQL` migrations, and run them as the owner role using a separate database alias for migrations. Libraries such as `django-tenants` implement schema-per-tenant; for RLS-based approaches check maintained packages or keep it in-house as above.

```python
# migrations/0007_rls_invoices.py
from django.db import migrations

class Migration(migrations.Migration):
    dependencies = [("billing", "0006_invoices")]
    operations = [
        migrations.RunSQL(
            sql=[
                "ALTER TABLE billing_invoice ENABLE ROW LEVEL SECURITY;",
                "ALTER TABLE billing_invoice FORCE ROW LEVEL SECURITY;",
                "CREATE POLICY tenant_isolation ON billing_invoice "
                "USING (tenant_id = (SELECT app_current_tenant())) "
                "WITH CHECK (tenant_id = (SELECT app_current_tenant()));",
            ],
            reverse_sql=["DROP POLICY tenant_isolation ON billing_invoice;"],
        )
    ]
```

### Laravel

Laravel packages like `stancl/tenancy` focus on database or schema per tenant; for shared-schema RLS, set the context in middleware inside a transaction.

```php
// app/Http/Middleware/SetTenantContext.php
namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class SetTenantContext
{
    public function handle(Request $request, Closure $next)
    {
        $tenantId = $request->attributes->get('tenant_id'); // resolved and validated earlier
        if (! $tenantId) {
            return $next($request); // no context: queries return nothing
        }

        return DB::transaction(function () use ($request, $next, $tenantId) {
            DB::select("SELECT set_config('app.tenant_id', ?, true)", [$tenantId]);
            return $next($request);
        });
    }
}
```

Eloquent global scopes (`addGlobalScope`) add `where tenant_id = ?` for convenience and better query plans; RLS stays as the backstop. Use a separate `migrations` connection that connects as the owner role, and keep queue workers inside the same pattern: **jobs must carry the tenant ID in the payload and call the same context wrapper**, because there is no HTTP middleware in a worker.

### Raw SQL, reports and background jobs

| Entry point | Rule |
| --- | --- |
| Queue workers and cron | Tenant ID in the job payload; wrap in the same `withTenant` helper |
| Reports and analytics across tenants | Use the `app_admin` role (BYPASSRLS), a read replica, and an allow-listed code path with audit logs |
| Admin and support tools | Impersonation with a logged reason and short TTL; set the tenant context, do not bypass |
| Migrations and data fixes | `migrator` role, reviewed scripts, logged |
| Ad hoc `psql` by engineers | Read-only role with RLS applied; BYPASSRLS access via break-glass |

## Next.js: resolving the tenant and setting the context

In a Next.js app, resolving the tenant happens at the edge of the request, and setting the database context happens inside server code that talks to Postgres.

### Resolving the tenant

| Strategy | Example | Notes |
| --- | --- | --- |
| Subdomain | `acme.app.example.com` | Clean separation; needs wildcard DNS and TLS |
| Custom domain | `app.acme.com` | Lookup table domain to tenant; verify domain ownership before enabling |
| Path | `/t/acme/...` | Easy; shared cookies across tenants need care |
| Session claim | `tenant_id` in the session after the user picks an org | Best for multi-membership users; always verify membership |

Never trust a tenant identifier supplied by the client without verifying that the authenticated user has a membership in that tenant. The host or path tells you what the user is **asking for**; the session and membership table tell you what they are **allowed** to access.

```ts
// proxy.ts  (Next.js 16 renamed the middleware file convention to proxy; verify against the docs for your version)
import { NextResponse, type NextRequest } from "next/server";

const ROOT = "app.example.com";

export function proxy(req: NextRequest) {
  const host = req.headers.get("host") ?? "";
  const sub = host.endsWith(`.${ROOT}`) ? host.slice(0, -(ROOT.length + 1)) : null;

  const headers = new Headers(req.headers);
  headers.delete("x-tenant-slug");            // never trust an inbound value
  if (sub) headers.set("x-tenant-slug", sub); // only the proxy sets it

  return NextResponse.next({ request: { headers } });
}

export const config = { matcher: ["/((?!_next/static|_next/image|favicon.ico).*)"] };
```

The edge or proxy layer resolves a **slug**; the server resolves slug to tenant ID and verifies membership. Keep database access out of the proxy where possible (it may run in a restricted runtime) and do the lookup in a server function.

### Server-side access pattern

```ts
// lib/tenant.ts
import { headers } from "next/headers";
import { cache } from "react";
import { getSession } from "@/lib/auth";
import { adminDb } from "@/lib/admin-db";

export const getTenantContext = cache(async () => {
  const slug = (await headers()).get("x-tenant-slug");
  const session = await getSession();
  if (!slug || !session) throw new Response("Unauthorized", { status: 401 });

  // Membership lookup uses the global tables; the user is allowed to act as this tenant?
  const row = await adminDb.query(
    `SELECT t.id AS tenant_id, m.role
       FROM tenants t JOIN memberships m ON m.tenant_id = t.id
      WHERE t.slug = $1 AND m.user_id = $2 AND t.status = 'active'`,
    [slug, session.userId],
  );
  if (row.rowCount === 0) throw new Response("Not found", { status: 404 });
  return { tenantId: row.rows[0].tenant_id as string, role: row.rows[0].role as string, userId: session.userId };
});
```

```ts
// app/(app)/invoices/page.tsx
import { getTenantContext } from "@/lib/tenant";
import { withTenant } from "@/lib/db";

export default async function InvoicesPage() {
  const { tenantId } = await getTenantContext();
  const invoices = await withTenant(tenantId, (c) =>
    c.query("SELECT id, number, total_cents, created_at FROM invoices ORDER BY created_at DESC LIMIT 50"),
  );
  return (
    <ul>
      {invoices.rows.map((i) => (
        <li key={i.id}>{i.number}: {(i.total_cents / 100).toFixed(2)}</li>
      ))}
    </ul>
  );
}
```

Points to remember:

1. **Server Components, Route Handlers and Server Actions** each need the context wrapper. Put it in one helper so they cannot skip it. A convention such as "all DB access goes through `withTenant` or `withAdmin`" can be enforced by an ESLint rule or by simply not exporting the raw pool.
2. **Caching.** Next.js data caches and `fetch` caches are keyed by URL or function arguments, not by tenant. Include the tenant ID in every cache key and tag (`unstable_cache` keys, `cacheTag("t:<tenant>:invoices")`). A cache entry without a tenant in its key is a cross-tenant leak that RLS cannot see. Verify the current caching APIs in the Next.js docs, since they changed a lot across recent versions.
3. **Streaming and long requests.** The transaction (and pooled connection) lives only inside `withTenant`. Avoid holding it open while rendering or calling third parties.
4. **Edge runtime.** Use a driver and pooler that fit the runtime (serverless drivers over HTTP or WebSocket, or a pooled endpoint). The same `set_config` in a transaction rule applies; some HTTP-based drivers batch statements in a single transaction call, which can fit this pattern well.
5. **Authorization still matters.** RLS proves "this row belongs to this tenant". It does not decide whether a `viewer` may delete an invoice. Keep role checks in the application, see [OWASP Top 10 for Developers](https://www.derar.dev/blog/owasp-top-10-for-developers-practical-fixes-2026) for the broken access control patterns.

### Server Actions

```ts
"use server";
import { z } from "zod";
import { getTenantContext } from "@/lib/tenant";
import { withTenant } from "@/lib/db";

const NewInvoice = z.object({ customerId: z.string().uuid(), number: z.string().min(1).max(40), totalCents: z.number().int().nonnegative() });

export async function createInvoice(input: unknown) {
  const { tenantId, role } = await getTenantContext();
  if (role === "viewer") throw new Error("forbidden");
  const data = NewInvoice.parse(input);
  return withTenant(tenantId, async (c) => {
    // tenant_id is set from the context, never from the client
    const r = await c.query(
      "INSERT INTO invoices (tenant_id, customer_id, number, total_cents) VALUES ($1, $2, $3, $4) RETURNING id",
      [tenantId, data.customerId, data.number, data.totalCents],
    );
    return r.rows[0].id as string;
  });
}
```

Even if a bug passed a different `tenantId` into the insert, the `WITH CHECK` clause would reject it. That is what defense in depth looks like.

## Performance of RLS and EXPLAIN checks

RLS adds a predicate to every query on the table. With a simple policy and the right indexes that predicate is just the `tenant_id` filter you would have written by hand. Problems appear with complex policies, missing indexes, and non-leakproof functions.

### What can go wrong

| Issue | Symptom | Fix |
| --- | --- | --- |
| `current_setting()` evaluated per row | Slow scans, high CPU | Wrap as `(SELECT current_setting(...))` so it becomes an init plan evaluated once |
| No index with `tenant_id` first | Seq scans filtered by RLS | Leading `tenant_id` indexes, see the data model section |
| Policy with subquery or join to another table | Plans get complex; repeated lookups | Keep the policy to a single-column comparison; denormalize `tenant_id` onto child tables (which composite keys already do) |
| User-defined functions in policies | Possible planner barriers | Use `STABLE` and `PARALLEL SAFE`; keep them simple |
| Non-leakproof operators in your query | The planner cannot push them below the policy qual, so index usage and row-ordering decisions suffer | Prefer built-in operators on indexed columns; leakproof status matters because security barrier quals run first |
| Function wrappers on columns (`lower(email) = ...`) without expression index | Seq scan | Expression indexes with `tenant_id` first |
| Cross-tenant admin queries through BYPASSRLS | Fine, but check plans separately | They use different plans than tenant queries |

The **leakproof** point deserves a sentence: to prevent information leaks through error messages or side effects, the planner evaluates the policy predicate before user-supplied functions unless those functions are marked `LEAKPROOF`. For ordinary equality comparisons on indexed columns this is not a problem, since built-in comparison operators are leakproof. Custom or complex operators can end up as filters applied after the policy, which hurts performance. Check plans with `EXPLAIN`.

### Reading the plan

```sql
SET ROLE app_user;
BEGIN;
SELECT set_config('app.tenant_id', '11111111-1111-1111-1111-111111111111', true);
EXPLAIN (ANALYZE, BUFFERS, VERBOSE)
SELECT id, number, total_cents FROM invoices
WHERE created_at >= now() - interval '30 days'
ORDER BY created_at DESC LIMIT 50;
ROLLBACK;
RESET ROLE;
```

What a good plan looks like:

```text
Limit  (cost=0.43..12.1 rows=50 ...) (actual time=0.05..0.31 rows=50 loops=1)
  InitPlan 1 (returns $0)
    ->  Result  (cost=0.00..0.01 rows=1 ...)
  ->  Index Scan using invoices_tenant_created_idx on invoices
        Index Cond: ((tenant_id = $0) AND (created_at >= (now() - '30 days'::interval)))
        Buffers: shared hit=8
Planning Time: 0.2 ms
Execution Time: 0.4 ms
```

Check three things: the **InitPlan** (the setting evaluated once), the **Index Cond** containing `tenant_id` (the policy predicate was used by the index), and **Buffers** that are small. A bad plan shows `Filter: (tenant_id = current_setting(...))` on a Seq Scan, or a `SubPlan` evaluated per row. See [Postgres Query Performance with EXPLAIN ANALYZE](https://www.derar.dev/blog/postgres-query-performance-explain-analyze-2026) for how to read these nodes in depth.

### Statistics and large tenants

- Planner statistics are per column across the whole table. A tenant with 90 percent of the rows skews estimates for everyone. Use `ALTER TABLE ... ALTER COLUMN tenant_id SET STATISTICS 1000` and extended statistics (`CREATE STATISTICS ... (dependencies) ON tenant_id, status`) to help.
- **Partitioning** by hash of `tenant_id` improves vacuum, index size and partition pruning for tenant-scoped queries, and RLS works with partitioned tables (policies are defined on the partitioned parent; verify behavior for direct partition access in your version).
- Generic prepared plans can be poor when tenants differ wildly in size; consider `plan_cache_mode = force_custom_plan` for the app role if you see this.
- Measure RLS overhead directly: run the same query as the owner (bypass) with an explicit `WHERE tenant_id = X` and as the app role with RLS. They should be within a few percent.

### Connection and transaction overhead

Wrapping every request in a transaction with a `set_config` call adds one cheap statement per request. You can reduce round trips by sending `set_config` and the first query in one batch (pipeline mode in recent drivers) or by combining statements into a single multi-statement call where the driver allows it.

## Auditing and observability

| What | How |
| --- | --- |
| Who changed what | Audit table written by triggers or the application: tenant, actor, table, row key, action, before and after (sparse), request ID, timestamp |
| Cross-tenant access | Log every use of `app_admin` or break-glass roles with a reason and ticket reference |
| Policy changes | Event triggers on DDL (`CREATE POLICY`, `DROP POLICY`, `ALTER TABLE ... DISABLE ROW LEVEL SECURITY`), or `pgaudit` for statement-level logging |
| Anomaly signals | Alert on queries with no tenant context, `row-level security` violation errors, spikes in `permission denied`, and RLS bypass role connections |
| Per-tenant metrics | Labelled query durations, rows returned, storage, connection usage (using `application_name` or a query comment with the tenant ID) |

```sql
-- Generic audit trigger recording the tenant and actor from the transaction context
CREATE TABLE audit_log (
  id         bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  tenant_id  uuid,
  actor_id   uuid,
  table_name text NOT NULL,
  action     text NOT NULL,
  row_key    jsonb,
  changed_at timestamptz NOT NULL DEFAULT now()
);

CREATE OR REPLACE FUNCTION audit_row() RETURNS trigger
LANGUAGE plpgsql SECURITY DEFINER SET search_path = public AS $$
BEGIN
  INSERT INTO audit_log (tenant_id, actor_id, table_name, action, row_key)
  VALUES (
    (SELECT app_current_tenant()),
    NULLIF(current_setting('app.user_id', true), '')::uuid,
    TG_TABLE_NAME, TG_OP,
    CASE WHEN TG_OP = 'DELETE' THEN to_jsonb(OLD) ->> 'id' ELSE to_jsonb(NEW) ->> 'id' END
      ::text::jsonb
  );
  RETURN NULL;
END $$;

CREATE TRIGGER invoices_audit AFTER INSERT OR UPDATE OR DELETE ON invoices
FOR EACH ROW EXECUTE FUNCTION audit_row();
```

The `SECURITY DEFINER` function runs as its owner, so it bypasses RLS on `audit_log` for the insert, which is deliberate here; pin `search_path` as shown and keep such functions minimal. Make `audit_log` append-only for the app role (`GRANT INSERT` only via the function, no `UPDATE` or `DELETE`), and ship it to external storage for tamper resistance. Enable RLS on `audit_log` for reads so tenants can see only their own audit trail.

Tag connections for visibility:

```sql
SELECT set_config('application_name', 'api:tenant:3f6b1d2e', true);  -- visible in pg_stat_activity (transaction-local)
```

## A complete working example

A compact but runnable setup: SQL for roles, schema, RLS and seeds; a TypeScript data layer; and a leak test. It follows the decisions above.

### Database setup

```sql
-- 001_roles.sql (run as a superuser or cloud admin once)
CREATE ROLE app_owner NOLOGIN;
CREATE ROLE migrator LOGIN PASSWORD 'change-me-migrator' IN ROLE app_owner;
CREATE ROLE app_user LOGIN PASSWORD 'change-me-app' NOSUPERUSER NOBYPASSRLS;
CREATE ROLE app_admin LOGIN PASSWORD 'change-me-admin' NOSUPERUSER BYPASSRLS;

CREATE DATABASE saas OWNER app_owner;
\c saas
REVOKE ALL ON DATABASE saas FROM PUBLIC;
GRANT CONNECT ON DATABASE saas TO app_user, app_admin, migrator;
ALTER SCHEMA public OWNER TO app_owner;
REVOKE CREATE ON SCHEMA public FROM PUBLIC;
GRANT USAGE ON SCHEMA public TO app_user, app_admin;
ALTER DEFAULT PRIVILEGES FOR ROLE app_owner IN SCHEMA public
  GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO app_user, app_admin;
ALTER DEFAULT PRIVILEGES FOR ROLE app_owner IN SCHEMA public
  GRANT USAGE, SELECT ON SEQUENCES TO app_user, app_admin;
```

```sql
-- 002_schema.sql (run as migrator after SET ROLE app_owner)
SET ROLE app_owner;

CREATE TABLE tenants (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  slug text NOT NULL UNIQUE,
  name text NOT NULL,
  status text NOT NULL DEFAULT 'active',
  created_at timestamptz NOT NULL DEFAULT now()
);

CREATE TABLE users (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  email text NOT NULL UNIQUE
);

CREATE TABLE memberships (
  tenant_id uuid NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
  user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
  role text NOT NULL CHECK (role IN ('owner','admin','member','viewer')),
  PRIMARY KEY (tenant_id, user_id)
);

CREATE TABLE customers (
  tenant_id uuid NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
  id uuid NOT NULL DEFAULT gen_random_uuid(),
  email text NOT NULL,
  name text NOT NULL,
  PRIMARY KEY (tenant_id, id),
  UNIQUE (tenant_id, email)
);

CREATE TABLE invoices (
  tenant_id uuid NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
  id uuid NOT NULL DEFAULT gen_random_uuid(),
  customer_id uuid NOT NULL,
  number text NOT NULL,
  total_cents bigint NOT NULL CHECK (total_cents >= 0),
  created_at timestamptz NOT NULL DEFAULT now(),
  PRIMARY KEY (tenant_id, id),
  UNIQUE (tenant_id, number),
  FOREIGN KEY (tenant_id, customer_id) REFERENCES customers (tenant_id, id)
);
CREATE INDEX invoices_tenant_created_idx ON invoices (tenant_id, created_at DESC);

CREATE OR REPLACE FUNCTION app_current_tenant() RETURNS uuid
LANGUAGE sql STABLE PARALLEL SAFE AS $$
  SELECT NULLIF(current_setting('app.tenant_id', true), '')::uuid
$$;

CREATE OR REPLACE FUNCTION enable_tenant_rls(tbl regclass) RETURNS void
LANGUAGE plpgsql AS $$
BEGIN
  EXECUTE format('ALTER TABLE %s ENABLE ROW LEVEL SECURITY', tbl);
  EXECUTE format('ALTER TABLE %s FORCE ROW LEVEL SECURITY', tbl);
  EXECUTE format('DROP POLICY IF EXISTS tenant_isolation ON %s', tbl);
  EXECUTE format('CREATE POLICY tenant_isolation ON %s
    USING (tenant_id = (SELECT app_current_tenant()))
    WITH CHECK (tenant_id = (SELECT app_current_tenant()))', tbl);
END $$;

SELECT enable_tenant_rls('customers');
SELECT enable_tenant_rls('invoices');
SELECT enable_tenant_rls('memberships');

ALTER TABLE tenants ENABLE ROW LEVEL SECURITY;
ALTER TABLE tenants FORCE ROW LEVEL SECURITY;
CREATE POLICY tenants_self ON tenants FOR SELECT USING (id = (SELECT app_current_tenant()));

RESET ROLE;
```

`users` has no RLS in this example; it is a global identity table accessed only by the authentication layer, through a role and queries you control. If your threat model includes the app role reading all users, add a policy based on membership.

```sql
-- 003_seed.sql (as app_admin, which bypasses RLS, for fixtures only)
INSERT INTO tenants (id, slug, name) VALUES
  ('11111111-1111-1111-1111-111111111111', 'acme', 'Acme Inc'),
  ('22222222-2222-2222-2222-222222222222', 'globex', 'Globex Corp');
INSERT INTO customers (tenant_id, id, email, name) VALUES
  ('11111111-1111-1111-1111-111111111111', 'aaaaaaaa-0000-0000-0000-000000000001', 'ann@acme.test', 'Ann'),
  ('22222222-2222-2222-2222-222222222222', 'bbbbbbbb-0000-0000-0000-000000000001', 'bob@globex.test', 'Bob');
```

### Application data layer (TypeScript)

```ts
// src/db.ts
import { Pool, type PoolClient } from "pg";

const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;

// Runtime pool connects as app_user (no BYPASSRLS, not the owner)
const appPool = new Pool({ connectionString: process.env.DATABASE_URL, max: 10 });
// A separate, audited pool for cross-tenant jobs; do not export it widely
const adminPool = new Pool({ connectionString: process.env.ADMIN_DATABASE_URL, max: 2 });

export async function withTenant<T>(
  tenantId: string,
  fn: (c: PoolClient) => Promise<T>,
  opts: { statementTimeoutMs?: number } = {},
): Promise<T> {
  if (!UUID.test(tenantId)) throw new Error("invalid tenant id");
  const c = await appPool.connect();
  try {
    await c.query("BEGIN");
    await c.query("SELECT set_config('app.tenant_id', $1, true)", [tenantId]);
    await c.query("SELECT set_config('statement_timeout', $1, true)", [String(opts.statementTimeoutMs ?? 5000)]);
    const out = await fn(c);
    await c.query("COMMIT");
    return out;
  } catch (e) {
    await c.query("ROLLBACK").catch(() => {});
    throw e;
  } finally {
    c.release();
  }
}

export async function withAdmin<T>(reason: string, fn: (c: PoolClient) => Promise<T>): Promise<T> {
  const c = await adminPool.connect();
  try {
    console.info(JSON.stringify({ type: "audit", event: "admin_db_access", reason })); // route to your audit pipeline
    return await fn(c);
  } finally {
    c.release();
  }
}
```

```ts
// src/invoices.ts
import { withTenant } from "./db";

export type NewInvoice = { customerId: string; number: string; totalCents: number };

export function listInvoices(tenantId: string, limit = 50) {
  return withTenant(tenantId, async (c) => {
    const r = await c.query(
      "SELECT id, number, total_cents, created_at FROM invoices ORDER BY created_at DESC LIMIT $1",
      [Math.min(limit, 200)],
    );
    return r.rows;
  });
}

export function createInvoice(tenantId: string, input: NewInvoice) {
  return withTenant(tenantId, async (c) => {
    const r = await c.query(
      `INSERT INTO invoices (tenant_id, customer_id, number, total_cents)
       VALUES ($1, $2, $3, $4) RETURNING id`,
      [tenantId, input.customerId, input.number, input.totalCents],
    );
    return r.rows[0].id as string;
  });
}
```

### What happens in a leak attempt

```sql
-- As app_user, tenant = acme
BEGIN;
SELECT set_config('app.tenant_id', '11111111-1111-1111-1111-111111111111', true);

SELECT email FROM customers;                    -- ann@acme.test only
INSERT INTO invoices (tenant_id, customer_id, number, total_cents)
VALUES ('22222222-2222-2222-2222-222222222222', 'bbbbbbbb-0000-0000-0000-000000000001', 'X-1', 100);
-- ERROR:  new row violates row-level security policy for table "invoices"

INSERT INTO invoices (tenant_id, customer_id, number, total_cents)
VALUES ('11111111-1111-1111-1111-111111111111', 'bbbbbbbb-0000-0000-0000-000000000001', 'X-2', 100);
-- ERROR:  insert or update on table "invoices" violates foreign key constraint
--         (customer belongs to another tenant: composite FK blocks it)
COMMIT;

SELECT count(*) FROM customers;                 -- 0: no context, fail closed
```

Three independent layers (RLS `WITH CHECK`, composite foreign key, and the application's use of `tenantId` from the session) all had to fail for a cross-tenant write to succeed.

## Rollout plan for an existing app, and a checklist

Retrofitting RLS onto a live system is where most of the risk lives. Do it in stages, never as a single big migration.

| Stage | Action | Risk control |
| --- | --- | --- |
| 1. Inventory | List tables, add `tenant_id` where missing (expand step), backfill, add indexes concurrently | Zero behavior change |
| 2. Roles | Create `app_user` (non-owner) and `migrator`; point migrations to the owner, the app to `app_user`. Grant privileges | Verify the app works with the new role before any policy |
| 3. Context plumbing | Introduce `withTenant` everywhere and make all DB access go through it, including workers and scripts. Log whether the context was set | Still no RLS; just plumbing and observability |
| 4. Shadow mode | Add policies on staging; on production, run a canary tenant or a read replica with RLS enabled and compare query results to the non-RLS path | Catches missed context paths |
| 5. Enable per table | `ENABLE` then `FORCE` per table, low-risk tables first, with the permissive policy and a fast rollback script (`DISABLE ROW LEVEL SECURITY`) at hand | Short blast radius |
| 6. Lock in | CI checks (all tenant tables have forced RLS), isolation tests, alerts for queries without context | Prevents regressions |
| 7. Harden | Composite FKs and tenant-scoped unique constraints; remove old global uniques | Do with `NOT VALID` then `VALIDATE` for large tables |

### Checklist

- [ ] Tenancy model chosen and documented, with a path to dedicated databases for large or regulated tenants.
- [ ] Every tenant table has `tenant_id NOT NULL`, an FK to `tenants`, and tenant-leading indexes.
- [ ] Composite primary and foreign keys `(tenant_id, id)` for tenant-owned relations.
- [ ] Per-tenant unique constraints (`UNIQUE (tenant_id, ...)`).
- [ ] `ENABLE` and `FORCE ROW LEVEL SECURITY` plus `USING` and `WITH CHECK` policies on all tenant tables.
- [ ] App role is not owner, not superuser, `NOBYPASSRLS`; migrations use a separate role.
- [ ] Tenant context set by `set_config(..., true)` inside the request transaction; never session-level `SET`.
- [ ] Works under PgBouncer transaction pooling; no session state relied upon.
- [ ] Fails closed when the context is missing; tests cover it.
- [ ] Views use `security_invoker`; `SECURITY DEFINER` functions pin `search_path` and are reviewed.
- [ ] Workers, cron jobs and scripts use the same context wrapper.
- [ ] Caches, search indexes, queues and object storage keys include the tenant.
- [ ] Cross-tenant isolation tests run in CI against real Postgres as the app role.
- [ ] CI query flags any table with `tenant_id` lacking forced RLS.
- [ ] Admin or BYPASSRLS access is a separate, audited, rarely used path.
- [ ] Tenant export, restore and deletion procedures tested.
- [ ] Per-request `statement_timeout`, pool limits, quotas for fairness.
- [ ] `EXPLAIN` verified for the top queries as the app role.
- [ ] Migration runner handles the chosen model, with canary and stop-on-failure behavior.

## What tends to go wrong

1. Connecting as the table owner or a superuser. RLS silently does nothing. Tests pass because they run as the owner too.
2. Forgetting `FORCE ROW LEVEL SECURITY` when the app shares a role with the owner.
3. Session-level `SET app.tenant_id` with a pooler. A different request reuses the connection and inherits the wrong tenant.
4. Using `SET LOCAL` outside a transaction. It affects only the current statement's implicit transaction, then reverts; subsequent queries have no context. Always start a transaction explicitly.
5. A policy that fails open. For example `USING (tenant_id = current_setting('app.tenant_id') OR current_setting('app.tenant_id') IS NULL)` "for convenience in scripts". An unset context should mean no access.
6. A missing `WITH CHECK` (or only `FOR SELECT` policies), so a tenant can insert or move rows into another tenant.
7. Global IDs without composite FKs. A child row can reference another tenant's parent.
8. Global unique constraints (`UNIQUE (email)`, `UNIQUE (slug)`) that prevent two tenants from using the same value, or leak existence through errors.
9. Views, materialized views and `SECURITY DEFINER` functions that bypass the policy.
10. Caches and background jobs without tenant keys. RLS does not protect Redis, Elasticsearch, S3 or in-memory memoization.
11. Believing RLS replaces authorization. It only enforces the tenant boundary.
12. Complex policies with joins and subqueries. They slow everything and invite recursion errors. Keep the isolation policy trivial.
13. Admin tools through BYPASSRLS with no audit. The bypass role becomes the new weak point.
14. Never testing the unhappy path: no-context queries, upserts, `RETURNING`, bulk updates and FK probing.
15. No plan for the big tenant or for per-tenant restore and deletion until a customer asks.

## When NOT to do this

- Single-tenant or internal tools. If every customer gets their own deployment, you do not need pooled-schema RLS.
- Few, very large, regulated tenants. Database or cluster per tenant gives stronger, simpler, auditable isolation, independent backup and region placement. RLS is a poor primary control when a contract demands physical separation.
- Very high tenant counts with tiny data and a serverless budget. Shared schema with RLS fits. Schema per tenant does not (catalog bloat).
- Schema per tenant at tens of thousands of tenants. Catalog size, migration time and backup time will hurt; use shared schema with RLS.
- Hot analytical workloads across tenants. Run analytics in a warehouse or on replicas with a BYPASSRLS role, and aggregate outside the transactional path.
- When you cannot guarantee the application sets the context on every path. First centralize data access; otherwise enabling RLS on a live app will turn missed paths into outages. Use the staged rollout.
- When a poolers or driver cannot keep a transaction around the request (some HTTP-only serverless drivers). Pick a driver that supports transactions, or use a design where a trusted API tier does the setting and querying in one call.
- Treating RLS as a performance feature. It is a safety feature; adding `tenant_id` to every query still matters for the planner.

## Questions that come up

**Is RLS enough for compliance-grade isolation?**
It is strong logical isolation and a good control for many standards, but if a contract or regulation requires physical or key separation, use database or cluster per tenant (with per-tenant keys). Discuss with your compliance advisor.

**Can I use RLS with Supabase or Neon?**
Yes. Supabase builds its authorization on RLS with JWT claims exposed as settings; follow its documented patterns. Pooled endpoints on managed platforms use transaction pooling, so the same transaction-scoped rules apply. Verify platform specifics in the provider's docs.

**What about users who belong to many tenants?**
Keep users global, store memberships, and have the application select the active tenant, verify membership, and set the context. The tenant switcher reads memberships through a policy based on the user ID.

**How do I handle uniqueness of global things like custom domains or usernames?**
Keep a small global table without tenant scoping (and without RLS or with a narrow read policy) for those identifiers, with a unique constraint, and reference it from tenant rows.

**What happens to RLS with logical replication, `pg_dump` and extensions?**
`pg_dump` runs as a role that normally bypasses RLS and dumps everything unless you pass `--enable-row-security`; logical replication copies rows regardless of RLS on the publisher. Treat those channels as privileged and restrict who can use them.

**Where do I start on an existing app?**
Connect as a non-owner role, enable and force RLS on your most sensitive table with a `USING` and `WITH CHECK` policy, route its access through a transaction-scoped context, and write the cross-tenant test that proves it.

## Sources and docs

- [PostgreSQL docs: Row Security Policies](https://www.postgresql.org/docs/current/ddl-rowsecurity.html) and [CREATE POLICY](https://www.postgresql.org/docs/current/sql-createpolicy.html).
- [PostgreSQL docs: Privileges and roles](https://www.postgresql.org/docs/current/user-manag.html) (including `BYPASSRLS`) and [CREATE VIEW (security_invoker)](https://www.postgresql.org/docs/current/sql-createview.html).
- [PostgreSQL docs: Logical replication row filters](https://www.postgresql.org/docs/current/logical-replication-row-filter.html).
- [PgBouncer documentation](https://www.pgbouncer.org/config.html): pool modes and prepared statement support.
- [AWS: Multi-tenant data isolation with PostgreSQL row-level security](https://aws.amazon.com/blogs/database/multi-tenant-data-isolation-with-postgresql-row-level-security/): a vendor-neutral-ish walkthrough of the pattern.
- [Supabase: Row Level Security guide](https://supabase.com/docs/guides/database/postgres/row-level-security): RLS in a managed platform.
- [Prisma docs](https://www.prisma.io/docs), [Drizzle docs](https://orm.drizzle.team/docs/overview), [Django docs](https://docs.djangoproject.com/), [Laravel docs](https://laravel.com/docs): verify the current extension, transaction and migration APIs.
- [Next.js docs](https://nextjs.org/docs): proxy (middleware), caching and Server Actions.
- [Citus documentation: multi-tenant applications](https://docs.citusdata.com/): sharding by tenant when one node is not enough.
- On this site: [Postgres Query Performance with EXPLAIN ANALYZE](https://www.derar.dev/blog/postgres-query-performance-explain-analyze-2026), [Zero-Downtime Postgres Migrations](https://www.derar.dev/blog/zero-downtime-postgres-migrations-2026), [Postgres Vector Search for AI Apps](https://www.derar.dev/blog/postgres-vector-search-ai-apps-2026), [OWASP Top 10 for Developers](https://www.derar.dev/blog/owasp-top-10-for-developers-practical-fixes-2026), [Secrets Management in 2026](https://www.derar.dev/blog/secrets-management-vault-sops-workload-identity-2026), [Threat Modeling for Developers](https://www.derar.dev/blog/threat-modeling-for-developers-stride-practical-guide-2026).
