← Writing / Product Engineering

Multi-Tenant Data Isolation with PostgreSQL Row-Level Security in Production SaaS

Moving tenant authorization out of brittle application WHERE clauses and into the database engine: how PostgreSQL RLS guarantees zero cross-tenant data leakage in multi-user applications.

P
Primidac
Product Engineer · Security & AI
Multi-Tenant Data Isolation with PostgreSQL Row-Level Security in Production SaaS

The Problem with Application-Level Multi-Tenancy

In conventional web development, developers segregate tenant data by adding WHERE tenant_id = current_tenant_id to every SQL query or ORM hook.

This approach fails at scale because:

  • Developer Oversight: One missed filter in an internal report or batch task leaks sibling tenant records.
  • ORM Leaks: Eager-loaded relationships or raw query builders frequently omit global scopes.
  • Complex Joins: Subqueries and aggregate analytics bypass application-level middleware.

The solution is enforcing data boundaries directly at the database engine level using PostgreSQL Row-Level Security (RLS).


1. Enabling RLS at the Database Level

With Row-Level Security, PostgreSQL evaluates tenant boundaries before returning rows to the client:

-- 1. Enable RLS on the table
ALTER TABLE projects ENABLE ROW LEVEL SECURITY;

-- 2. Force RLS for all table owners (prevent accidental superuser bypass)
ALTER TABLE projects FORCE ROW LEVEL SECURITY;

-- 3. Define the tenant isolation policy
CREATE POLICY tenant_isolation_policy ON projects
  FOR ALL
  TO authenticated_app_user
  USING (tenant_id = current_setting('app.current_tenant_id', true)::uuid)
  WITH CHECK (tenant_id = current_setting('app.current_tenant_id', true)::uuid);

2. Managing Tenant Context in Connection Pools

In pooled application servers (Next.js, Node, Go), database connections are shared across concurrent requests. To safely scope each transaction:

import { pool } from './db';

export async function withTenantContext<T>(
  tenantId: string,
  operation: (client: any) => Promise<T>
): Promise<T> {
  const client = await pool.connect();
  try {
    await client.query('BEGIN');
    
    // Scoped strictly to the current transaction
    await client.query(
      'SELECT set_config($1, $2, true)',
      ['app.current_tenant_id', tenantId]
    );

    const result = await operation(client);
    await client.query('COMMIT');
    return result;
  } catch (err) {
    await client.query('ROLLBACK');
    throw err;
  } finally {
    client.release();
  }
}

The third argument true in set_config specifies that the parameter applies only to the local transaction, preventing tenant context leakage to subsequent queries reusing the pooled connection.


3. Performance & Index Optimization

RLS adds filter evaluation on table scans. To maintain sub-5ms query performance:

  • Always create composite indexes on (tenant_id, id) and (tenant_id, created_at).
  • Use EXPLAIN ANALYZE with tenant settings applied to confirm index scans are utilized over sequential scans.

When architected this way, multi-tenant isolation becomes an impenetrable database invariant rather than an afterthought.

// ARCHIVE
Explore more notes & research.
← All Technical Notes
Notification