MVP Factory
EN
ai startup development

PostgreSQL partitioning for 100M+ row SaaS tables

KW
Krystian Wiewiór · · 5 min read

Meta description: Master PostgreSQL declarative partitioning — Range, Hash, and List strategies, partition pruning internals, global vs. local indexes, and the ATTACH/DETACH pattern for zero-downtime archival at scale.

Tags: backend microservices saas api architecture


TL;DR

Once your SaaS tables cross 100M rows, full-table scans and bloated indexes become existential threats to query latency. PostgreSQL declarative partitioning — combined with constraint exclusion for pruning and the ATTACH/DETACH pattern for online schema operations — is the lever most teams reach for too late. What they get wrong, and how to fix it.


Why partitioning becomes non-negotiable above 100M rows

In my experience building production systems on PostgreSQL, the inflection point is predictable: somewhere between 50M and 150M rows, B-tree index scans stop being “fast enough,” autovacuum starts falling behind, and your DBA starts losing sleep. A sequential scan on a 200GB table that could be pruned to a 2GB partition is a 100x regression waiting to happen.

The response is declarative table partitioning, available without extensions since PostgreSQL 10. The question is not whether to partition, but which strategy fits your access patterns.


Range vs. Hash vs. List: choosing your strategy

StrategyBest ForPartition PruningGotchas
RangeTime-series, event logs, audit trailsExcellent — planner eliminates partitions by key boundsHot partition on current range; uneven sizes over time
HashEven distribution, tenant dataModerate — only on equality predicatesCannot drop “old” data without detaching; no natural archival
ListRegion, status, tenant ID (low cardinality)Excellent on equalityCardinality explosion past ~100 partitions hurts planning time

For SaaS event logs and audit tables, Range partitioning on a timestamp column is almost always the right answer. It aligns with your natural retention windows, enables the ATTACH/DETACH archival pattern, and gives the query planner the most leverage.


How the planner uses constraint exclusion

This is where PostgreSQL earns its keep. When you define a Range partition, the planner stores the partition bounds as implicit CHECK constraints. At plan time — not execution time — it evaluates your WHERE clause against those bounds and eliminates entire partitions from the scan.

-- Partitioned table
CREATE TABLE events (
  id          BIGSERIAL,
  tenant_id   UUID NOT NULL,
  occurred_at TIMESTAMPTZ NOT NULL,
  payload     JSONB
) PARTITION BY RANGE (occurred_at);

-- Quarterly partitions
CREATE TABLE events_2024_q1
  PARTITION OF events
  FOR VALUES FROM ('2024-01-01') TO ('2024-04-01');

A query with WHERE occurred_at >= '2024-01-01' AND occurred_at < '2024-02-01' triggers partition pruning: the planner’s constraint exclusion logic sees that events_2024_q2 through events_2024_q4 cannot possibly satisfy the predicate and excludes them entirely from the plan. Enable enable_partition_pruning = on (the default) and confirm pruning is happening via EXPLAIN.


Global indexes vs. local indexes: the hidden footgun

PostgreSQL does not support global indexes across all partitions. Every index you create on a partitioned table is implicitly a local index — one B-tree per partition. Usually fine. Two places it bites you:

  1. Uniqueness constraints must include the partition key. A UNIQUE(id) on a partitioned table is impossible unless id is part of the partition key. Use UNIQUE(id, occurred_at) or switch to application-level UUID generation.
  2. Foreign keys referencing a partitioned table are unsupported. FK constraints cannot span partition boundaries. If child tables need referential integrity against your partitioned parent, enforce it at the application layer or via triggers.

The ATTACH/DETACH pattern for zero-downtime operations

This pattern keeps your schema migrations online at scale. The workflow:

-- 1. Build the new partition outside the parent table (no locks on parent)
CREATE TABLE events_2024_q4 (LIKE events INCLUDING ALL);
-- Load data, build indexes, validate — all offline
\COPY events_2024_q4 FROM 'export_q4.csv' CSV;
CREATE INDEX ON events_2024_q4 (tenant_id, occurred_at);

-- 2. Attach — acquires a brief ShareUpdateExclusiveLock, not AccessExclusiveLock
ALTER TABLE events
  ATTACH PARTITION events_2024_q4
  FOR VALUES FROM ('2024-10-01') TO ('2025-01-01');

-- 3. Archive old partition — DETACH is also low-lock
ALTER TABLE events DETACH PARTITION events_2024_q1;
-- Optionally dump to cold storage, then drop
DROP TABLE events_2024_q1;

ATTACH PARTITION with a pre-validated constraint (ALTER TABLE ... ADD CONSTRAINT ... NOT VALID + VALIDATE CONSTRAINT) avoids a full table scan and acquires only a lightweight lock. For partitions in the tens of gigabytes, that’s the difference between a 200ms lock window and a multi-minute outage.


Takeaways

  1. Partition by time before you need to. The migration cost from an unpartitioned 200M-row table to a partitioned one is high. If your table has a natural time dimension and is growing faster than 10M rows per month, partition it now.

  2. Design your unique constraints around the partition key from day one. Retrofitting uniqueness semantics after partitioning is painful. Include occurred_at or your partition key in every unique index upfront.

  3. Automate the ATTACH/DETACH lifecycle as a cron job, not a runbook. Rolling retention windows — attach this month’s partition, detach and archive the partition from N months ago — should be fully automated and tested in staging before you need them under pressure in production.


Share: Twitter LinkedIn