Enforcing Strict Multi-Tenant Data Isolation in PostgreSQL with Row-Level Security (RLS) and Session Contexts
Shafikul Islam
Backend & Cloud Infrastructure Engineer · Infrastructure & Cloud Team Lead

Why Application-Only Tenant Filtering Is Fragile
In a shared-schema multi-tenant B2B SaaS, every table has a tenant_id column. Even with code review and integration tests, a single complex analytics query or newly added JOIN that omits AND tenant_id = $1 can leak confidential records across tenants.
By enabling PostgreSQL Row-Level Security (RLS), the database kernel itself rejects or filters out any row that does not match the active request's tenant context, even if the application runs an unqualified SELECT * FROM invoices.
1. Enabling Row-Level Security Policies on Tenant Tables
ALTER TABLE clinical_patients ENABLE ROW LEVEL SECURITY;
ALTER TABLE clinical_patients FORCE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation_policy ON clinical_patients
USING (tenant_id = NULLIF(current_setting('app.current_tenant_id', true), '')::uuid)
WITH CHECK (tenant_id = NULLIF(current_setting('app.current_tenant_id', true), '')::uuid);
Notice two crucial details:
- FORCE ROW LEVEL SECURITY: Ensures the policy applies even to the table owner role (we also run the application under a dedicated non-superuser role app_rw).
- Fail-Closed Default (NULLIF(..., '')::uuid): If a developer forgets to set app.current_tenant_id on a connection, current_setting returns NULL, and the query safely returns 0 rows instead of failing open.
2. Making RLS Safe with PgBouncer Transaction Pooling (SET LOCAL)
Never use session-level SET app.current_tenant_id = '...' when using PgBouncer in transaction pooling mode, or the setting could leak to the next transaction reusing that backend connection.
Instead, always use SET LOCAL (or set_config('app.current_tenant_id', $1, true)) inside the transaction block so PostgreSQL automatically clears the variable the moment the transaction commits or rolls back.