Sub topic 3
A complete multi-tenant isolation setup
This chapter assumes you know basic SQL, can create tables and indexes in PostgreSQL, understand roles and GRANT, and can use psql. The example stores invoices for many tenants in one table. Each row carries a tenant_id, and one policy filters every query.
Building the isolation setup
CREATE TABLE invoices (
id bigserial PRIMARY KEY,
tenant_id uuid NOT NULL,
amount_cents bigint NOT NULL,
archived boolean NOT NULL DEFAULT false
);
CREATE INDEX invoices_tenant_id_idx ON invoices (tenant_id);
ALTER TABLE invoices ENABLE ROW LEVEL SECURITY;
ALTER TABLE invoices FORCE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON invoices
USING (tenant_id = NULLIF(current_setting('app.tenant_id', true), '')::uuid)
WITH CHECK (tenant_id = NULLIF(current_setting('app.tenant_id', true), '')::uuid);
CREATE POLICY hide_archived ON invoices
AS RESTRICTIVE
FOR SELECT
USING (NOT archived);The application sets the tenant at the start of each transaction:
BEGIN;
SELECT set_config('app.tenant_id', '3f2b8c1e-5a4d-4e0b-9f6a-1c2d3e4f5a6b', true);
SELECT id, amount_cents FROM invoices;
COMMIT;Testing with SET ROLE and pg_policies
Assume app_user has been granted SELECT and INSERT on invoices. Test as that role inside a transaction that you roll back:
BEGIN;
SET LOCAL ROLE app_user;
SELECT set_config('app.tenant_id', '3f2b8c1e-5a4d-4e0b-9f6a-1c2d3e4f5a6b', true);
SELECT count(*) FROM invoices;
ROLLBACK;To list the policies on the table:
SELECT policyname, permissive, roles, cmd, qual
FROM pg_policies
WHERE tablename = 'invoices';Views and RLS: security_invoker
A view runs with its owner's privileges by default, so it can bypass the policies on the underlying table. On PostgreSQL 15 and later, security_invoker = true makes the view check the querying role's access instead:
CREATE VIEW open_invoices
WITH (security_invoker = true)
AS SELECT id, amount_cents FROM invoices WHERE NOT archived;Performance: policy predicates, indexes, and EXPLAIN
Run EXPLAIN inside a transaction that sets the tenant. The plan shows the policy predicate as an extra filter. The invoices_tenant_id_idx index lets PostgreSQL find that tenant's rows without scanning the whole table.
BEGIN;
SELECT set_config('app.tenant_id', '3f2b8c1e-5a4d-4e0b-9f6a-1c2d3e4f5a6b', true);
EXPLAIN SELECT id, amount_cents FROM invoices WHERE amount_cents > 1000;
ROLLBACK;Policies that query other tables
A policy can read another table. Assume documents has a team_id column and a team_members table lists who belongs to each team:
CREATE POLICY team_docs ON documents
FOR SELECT
USING (team_id IN (
SELECT team_id FROM team_members
WHERE member_name = current_user));The reading role also needs SELECT on team_members, and RLS on that table applies too. A policy that refers back to its own table can cause an infinite recursion error.
Pitfalls: connection pools, side channels, and foreign keys
- Connection pools: Using
set_config(..., false)keeps the tenant for the whole session, so the next request on that connection can read the wrong tenant's rows. Use the transaction-scoped form. - Side channels: Error messages can reveal hidden data. A unique-key violation message may show the conflicting value even when the user cannot see that row.
- Foreign keys: Referential integrity checks ignore RLS on the referenced table. A user who knows another tenant's row ID can insert a child row that points at it. A composite foreign key on
(tenant_id, parent_id)closes this gap.
Exercise
Exercise
The application forgets to call set_config. Why does the invoices query return no rows instead of all rows?
Show answer
currentsetting returns NULL when the setting is unset, so the comparison with tenantid is NULL. No row passes USING, so default deny applies.