Multi-Tenant PostgreSQL: RLS vs. Partitioning at Scale

0 Shares
0
0
0

Scaling a B2B SaaS database past the first few thousand tenants exposes two recurring bottlenecks: noisy-neighbor resource contention and uneven query planning. While early-stage SaaS platforms commonly start with a shared-table design protected by PostgreSQL Row-Level Security (RLS), growing customer volume forces teams to weigh three core isolation patterns: Shared Schema with RLS, Schema-per-Tenant, and Declarative Partitioning (or distributed sharding).

1. Shared-Schema Baseline and Real RLS Overhead

In a shared-table architecture, every multi-tenant table carries a tenant_id column, and PostgreSQL enforces isolation at the database layer via RLS policies:

SQL

ALTERTABLE telemetry_events ENABLE ROW LEVEL SECURITY;
-- Crucial in production: without FORCE, the table owner role bypasses RLS
ALTERTABLE telemetry_events FORCE ROW LEVEL SECURITY;

CREATE POLICY tenant_isolation_policy ON telemetry_events
USING (tenant_id =NULLIF(current_setting('app.current_tenant_id', true), '')::uuid)
WITHCHECK (tenant_id =NULLIF(current_setting('app.current_tenant_id', true), '')::uuid);

What Benchmarks Actually Show About RLS

A common myth is that RLS policy evaluation itself slows down queries. Published PostgreSQL benchmarks show the opposite—the bottleneck is indexing, not the policy check:

  • Policy evaluation cost is negligible: In a 1-million-row benchmark comparing identical queries with and without RLS enabled, policy evaluation added only 1.6 ms on a full-table count (73.3 ms unguarded vs. 74.9 ms with RLS). Once a tenant_id index was added, latency dropped to 2.2 ms–2.7 ms (a 26× speedup).
  • Pipelined connection overhead: In a 64-worker concurrent read test reaching 142,564 reads/sec, passing the tenant context and executing an RLS-guarded query averaged 47.5 µs per single-worker query compared to 42.9 µs unguarded—just 4.6 µs of policy overhead.

Where Shared Tables Actually Break at Scale

Technical diagram showing noisy-neighbor resource contention and B-tree index bloat in a shared-schema PostgreSQL database
High-volume enterprise tenants can cause index bloat and heap fetch bottlenecks in shared multi-tenant tables.
  1. Secondary Predicate Heap Fetches: Even with an index on tenant_id, filtering on an unindexed secondary column (e.g., status or timestamp) forces PostgreSQL to visit heap blocks to evaluate the second condition, keeping filtered query latency around 40 ms vs. 42 ms unindexed. Composite indexes (tenant_id, created_at) are mandatory.
  • PgBouncer Session-State Leaks: Under PgBouncer in transaction pooling mode, running a session-level SET app.current_tenant_id leaves the tenant ID attached to the pooled server connection after the transaction ends—exposing the next client on that connection to the previous tenant’s context. Production systems must use transaction-local set_config(‘app.current_tenant_id’, …, true) inside each transaction.
  • Table Owner Bypass & Non-SQL Stores: By default, table owners bypass RLS unless FORCE ROW LEVEL SECURITY is applied. Furthermore, RLS does not protect Redis caches, background queues, or object storage—those layers require explicit tenant-prefixed keys.

2. Schema-per-Tenant Isolation Limits

Systems architecture illustration depicting PostgreSQL system catalog bloat across thousands of isolated tenant schemas
caling past thousands of tenant schemas inflates pg_class and pg_statistic metadata, slowing down DDL migrations.

