PostgreSQL Row-Level Security for Multi-Tenant SaaS in Production

Database Engineering

Configure PostgreSQL row-level security for multi-tenant SaaS. Scope tenant context with PgBouncer, test isolation, and measure real query execution plans.

TL;DR

  • PostgreSQL row-level security (RLS) filters normal operations through database policies. On a shared SaaS table, enable RLS, enforce tenant identity on both reads and writes, and connect your application as a non-owner role without BYPASSRLS.
  • Bind the authorised tenant to each transaction with set_config(..., true), including read-only work. This works with PgBouncer transaction pooling because the context and queries share a backend until commit or rollback. The tenant setting is supplied by trusted application code. It cannot authenticate a principal independently.
  • Use leading tenant columns in indexes where they match real queries. Measure plans as the actual application role and tenant, using representative tenant sizes and predicate shapes. Keep the application’s explicit tenant filter too. The policy covers row isolation when an ordinary query omits it.

Why shared-table multi-tenancy needs a second check

A SaaS billing platform puts all invoice rows in one PostgreSQL table. Normal handler code includes WHERE tenant_id = :tenant. Later, someone adds a CSV export, a bulk update, or a background worker with another query path. The reviewers must remember the filter every time. They must also notice that a join between tables matched only on an object ID even though both schemas use a tenant-scoped key. One missed predicate can return rows a caller should never see.

Row-level security makes the database participate in that decision. Once RLS is enabled, PostgreSQL checks policies before returning or writing eligible rows under ordinary access. When no applicable policy exists, the table is default-deny for roles subject to RLS. A table owner normally bypasses RLS unless the table uses FORCE ROW LEVEL SECURITY. Superusers and roles with BYPASSRLS remain outside it. Keep migrations and request processing on separate identities. PostgreSQL row security policy semantics

The design in this guide is a defence against query bugs in a service that already authenticates callers and checks their tenant membership. A database role that can execute arbitrary SQL can change its custom setting. Do not give untrusted users the service connection or treat the setting as proof of membership. If you require mutually untrusted SQL clients, use stronger boundaries such as per-tenant credentials and a policy tied to authenticated database identity, or choose separate databases.

Define the expected negatives before touching the schema. A missing tenant context returns no results and rejects inserts. The service must not carry tenant A into a reused connection for tenant B. An update may change invoice details while ownership stays in scope. Revocation must affect membership resolution before a new tenant-scoped database transaction starts.

Design the tenant boundary from authentication to SQL

Verified user or service identity
  → application checks active tenant membership
  → request opens a database transaction as the restricted role
  → transaction-local tenant context
  → policy and SQL privileges govern rows
  → commit or rollback removes the local context

Decide how the API chooses the tenant before assigning a database context. A principal may belong to several workspaces. A tenant in a request path expresses where the principal wants to operate. Verify the membership independently and use the authorised ID derived from that verification. Never bind a request header or path directly to the setting. Authentication proves who the caller is. Tenant membership and action permission specify what they can do.

Give a migration owner control of schemas, policies and grants. Give the application role only the table operations it needs. Use a different role for read-only workers where possible. Review function ownership, views and materialised outputs as additional routes through the data model. PostgreSQL 15 and later support security_invoker views when the underlying permissions and policies should follow the caller. A view or security-definer function evaluated with a privileged owner can behave differently from direct access. PostgreSQL view security options

Model relationships with tenant-aware keys. For a line-item table referencing an invoice, use FOREIGN KEY (tenant_id, invoice_id) referencing the invoice’s composite key. That is a structural constraint independent of the caller’s visibility. When possible, put tenant scope on uniqueness too, both to encode the intended business rule and to avoid confusing collisions across tenants. PostgreSQL referential integrity checks bypass row security. A foreign key or uniqueness error can expose information through success or failure, so think carefully about globally unique identifiers that are expected to remain private. PostgreSQL notes on referential integrity and row visibility

Implement PostgreSQL row-level security for a SaaS API

Enable and force RLS in a migration

Run this PostgreSQL 18 example with a migration role authorised to create roles and set the schema owner. Both named roles are NOLOGIN. In deployment, let an application login inherit the privileges of saas_api while keeping ownership and migration privileges separate. Do not make that login a member of the owner role. The example uses separate naming for clarity. Apply the same ownership split to read replicas, support tooling and test databases.

CREATE ROLE saas_owner NOLOGIN;
CREATE ROLE saas_api NOLOGIN NOBYPASSRLS;
CREATE SCHEMA app AUTHORIZATION saas_owner;

SET ROLE saas_owner;
CREATE TABLE app.invoice (
  tenant_id uuid NOT NULL,
  id bigint GENERATED ALWAYS AS IDENTITY,
  issued_at timestamptz NOT NULL DEFAULT now(),
  amount_minor bigint NOT NULL CHECK (amount_minor >= 0),
  PRIMARY KEY (tenant_id, id)
);

