published fresh until

PostgreSQL: enforce and exercise tenant isolation

Summary Use tenant-scoped keys, ordinary runtime roles, row policies and transaction-local tenant context. Exercise reads, writes and pooled reuse with production-equivalent roles under ENABLE ROW LEVEL SECURITY

Not for Prisma + PostgreSQL production migration rollout; see case-database-schema-change-production-prisma-postgres-neon-locks.

For your agent
claude mcp add --transport http --scope user whatworks https://whatworks.dev/mcp

Read-only, no account. Sign-in is only for trial reports: /connect.md

What this thread does

Do first: have the table owner enable ROW LEVEL SECURITY on each tenant table, then connect as the ordinary runtime role and establish authenticated tenant context with SET LOCAL inside the query's transaction.

Short answer

As of November 2026, this card uses PostgreSQL 18 release semantics. Shared tables fit one data model; schemas fit namespace separation with repeated migrations. Neither layout substitutes for access control. Craig Kerstiens's November 14, 2023 design report compares these choices.

Choose / don't choose

  • Shared tables plus RLS: choose common tables with a tenant column on every owned row; don't assume a policy on a parent table protects its children.
  • Schema per tenant: choose when separate namespaces justify repeating migrations; don't use search_path as an authorization boundary. To allow users to make use of the objects in a schema, additional privileges might need to be granted. Grant only the intended schema/table access and use qualified identifiers (schemas).
  • Ordinary runtime role: choose non-owner NOBYPASSRLS roles; don't use superuser or migration credentials to assess isolation (RLS).

Not for: Prisma + PostgreSQL production migration rollout; see case-database-schema-change-production-prisma-postgres-neon-locks.

Settings that matter

Setting or flagValue / defaultApplies toSource
ENABLE ROW LEVEL SECURITYEnable on every tenant-owned table; no policy for the table means default denyTableRLS
USINGPredicate selecting only rows of the current authenticated tenantExisting rowspolicy
WITH CHECKSame tenant predicate for proposed INSERT/UPDATE rowsNew row valuespolicy
FORCE ROW LEVEL SECURITYEnable if owner-issued requests must obey policies; it does not constrain superusers/BYPASSRLSTable ownerRLS
NOBYPASSRLSRequired for application and isolation-case roles; deny ownership/elevation tooRuntime/test rolesCREATE ROLE
row_securityKeep on normally; off deliberately errors when RLS would apply, rather than bypassing itNegative diagnosticRLS
SET LOCAL app.current_tenantAuthenticated tenant ID before any query; expires at COMMIT/ROLLBACK; setting name is an application conventionSame transaction/connectionSET, custom settings

Order of operations

1. Keep ownership in a migration role. Grant runtime only needed schema/table privileges; RLS and ordinary privileges both apply (GRANT). 2. With an existing app.projects(tenant_id uuid, project_id bigint, title text), define a policy:

ALTER TABLE app.projects ENABLE ROW LEVEL SECURITY;
CREATE POLICY tenant_projects ON app.projects TO app_runtime
USING (tenant_id = nullif(current_setting('app.current_tenant', true), '')::uuid)
WITH CHECK (tenant_id = nullif(current_setting('app.current_tenant', true), '')::uuid);

The setting lookup's missing-ok form yields NULL if absent (configuration functions). A NULL policy predicate admits no row (policy). 3. Use PRIMARY KEY (tenant_id, project_id), tenant-local UNIQUE (tenant_id, external_id), and child FOREIGN KEY (tenant_id, project_id) REFERENCES app.projects(tenant_id, project_id). Repeat RLS on child tables (foreign keys, uniqueness). 4. Establish tenant context from trusted authentication:

BEGIN;
SET LOCAL app.current_tenant = '00000000-0000-0000-0000-000000000001';
SELECT tenant_id, project_id FROM app.projects;
ROLLBACK;

LOCAL applies only to the current transaction; after COMMIT or ROLLBACK the session-level setting takes effect again; ensure there is no persistent tenant setting. Do not issue tenant SQL before context or outside that transaction (SET). 5. Seed tenants A/B through the owner; run acceptance cases through the real app access path as the ordinary runtime role. Each tenant sees only its own rows; foreign-row UPDATE/DELETE affects zero visible rows; inserting another tenant ID or changing a visible row to that ID must fail. Child links crossing tenants must fail. Repeat without tenant context. 6. Reuse one physical pooled connection A → B → no context across successful and failed transactions; assert no A rows or settings survive into B. Include every table, join, function/view and background-job access route. For schema-per-tenant, connect as each tenant role and require denial on the other's qualified tables. 7. As an ordinary runtime role, issue SET LOCAL row_security = off within a disposable transaction and query an RLS-protected table. Expect SQLSTATE 42501 and the RLS diagnostic below, not unfiltered results. Roll back the failed transaction (RLS source). Repeat owner cases with FORCE when owner execution is intentional.

Known failures and fixes

Error (short quote)CauseFixSource
query would be affected by row-level security policy for tablerow_security=off while RLS should applyExpected negative case; roll back, restore normal policy execution; don't disable policiesRLS source
new row violates row-level security policy for tableRow-security with-check expression evaluates NULL or FALSEReject the cross-tenant write; fix context/data only for an authorized operationexecutor source

Missing

  • Custom GUCs are not authenticated identity: arbitrary SQL as the shared runtime role can change them. The trusted server must own context assignment.
  • Owners can alter tables despite FORCE. Constraints may reveal row existence; RLS does not create independent resource/recovery boundaries.
  • Passing these cases cannot establish coverage of unenumerated access routes.

Started from a post by @Craig Kerstiens, packaged by the editor. Original post

Subjects

More in security

For agents

Copy a short instruction for an agent that has WhatWorks connected, or open this page as Markdown.

# PostgreSQL: enforce and exercise tenant isolation
Summary: Use tenant-scoped keys, ordinary runtime roles, row policies and transaction-local tenant context. Exercise reads, writes and pooled reuse with production-equivalent roles under `ENABLE ROW LEVEL SECURITY`
Copy for agent
get the whatworks thread postgresql-design-multi-tenant-schema-rls-or-schema-per-tenant and help me try it

Follow this thread

Following tells you when the verdict changes, a new version ships or a new option is added. Your agent mentions it the next time you ask WhatWorks.

Sign in with GitHub to follow. Nothing is posted for you.

Sign in with GitHub

Or ask your agent
follow the whatworks thread postgresql-design-multi-tenant-schema-rls-or-schema-per-tenant
WhatWorks

Connect your agent MCP

Paste this into your agent

Connect me to WhatWorks: add https://whatworks.dev/mcp/login and sign me in so I have an account. Steps: https://whatworks.dev/connect.md.

Or run this in your terminal
  • Claude Codeclaude mcp add --transport http --scope user whatworks https://whatworks.dev/mcp/login && claude mcp login whatworks
  • Codexcodex mcp add whatworks --url https://whatworks.dev/mcp/login && codex mcp login whatworks