---
title: "PostgreSQL Partitioning for 100M+ Row SaaS Tables"
published: true
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: postgresql, architecture, api, performance
canonical_url: https://mvpfactory.co/blog/postgresql-partitioning-saas-scale
---
What You Will Learn
By the end of this workshop, you will understand how PostgreSQL declarative partitioning works under the hood — how the query planner eliminates entire partitions at plan time, where the global index footgun hides, and how to roll a zero-downtime ATTACH/DETACH archival pattern into your production SaaS schema. If your tables are approaching 100M rows, this is the lever you want before you need it.
Prerequisites
- PostgreSQL 10 or later (declarative partitioning is built in, no extensions)
- A table with a natural time dimension growing faster than ~10M rows per month
- Basic familiarity with
EXPLAINoutput andCREATE INDEX
Step 1: Choose Your Partitioning Strategy
Here is the decision table I use on every project:
| Strategy | Best For | Partition Pruning | Gotchas |
|---|---|---|---|
| Range | Time-series, event logs, audit trails | Excellent — planner eliminates by key bounds | Hot partition on current range; uneven sizes over time |
| Hash | Even distribution, tenant data | Moderate — equality predicates only | Cannot drop "old" data without detaching; no natural archival |
| List | Region, status, low-cardinality tenant ID | Excellent on equality | Cardinality 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 retention windows, enables the ATTACH/DETACH pattern, and gives the planner the most leverage.
Step 2: Create the Partitioned Table
Here is the minimal setup to get this working:
CREATE TABLE events (
id BIGSERIAL,
tenant_id UUID NOT NULL,
occurred_at TIMESTAMPTZ NOT NULL,
payload JSONB
) PARTITION BY RANGE (occurred_at);
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 sees that events_2024_q2 through events_2024_q4 cannot satisfy the predicate and excludes them entirely. Confirm it is working with EXPLAIN and ensure enable_partition_pruning = on (the default). This is constraint exclusion — evaluated at plan time, not execution time.
Step 3: Implement the ATTACH/DETACH Pattern
Let me show you a pattern I use in every project for zero-downtime archival:
-- 1. Build the new partition outside the parent (no locks on the parent table)
CREATE TABLE events_2024_q4 (LIKE events INCLUDING ALL);
-- Load and index it offline
\COPY events_2024_q4 FROM 'export_q4.csv' CSV;
CREATE INDEX ON events_2024_q4 (tenant_id, occurred_at);
-- 2. Attach — acquires ShareUpdateExclusiveLock, NOT AccessExclusiveLock
ALTER TABLE events
ATTACH PARTITION events_2024_q4
FOR VALUES FROM ('2024-10-01') TO ('2025-01-01');
-- 3. Detach and archive the old partition
ALTER TABLE events DETACH PARTITION events_2024_q1;
DROP TABLE events_2024_q1;
ATTACH PARTITION combined with a pre-validated constraint (ALTER TABLE ... ADD CONSTRAINT ... NOT VALID + VALIDATE CONSTRAINT) avoids a full table scan and acquires only a lightweight lock. On a partition in the tens of gigabytes, that is the difference between a 200ms lock window and a multi-minute outage.
Gotchas
The docs do not mention this clearly enough, but there are two places the local index behaviour bites you hard:
1. Uniqueness constraints must include the partition key. 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 from day one.
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.
Here is the gotcha that will save you hours: 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 — must be fully automated and tested in staging before you need them under pressure in production.
Conclusion
The inflection point is predictable: somewhere between 50M and 150M rows, B-tree index scans stop being fast enough and autovacuum starts falling behind. A sequential scan on a 200GB table that could be pruned to a 2GB partition is a 100x regression waiting to happen.
Three things to take away:
- Partition by time before you need to. Migration from an unpartitioned 200M-row table is expensive. If your table has a natural time dimension, partition it now.
- Design unique constraints around the partition key from day one. Retrofitting uniqueness semantics after partitioning is painful.
- Automate ATTACH/DETACH as a cron job. This should never be a manual runbook operation under production pressure.
Top comments (0)