ALTER TABLE app.invoice ENABLE ROW LEVEL SECURITY;
ALTER TABLE app.invoice FORCE ROW LEVEL SECURITY;

CREATE POLICY invoice_tenant ON app.invoice TO saas_api
  USING (tenant_id = nullif(
    current_setting('app.tenant_id', true), ''
  )::uuid)
  WITH CHECK (tenant_id = nullif(
    current_setting('app.tenant_id', true), ''
  )::uuid);

CREATE INDEX invoice_tenant_recent
ON app.invoice (tenant_id, issued_at DESC, id DESC);

GRANT USAGE ON SCHEMA app TO saas_api;
GRANT SELECT, INSERT, UPDATE, DELETE ON app.invoice TO saas_api;
RESET ROLE;

USING checks row visibility and which existing rows are eligible to update or delete. WITH CHECK governs proposed rows on insert and update. The expression converts a controlled tenant setting to a UUID. The second argument to current_setting returns null when a setting is absent. nullif handles an empty placeholder after a custom setting has been cleared on a reused backend. An undefined or cleared context then matches no tenant. The application passes a parsed UUID. A malformed value reaching SQL may raise a type cast error and should surface as a service setup error rather than being mistaken for an ordinary denial.

Be deliberate about additional policies. PostgreSQL combines applicable permissive policies with OR. Adding a second permissive policy can broaden access even if the original policy remains intact. Restrictive policies add AND conditions to an otherwise permitted row, and the table still needs an applicable permissive policy. Keep tenant scope in reviews of policy composition as well as reviews of each predicate. PostgreSQL policy composition and command checks

Set tenant context inside the same transaction as the query

The SQLAlchemy 2.x example expects an async session factory that uses the application login. Membership checks run before this helper is called. The caller binds a validated cursor only after its tenant and sort order are checked. For a first page, issue the same query without the time-and-ID cursor condition. Under PostgreSQL’s configuration API, the third argument of set_config determines transaction-local scope. PostgreSQL configuration functions

from datetime import datetime
from uuid import UUID

from sqlalchemy import text
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker

async def latest_invoices(
    sessions: async_sessionmaker[AsyncSession],
    tenant_id: UUID,
    before: tuple[datetime, int],
) -> list[dict]:
    # tenant_id must already be authorised for the requesting principal.
    async with sessions.begin() as db:
        await db.execute(
            text("SELECT set_config('app.tenant_id', :tenant, true)"),
            {"tenant": str(tenant_id)},
        )
        rows = await db.execute(
            text("""
                SELECT id, issued_at, amount_minor FROM app.invoice
                WHERE tenant_id = :tenant
                  AND (issued_at, id) < (:issued_at, :id)
                ORDER BY issued_at DESC, id DESC
                LIMIT 50
            """),
            {"tenant": tenant_id, "issued_at": before[0], "id": before[1]},
        )
        return [dict(row) for row in rows.mappings()]

A transaction-pooling configuration assigns a server connection for the life of the transaction. The setting and the protected work must be on that connection. With both operations inside the session transaction, PgBouncer can release the backend after commit or rollback. Calling set_config in a separate autocommit statement discards the local setting before the next statement executes. A session-wide SET is likewise inappropriate here because the next transaction can have a different backend, and session state must never pick the tenant for a new request. PgBouncer pooling mode guarantees and limitations

# Mount a private auth file and configure TLS for the deployment.
[databases]
app = host=db.internal port=5432 dbname=app

[pgbouncer]
pool_mode = transaction
auth_type = scram-sha-256
auth_file = /etc/pgbouncer/userlist.txt

The configuration fragment assumes a private user list and deployment-specific client and server TLS. Validate driver and pooler prepared-statement settings together before production. Do not build tenant context into an engine-level connection checkout event that might execute before the actual PostgreSQL transaction starts. Keep the transaction wrapper in one application abstraction and use it for background jobs, exports, reports and command handlers.

Verify visibility and query plans as the restricted role

Seed two tenants and test following flows as the actual login or a matching restricted role. For testing only, use a trusted database administrator to set up the fixtures. The application principal must never be able to create arbitrary invoice fixtures for another tenant.

  1. Start a transaction with tenant A and query without an explicit tenant predicate. Confirm it only returns tenant A.
  2. Try to insert with tenant B in the row while tenant A is set. Confirm the policy rejects it.
  3. Try to move an existing tenant A row to tenant B. Confirm the proposed row fails WITH CHECK.
  4. Rollback, begin another transaction on the same logical client and omit the new context. Expect an empty result.
  5. Run the expected queries for a small tenant and a large tenant, with dimensions matching production data skew.

