Skip to content

Multi-Tenant Data Isolation: Row-Level Security (RLS), Tenant Indexes, and Fail-Closed Defaults

2 min read

In multi-tenant SaaS, forgetting a single WHERE workspace_id = $1 clause in an endpoint or background worker can expose one company's private messages to another. Relying purely on developer memory does not scale. Defense-in-depth enforces tenant boundaries at both the application layer and the database layer.

Defense-in-Depth Isolation Checklist

Control LayerMechanismWhat It Stops
Auth MiddlewareResolve membership from verified JWT + DB role checkForged workspaceId headers or URL params
Database RLSPostgreSQL Row-Level Security policies enabled on every tenant tableAccidental unfiltered queries from client or RPC roles
Composite IndexesLead indexes with (tenant_id, ...)Slow cross-tenant table scans and noisy-neighbor lockups
Cache & Queue KeysPrefix every cache key and pub/sub channel with tenantId:Cross-tenant cache pollution and real-time event leaks

Writing Performant PostgreSQL RLS Policies

RLS is powerful, yet poorly written RLS policies calling unindexed subqueries per row can devastate query latency. Always index membership foreign keys and wrap auth.uid() in a scalar (SELECT auth.uid()) so Postgres evaluates it once per statement instead of once per scanned row:

sql
ALTER TABLE workspace_documents ENABLE ROW LEVEL SECURITY;

CREATE POLICY workspace_members_read_documents
  ON workspace_documents
  FOR SELECT
  TO authenticated
  USING (
    EXISTS (
      SELECT 1
      FROM workspace_members wm
      WHERE wm.workspace_id = workspace_documents.workspace_id
        AND wm.user_id = (SELECT auth.uid())
    )
  );

Fail-Closed Defaults for Sensitive Tables

  • Revoke PUBLIC and anon privileges on private tables and RPC functions explicitly.
  • Restrict client-side writes on security-critical tables (billing subscriptions, OAuth credentials, role grants) so mutations flow exclusively through audited server-side endpoints or SECURITY DEFINER procedures with locked search_path.
  • Add automated integration tests that authenticate as User B and assert 403 / empty results when attempting to read or mutate Tenant A's IDs.

Next: deliver tenant-scoped real-time events smoothly across browser tabs in Real-Time Messaging Architecture.

Was this helpful?