PostgreSQL Multi-Tenancy: Building Shared Schemas with Row-Level Security (RLS)

Database tutorial - IT technology blog
Database tutorial - IT technology blog

Quick start (5 min)

At 2:14 AM, an urgent Slack ping broke my sleep: an enterprise customer could see another tenant’s financial records on their dashboard. My stomach churned. In multi-tenant SaaS, cross-tenant data leakage is the nightmare that ruins careers and companies overnight.

Most shared-schema setups rely on simple application filters like WHERE tenant_id = $1. It works smoothly until a tired engineer forgets that clause in an ad-hoc reporting service or a rushed hotfix. PostgreSQL Row-Level Security (RLS) pushes that boundary directly into the core engine. Miss a clause in code? The database still blocks unauthorized rows.

Let’s walk through a minimal, 5-minute reproduction showing how PostgreSQL enforces this boundary:

-- 1. Create tenant and document tables
CREATE TABLE tenants (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    name TEXT NOT NULL
);

CREATE TABLE documents (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id UUID NOT NULL REFERENCES tenants(id),
    title TEXT NOT NULL,
    content TEXT NOT NULL
);

-- 2. Seed records for two distinct tenants
INSERT INTO tenants (id, name) VALUES
    ('a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11', 'Acme Corp'),
    ('b0eebc99-9c0b-4ef8-bb6d-6bb9bd380a22', 'Globex Inc');

INSERT INTO documents (tenant_id, title, content) VALUES
    ('a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11', 'Acme Secret Q3', 'Revenue: $1.2M'),
    ('b0eebc99-9c0b-4ef8-bb6d-6bb9bd380a22', 'Globex Roadmap', 'Acquisition plans');

-- 3. Enable RLS and define our isolation boundary
ALTER TABLE documents ENABLE ROW LEVEL SECURITY;

CREATE POLICY tenant_isolation_policy ON documents
    AS PERMISSIVE
    FOR ALL
    TO application_user
    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);

Next, set up an unprivileged role to simulate incoming application traffic:

CREATE ROLE application_user WITH LOGIN PASSWORD 'strong_password';
GRANT SELECT, INSERT, UPDATE, DELETE ON documents TO application_user;

-- Switch session to the runtime user
SET ROLE application_user;

-- Assign the active session tenant to Acme Corp
SET LOCAL app.current_tenant_id = 'a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11';

-- Query all documents without a WHERE filter
SELECT id, title, content FROM documents;

PostgreSQL returns only Acme Corp’s records. Globex data stays completely hidden, even if your API executes a naked SELECT * FROM documents;. Try to force an insert into another workspace with INSERT INTO documents (tenant_id, title, content) VALUES ('b0eebc99-9c0b-4ef8-bb6d-6bb9bd380a22', 'Intruder', 'Data');, and PostgreSQL rejects the write instantly with an RLS policy violation.

Deep dive

Understanding how PostgreSQL handles RLS under the hood helps you avoid subtle performance hits and hard-to-catch edge cases.

Why Shared Schema over Database-per-tenant or Schema-per-tenant?

SaaS teams usually compare three core architectural models:

  • Database-per-tenant: Provides complete isolation. But running migrations across 2,500 individual databases is slow, brittle, and notoriously complex. Managing separate connection pools can burn through 16 GB of server RAM on idle overhead alone.
  • Schema-per-tenant: Isolates tenants within one database instance. However, PostgreSQL system catalogs (such as pg_class and pg_attribute) choke once you scale past 20,000 tables, slowing down routine DDL and planning steps.
  • Shared Schema with RLS: Packs everyone into a single set of shared tables. Migrations run in milliseconds, operational overhead drops near zero, and hardware utilization peaks. Security enforcement happens directly in the engine on every index lookup and scan.

Session configuration settings vs. App Context

Our policy uses current_setting('app.current_tenant_id', true). Passing true as the second argument ensures PostgreSQL returns NULL instead of throwing an error when the variable hasn’t been set yet. Pairing this with SET LOCAL ties the variable directly to the active transaction:

BEGIN;
SET LOCAL app.current_tenant_id = 'a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11';
SELECT * FROM documents;
COMMIT;