Assigning each customer a dedicated schema (tenant_001.orders, tenant_002.orders) isolates per-tenant tables and allows targeted backups using pg_dump -n tenant_001. However, PostgreSQL’s system catalog design imposes a practical ceiling:

  • System Catalog Bloat: Every table and index registers metadata in pg_class, pg_attribute, and pg_statistic (~1–2 KB per table in pg_class alone). In a benchmark modeling 10,000 tenants with just 5 tables and 3 indexes each (50,000 tables), system catalog overhead reaches roughly ~400 MB, and adding a single column across all tenants stretches DDL migration time from ~1 second (at 100 tenants) to ~2 minutes (at 10,000 tenants)—with the risk of partial failure mid-loop.
  • Practical Crossover Point: Engineering benchmarks place the manageable ceiling for schema- or table-per-tenant designs around 1,000 to 5,000 tenants (fewer if each tenant has dozens of tables), after which catalog bloat and migration locks degrade planner and operational stability.

3. Declarative Partitioning and Distributed Sharding

To get physical data separation without tens of thousands of independent schemas, high-scale PostgreSQL deployments combine Declarative Partitioning (or extensions like Citus) with composite keys:

SQL

CREATETABLE audit_logs (
  tenant_id uuid NOTNULL,
  event_id uuid NOTNULL,
  recorded_at timestamptz NOTNULL,
  payload jsonb,
  PRIMARY KEY (tenant_id, recorded_at, event_id)) PARTITIONBY HASH (tenant_id);
Data flow diagram showing PostgreSQL declarative hash partitioning routing tenant queries into isolated storage partitions
Declarative hash partitioning isolates active data trees and enables partition pruning for predictable p99 read latency.
  • Single DDL Propagation: Running ALTER TABLE audit_logs ADD COLUMN ... automatically propagates across all child partitions, avoiding sequential migration loops.
  • Per-Partition VACUUM and Statistics: Autovacuum runs independently on active partitions, preventing a high-churn enterprise tenant from starving smaller tenants of I/O, while pg_statistic tracks accurate row counts per partition.
  • Partition Pruning Requirement: Application queries must include tenant_id in the WHERE clause (or combine RLS with explicit partition-key filters) so the PostgreSQL planner prunes inactive partitions at planning/execution time. When single-node hardware limits are reached (typically beyond 50,000+ tenants or multi-terabyte datasets), distributed PostgreSQL extensions like Citus hash-shard tables by tenant_id across worker nodes.

Architecture Comparison Matrix

Architectural ModelPractical Tenant Sweet SpotSchema Migration BehaviorPer-Tenant Recovery / DeletionKey Operational Trade-Off
Shared Table + RLS 1 – 5,000 (up to 50,000 with careful indexing)Low (Single DDL statement)Hard (Requires row-level filtering/export)Requires composite indexes, FORCE RLS, and transaction-local set_config
Schema-per-Tenant< 100 – 3,000 (depending on table count)High (Sequential ALTER TABLE loop per schema)Easy (pg_dump -n / DROP SCHEMA)pg_class / pg_statistic bloat and lock risk during migrations
Declarative Partitioning100 – 50,000 (single node)Low–Moderate (Parent DDL propagates to partitions)Easy (DETACH PARTITION / DROP)List partitioning per tenant hits catalog limits at thousands of partitions; Hash partitioning groups tenants
Distributed Sharding (Citus)10,000 – 100,000+Moderate (Distributed DDL propagation)Moderate (Shard-level isolation/rebalancing)Cross-tenant joins and distributed transactions require strict co-location by tenant_id

Real-World References & Benchmarks

  1. RLS Performance Benchmark (1M Rows & Index Impact): Does Postgres RLS actually ruin performance? Let’s look at the data (DEV Community, 2026) High-Concurrency Pipelined RLS Benchmark: Benchmarking single round trip PostgreSQL RLS at 142,564 reads/sec (r/PostgreSQL, 2026)
  2. Production RLS & PgBouncer Pitfalls: Multi-Tenant SaaS on PostgreSQL: RLS, Schema-per-Tenant, and Caching Bugs (RorixTech, 2026)
  3. Catalog Bloat & Migration Timing Benchmarks: Table-Per-Tenant vs. Shared Table: The Multi-Tenancy Tradeoff in Postgres (Medium, 2026)
  4. AWS Multi-Tenant Architecture Guidance: Multi-tenant data isolation with PostgreSQL Row Level Security (AWS Database Blog)
0 Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

You May Also Like