Use EXPLAIN (ANALYZE, BUFFERS) on a safe representative read. Look for a scan that narrows by tenant and stops early when the query asks for a small most-recent page. A composite B-tree with tenant, timestamp and ID can match that listing. Another query may prefer a sequential scan, especially when it returns most of a small table. A node name alone does not tell you whether a plan is inefficient. Check actual rows, loops, buffer reads, planning stability and whether the sort spills. Keep predicates on typed columns. Repeated joins or lookups inside a policy can dominate a large scan. PostgreSQL documentation on reading EXPLAIN plans

Failure modes worth testing before rollout

The migration owner becomes the runtime user

Everything appears healthy, but the service runs with an identity that owns the table or bypasses row security. Check ownership and attributes on the actual deployment credentials. Add a smoke test for same-tenant reads and cross-tenant rejection. Verify how role inheritance and privileged functions affect each protected path.

A worker never establishes the tenant transaction

A worker opens a session and sees no rows, which it misinterprets as an empty queue. Pass authorised tenant context into the task payload from a trusted source and set it explicitly in the transaction. For tasks intentionally operating across tenants, create and audit a distinct job identity with an explicit scope instead of broadly expanding the main application role.

A raw export uses a privileged view

A view or reporting table may expose data according to different privileges. Test the actual SQL used by exports. Use caller-checked views when appropriate and verify compiled or replicated report data independently. Identity checks on a primary table do not automatically enforce access to a copied dataset.

Ordinary code gains arbitrary SQL execution

A configurable query builder accepts unexpected SQL rather than parameters. Because the application role supplies the custom tenant value, RLS does not turn a shared service login into an independent identity boundary. Parameterise values, allowlist dynamic identifiers, and avoid executing user-provided statements. Where the threat model requires containment of a compromised service principal, design a stronger database boundary.

When to choose a different tenant layout

  • Separate databases give a clearer operational and restore boundary where regulation, contractual isolation or encryption ownership requires it. The costs include provisioning, dependency rollouts and additional connection pools.
  • Separate schemas can support differing data lifecycles without a database per tenant. Audit privileges, migrations and schema selection. A shared privileged login can still reach across schemas.
  • Shared tables plus RLS suit tenants with a common schema and a need for efficient pooled infrastructure. The application remains responsible for authentication, membership and action policy.

Measure the overhead that matters to your query mix

In a hypothetical setup with 100 tenants and one million invoices, an even distribution averages 10,000 rows per tenant. If one customer instead holds 300,000 invoices, the mean hides the very population that may need different plans. Compare recent listings and exports for both tenant sizes under the same application role, parameter style and pooler used in production. Capture median and tail latency with buffer use. Reproduce a query that includes a join or permission check if those predicates appear in your actual policies. Use real measurements to decide if the policy predicate or the data access pattern needs work.

Make rollout gradual. Create the owner and runtime roles, deploy the transaction wrapper, exercise integration tests, then enable the policy with a short lock budget appropriate to your workload. Coordinate the database change with worker versions that already set tenant context. Check the number of unexpected empty results and policy rejections during the rollout. A rejection can reveal a missing tenant binding and deserves investigation.

Frequently asked questions

How do I use PostgreSQL RLS with PgBouncer transaction pooling?

Open a transaction, set the authorised tenant with set_config using its local mode, and run every protected statement on that transaction’s connection. PgBouncer keeps the backend assigned for the transaction. Commit or roll back before returning it. Avoid setting the tenant outside the transaction or assuming one session owns the backend.

Does PostgreSQL row-level security apply to the table owner?

A table owner normally bypasses row-level security. FORCE ROW LEVEL SECURITY makes the owner subject to policy during ordinary access. Superusers and roles with BYPASSRLS can still bypass the policy. Give the application login its own restricted role and test access with the same identity used in the deployment.

What is the performance impact of PostgreSQL RLS?

It depends on the policy predicate, indexes and tenant distribution. A direct tenant comparison can work with an index that starts with tenant ID, while repeated lookups or joins can add more work. Inspect representative EXPLAIN ANALYZE plans and buffer counts while connected as the production-equivalent runtime role.

Does RLS replace tenant checks in the SaaS application?

The application still verifies the principal, authorises membership and controls which actions are permitted. A row-level policy that reads a custom tenant setting trusts the service to set the correct tenant. Keep that setting transaction-local, restrict privileges and treat RLS as another check on ordinary application queries.

Further reading

Planning PostgreSQL row-level security for shared tables? Talk to Dumb Potato about the authentication boundary, migration order and negative test cases.

Dumb Potato Editorial

Putting this into practice?

Share the problem you’re solving and the tradeoffs you’re weighing with our engineering team.

See how we help with data platforms

Discuss your project