Sub topic 10
A Complete Multi-Tenant Isolation Setup
This chapter assumes you know PostgreSQL roles, GRANT, tables, indexes, and basic SELECT, INSERT, UPDATE, and DELETE statements. You will build tenant isolation with row-level security (RLS), which limits access to individual rows instead of only whole tables.
The tenant isolation model
Each row stores a tenant_id. The application sets the current tenant in the database session. An RLS policy compares the row's tenant_id with that session value.
The application role must have ordinary table privileges, such as SELECT and INSERT. Those privileges answer, “May this role use the table?” RLS answers, “Which rows may it use?”
Create the table and policy
The index supports the tenant comparison. FORCE ROW LEVEL SECURITY also applies RLS to the table owner. Without it, the owner normally bypasses policies.
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
);current_setting reads a PostgreSQL configuration setting. Its second argument, true, makes a missing setting return NULL instead of raising an error. NULLIF also turns an empty value into NULL. Therefore, a request with no tenant context matches no rows and cannot insert a row.
USING filters existing rows for SELECT, UPDATE, and DELETE. WITH CHECK validates rows created or changed by INSERT and UPDATE. Using both prevents a tenant from reading another tenant's rows or assigning new rows to another tenant.
Set the tenant safely
Set the tenant inside every transaction. The third argument to set_config is true, so the value lasts only until the transaction ends.
BEGIN;
SELECT set_config(
'app.tenant_id',
'3f2b8c1e-5a4d-4e0b-9f6a-1c2d3e4f5a6b',
true
);
SELECT id, amount_cents
FROM invoices
WHERE amount_cents > 1000;
COMMIT;This transaction-scoped setting matters when the application uses a connection pool. A pooled connection can serve different tenants over time. A session-level setting could remain active and expose data to the next request.
Add business rules
RLS policies can combine tenant isolation with other restrictions. A restrictive policy must also pass when PostgreSQL evaluates the row.
CREATE POLICY hide_archived ON invoices
AS RESTRICTIVE
FOR SELECT
USING (NOT archived);The tenant policy is permissive by default. Multiple permissive policies for the same command are combined with OR. Restrictive policies are then combined with AND. In this example, a visible invoice must belong to the current tenant and must not be archived.
| Policy kind | Combination |
|---|---|
| Permissive | Any matching policy can allow the row |
| Restrictive | Every applicable restrictive policy must allow the row |
Superusers and roles with the BYPASSRLS attribute bypass RLS. Review those roles carefully. FORCE ROW LEVEL SECURITY protects against the normal table-owner bypass, but it does not override a superuser or BYPASSRLS.
Exercise
Why should the application set app.tenantid with setconfig(..., true) inside each transaction?
Show answer
The true argument makes the setting transaction-scoped, so a pooled connection cannot carry one tenant's context into a later tenant's request.