Sub topic 10
A complete multi-tenant isolation setup
This chapter assembles the pieces from earlier chapters into one working design. Every tenant's invoices live in one shared table, and PostgreSQL enforces that a connection can only see and write its own tenant's rows.
You should already know ENABLE ROW LEVEL SECURITY, the difference between USING and WITH CHECK, permissive versus restrictive policies, and how BYPASSRLS and FORCE work. You also need basic role and GRANT handling, and a psql session where you can create roles.
The design in one picture
The application connects as a single non-privileged role. At the start of each transaction it records the tenant ID in a custom setting. Policies compare each row's tenant_id to that setting.
Three decisions make this work:
- The application role has no
BYPASSRLSand does not own the table. - The tenant is carried in a setting that is local to the transaction.
- Policies deny by default when the setting is missing.
Step 1: roles
Use one role to own the schema and another for the application. The owner runs migrations. The application role only reads and writes data.
CREATE ROLE app_owner NOLOGIN;
CREATE ROLE app_user NOLOGIN;In production app_user would have LOGIN and a password or certificate. NOLOGIN lets you follow along with SET ROLE. Do not give app_user SUPERUSER, BYPASSRLS, or ownership of any table. Any of these would switch the policies off for it.
Step 2: table, index, policies
Create the table as app_owner so that ownership is not the superuser's. This is the setup from the spine, with the table owner's role made explicit.
SET ROLE app_owner;
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);
GRANT SELECT, INSERT, UPDATE, DELETE ON invoices TO app_user;
GRANT USAGE ON SEQUENCE invoices_id_seq TO app_user;
RESET ROLE;Each part does a specific job:
ENABLEturns on default deny for roles that are subject to RLS.FORCEalso subjects the owner,app_owner, to the policies. Without it, a migration script or a stray owner connection would see every tenant's rows. Superusers andBYPASSRLSroles still bypass RLS even withFORCE.tenant_isolationis a permissive policy for all commands. ItsUSINGclause filters rows that are read, updated, or deleted. ItsWITH CHECKclause rejects inserted or updated rows that belong to another tenant.hide_archivedis restrictive. A row must pass it and at least one permissive policy. It affects onlySELECT, so tenants can still insert archived rows.current_setting('app.tenant_id', true)usesmissing_ok = true. If the setting was never set, it returnsNULL. After a transaction-localset_configends, a pooled connection can instead report an empty string, which is whyNULLIF(..., '')turns it intoNULLbefore theuuidcast. Comparing a column toNULLis never true, so no rows match and the table fails closed.
Step 3: set the tenant per transaction
The application calls set_config with is_local = true. The value then lasts until the end of the current transaction.
BEGIN;
SELECT set_config('app.tenant_id', '3f2b8c1e-5a4d-4e0b-9f6a-1c2d3e4f5a6b', true);
SELECT id, amount_cents FROM invoices;
COMMIT;Always bind the tenant ID as a query parameter in application code. Never build the set_config call by string concatenation.
Do not use a session-level SET app.tenant_id = ... or set_config(..., false) with a connection pool. In transaction-pooling mode, the next client may receive that same server connection and inherit the previous tenant. A transaction-local setting disappears at COMMIT or ROLLBACK, so it cannot carry over.
Step 4: verify behavior
Run this as a superuser or as app_owner with membership in app_user. SET ROLE makes PostgreSQL evaluate RLS for app_user, even if your login role is a superuser.
SET ROLE app_user;
BEGIN;
SELECT set_config('app.tenant_id', '11111111-1111-1111-1111-111111111111', true);
INSERT INTO invoices (tenant_id, amount_cents)
VALUES ('11111111-1111-1111-1111-111111111111', 5000);
INSERT INTO invoices (tenant_id, amount_cents, archived)
VALUES ('11111111-1111-1111-1111-111111111111', 900, true);
COMMIT;
BEGIN;
SELECT set_config('app.tenant_id', '22222222-2222-2222-2222-222222222222', true);
SELECT count(*) FROM invoices; -- 0: tenant 2 sees nothing of tenant 1
INSERT INTO invoices (tenant_id, amount_cents)
VALUES ('11111111-1111-1111-1111-111111111111', 1);
-- ERROR: new row violates row-level security policy for table "invoices"
ROLLBACK;
SELECT count(*) FROM invoices; -- 0: no tenant set, so the table fails closed
RESET ROLE;The three results are: another tenant's rows are invisible, a forged tenant_id is rejected, and a missing tenant gives an empty table. Checking all three is a useful regression test for any change to the policies.
Edge cases to know
Commands that read rows. An UPDATE or DELETE with a WHERE clause must read rows, so the SELECT policies apply to it too. With hide_archived in place, app_user cannot update or delete an archived row by filtering on its columns. Likewise, INSERT ... RETURNING needs the new row to pass the SELECT policies. Inserting an archived row with RETURNING therefore fails. If tenants must be able to unarchive rows, restrict hide_archived less, or perform that change through a controlled function.
The setting is only as trustworthy as the caller. Any role that can run arbitrary SQL can call set_config('app.tenant_id', ...) itself. This design protects against application bugs such as a forgotten WHERE tenant_id = .... It does not protect against a tenant who can execute their own SQL on the shared connection. For that, give each tenant a separate database role and compare against current_user instead, as in the documents example from earlier chapters.
Uniqueness is per tenant. Add tenant_id to unique constraints, for example UNIQUE (tenant_id, invoice_number). A global unique constraint would reveal that another tenant already used a value, because the insert fails.
Index design. The single-column index on tenant_id lets the planner filter on the policy predicate. For common queries, a composite index that leads with tenant_id, such as (tenant_id, created_at), usually serves both the policy and the application's own filters.
Default values. You can reduce mistakes by letting the database fill the tenant for the application:
ALTER TABLE invoices
ALTER COLUMN tenant_id
SET DEFAULT NULLIF(current_setting('app.tenant_id', true), '')::uuid;With a missing setting the default yields NULL, and the NOT NULL constraint rejects the insert. That failure is the intended result.
Checking what you built
Use pg_policies to list the policies, and EXPLAIN to confirm the planner can use the index with the policy predicate added.
SELECT policyname, permissive, roles, cmd, qual, with_check
FROM pg_policies
WHERE tablename = 'invoices';The permissive column shows PERMISSIVE or RESTRICTIVE. The roles column shows {public} when a policy has no TO clause. In this design that is intended, because app_user is the only role with table privileges.
| Check | Expected result |
|---|---|
| `app_user` has `rolbypassrls` | false |
| `app_user` owns `invoices` | no |
| `relforcerowsecurity` for `invoices` | true |
| Query with no tenant set | zero rows |
| Insert with a different tenant | policy violation error |
You can read the role and table flags from pg_roles and pg_class.
Exercise
A teammate changes the application to run SET app.tenant_id = '...' once when each pooled connection is opened, instead of calling set_config inside each transaction. Tests with one client pass. Why is this unsafe, and what should replace it?
Show answer
A session-level SET lasts for the life of the server connection. With transaction pooling, different clients take turns on the same connection, so a later client can run queries under the earlier client's tenant ID, and the policies will approve them. Single-client tests cannot show this. Replace it with SELECT set_config('app.tenant_id', $1, true) inside an explicit transaction for every request, so the value ends at COMMIT or ROLLBACK.
Exercise
The application's migration tool connects as app_owner and runs a data fix with SELECT count(*) FROM invoices. It returns 0 even though the table has rows. Which setting causes this, and how could you make the migration see all rows?
Show answer
FORCE ROW LEVEL SECURITY makes the policies apply to the table owner, and no tenant is set, so the predicate evaluates to NULL and matches nothing. To see all rows, run the migration as a superuser or a role with BYPASSRLS, or set the intended tenant with set_config inside the migration's transaction. Removing FORCE would also work, but it would weaken the isolation for any process connecting as the owner.