As soon as the transaction commits or rolls back, PostgreSQL wipes app.current_tenant_id clean. This guarantees zero state leakage between pooled connections.

The Superuser and Table Owner Bypass Trap

Remember that 2 AM alert? Our backend was connecting as postgres, which owned the table. This is the exact trap that blindsides engineering teams: superusers and table owners bypass RLS policies by default.

If your web app connects using the migration user that ran CREATE TABLE, PostgreSQL silently skips your RLS policies. You can close part of this gap with:

ALTER TABLE documents FORCE ROW LEVEL SECURITY;

This forces policies on the table owner. However, true database superusers still bypass RLS no matter what. Always create a dedicated, unprivileged role for your application services in staging and production.

Advanced usage

Integrating RLS with Connection Pooling and Transaction Middleware

Modern web services rarely establish a fresh TCP connection per request. They share a pool managed by tools like PgBouncer or an ORM pooler. If you execute a global SET app.current_tenant_id on a persistent connection, you risk exposing tenant data to whichever HTTP thread grabs that socket next.

You can cleanly isolate tenant sessions using this Python pattern with asyncpg:

import asyncpg
from contextlib import asynccontextmanager

class TenantDatabaseManager:
    def __init__(self, pool: asyncpg.Pool):
        self.pool = pool

    @asynccontextmanager
    async def tenant_session(self, tenant_id: str):
        async with self.pool.acquire() as connection:
            async with connection.transaction():
                # SET LOCAL binds cleanly to this individual transaction
                await connection.execute(
                    "SET LOCAL app.current_tenant_id = $1", 
                    tenant_id
                )
                yield connection

# Example usage inside a FastAPI/Starlette endpoint
async def get_tenant_docs(db_manager: TenantDatabaseManager, tenant_id: str):
    async with db_manager.tenant_session(tenant_id) as conn:
        rows = await conn.fetch("SELECT id, title FROM documents")
        return [dict(row) for row in rows]

Role-Based Access Control (RBAC) inside Multi-Tenancy

Simple tenant_id matching isn’t always enough. In real applications, basic members should only view general records, while team admins can access restricted billing or confidential files. You can combine multiple session variables directly inside your RLS rules:

CREATE POLICY tenant_rbac_policy ON documents
    AS PERMISSIVE
    FOR ALL
    TO application_user
    USING (
        tenant_id = NULLIF(current_setting('app.current_tenant_id', true), '')::uuid
        AND (
            current_setting('app.user_role', true) = 'admin'
            OR (
                current_setting('app.user_role', true) = 'member'
                AND title NOT LIKE '[Confidential]%'
            )
        )
    );

Practical tips

1. Index your tenant identifiers everywhere

With RLS enabled, PostgreSQL appends your tenant check to every single scan. Without an index on a 10-million-row table, simple lookups will trigger painful sequential scans, spiking query times from 2ms to over 800ms:

-- Always place tenant_id as the leading column
CREATE INDEX idx_documents_tenant_created_at ON documents (tenant_id, id);

Keep tenant_id as the prefix on composite indexes so the planner can instantly discard rows from other accounts.

2. Safely seed and ingest onboarding datasets

When staging lookup tables or bulk data for newly onboarded tenants, engineers often clean raw CSV exports before writing migration scripts. If you use third-party browser utilities like toolcraft.app/en/tools/data/csv-to-json to convert test fixtures, ensure client-side processing so sensitive data never leaves your workstation. Zero data leakage should apply to local tooling just as strictly as production clusters.

3. Handle background workers and system jobs safely

Background workers using Celery, BullMQ, or Sidekiq frequently run nightly billing or data aggregation sweeps. Resist the temptation to run these jobs as superusers. Instead, batch your workloads by tenant ID and wrap each tenant’s batch in a separate SET LOCAL app.current_tenant_id block. This confines job errors and prevents accidental multi-tenant writes during bulk jobs.

4. Audit your queries using EXPLAIN ANALYZE

Double-check your execution plan under your production role before shipping new policies:

SET ROLE application_user;
SET LOCAL app.current_tenant_id = 'a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11';
EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM documents;

Inspect the output for an Index Scan matching your tenant condition. If you see the policy applied cleanly through an index filter rather than a full sequential scan, your query is fast, safe, and ready for production.

Share: