0%
PostgreSQL Deep Dive: MVCC, Vacuum, Plans, and Replication
Architecture and Storage
MVCC and Vacuum
Indexes and Query Planning
Partitioning
Partitioning splits one logical table into many physical tables, each holding a slice of the rows by a key such as date or tenant. Queries still address the parent table, and Postgres routes rows and prunes partitions automatically. Done well, partitioning makes huge tables manageable: old data drops in an instant, vacuum works on small pieces and queries touch only relevant slices. Done badly, it adds overhead with no benefit. This section explains what partitioning solves and when it is worth it.
Declarative partitioning
Since version 10, CREATE TABLE with PARTITION BY RANGE, LIST or HASH defines a partitioned parent that holds no rows itself. Partitions are ordinary tables attached with FOR VALUES clauses describing their slice. Inserts into the parent are routed to the right partition, updates that change the key move rows between partitions, and queries on the parent are planned across the partitions that could contain matching rows.
The problems partitioning solves
The strongest reasons are data lifecycle and maintenance. Deleting a month of old rows from a 5 billion row table means a huge DELETE, bloat and vacuum work; with monthly partitions it is a DROP of one partition, instant and without bloat. Vacuum, analyze and index rebuilds work on smaller tables. Time ordered data concentrates writes on the newest partition, whose indexes stay small and cached.
Partition pruning
When a query has a condition on the partition key, the planner excludes partitions that cannot contain matching rows, partition pruning. A query for last week touches one or two partitions out of hundreds. Pruning also happens at execution time for parameters and join values not known at planning, using initial and runtime pruning. EXPLAIN shows the remaining partitions and a Subplans Removed line when execution time pruning applied.
Loading problem...
Partitioning is not an index
Partitioning does not make point lookups by primary key faster: a B-tree on a 5 billion row table is only one or two levels deeper than on a 50 million row partition, and queries without the partition key must check every partition, which is slower. Partitioning helps when queries naturally filter on the key and when data lifecycle matters. For lookup speed alone, a good index on an unpartitioned table usually wins.
Signs a table needs partitioning
Common signals: a table in the hundreds of gigabytes or larger that grows continuously; retention requirements that delete large slices of old data; vacuum on the table running for hours or falling behind; queries that almost always filter on a time range or a tenant; and maintenance such as reindexing that has become impractical. A table of 20 GB rarely benefits; a 2 TB event log with 90 day retention almost always does.
Costs and limits
Partitioning has costs. Each partition is a table with its own indexes and statistics. Planning time grows with the number of partitions when pruning cannot happen at plan time. Primary keys and unique constraints must include the partition key. Foreign keys referencing partitioned tables are supported since version 12. Some operations, such as moving rows between partitions on update, are more expensive. These costs are small when partitioning fits the access pattern and significant when it does not.
Unique constraints must include the key
A unique index on a partitioned table is enforced per partition, so it must include the partition key columns, otherwise two partitions could each contain the same value. A table partitioned by created_at therefore cannot have a primary key on id alone, only on id and created_at. If global uniqueness of id matters, it must come from the generator, such as a sequence or UUID, or from a separate unpartitioned lookup table.
How many partitions
The planner and executor handle thousands of partitions in recent versions, but each adds catalog entries, files, memory in each backend that touches it and planning work when pruning is incomplete. A practical range is tens to a few thousand partitions. Daily partitions for years of data, or many thousands of tenant partitions, approach the limits, and coarser partitions or subpartitioning are worth considering.
Partitioning existing tables
An existing large table cannot be converted to partitioned in place. Common approaches create a new partitioned table and attach the old table as a partition covering the historical range, after adding a matching CHECK constraint so the attach skips validation; or build a new partitioned table and copy data in batches with a dual write or logical replication, then switch. Planning the conversion early, before a table grows enormous, makes it much easier.
Inheritance based partitioning
Before version 10, partitioning was built from table inheritance: child tables inherited from a parent, CHECK constraints described each child range, and triggers on the parent routed inserts to the right child. Constraint exclusion skipped children whose CHECK contradicted the query. Many older systems still run this way. Declarative partitioning is faster, simpler and better supported, so migrating old inheritance schemes is usually worthwhile.
Hot and cold data
Time partitioned tables split naturally into a hot partition receiving writes and many cold ones that are only read. The hot partition and its indexes stay in shared buffers, so inserts and recent queries are fast, while cold partitions are read rarely and can sit on slower storage. Without partitioning, recent rows share index pages with old ones, and the indexes of a huge table rarely fit in memory, so even recent lookups hit disk more often.
Bulk loading
Loading a large batch of data, such as a day of imported events, is faster into a separate table without indexes, which can then have indexes built in one pass and be attached as a partition. This avoids maintaining indexes row by row during the load and keeps the load from interfering with queries on existing partitions. Replacing a partition with a corrected version uses the same pattern: load a new table, detach the old partition and attach the new one.
Parallelism
Scans over many partitions can be parallelized with Parallel Append, which distributes partitions among workers so each scans different partitions at the same time. This speeds up analytical queries over large ranges. Partitioning is not required for parallel query, which also works on unpartitioned tables by splitting blocks among workers, but Parallel Append can mix partitions with different scan types efficiently.
Partitioning and replication
Partitions replicate like any other tables. Physical standbys contain the same partitions, and logical replication can publish partitions individually or through the root with publish_via_partition_root. Dropping a partition on the primary drops it on standbys instantly through WAL, which makes retention cheap across the whole cluster, not just on the primary.
Partitioning and backups
Partitioning does not change physical backups, which copy the whole cluster, but it helps logical ones: pg_dump can dump only recent partitions, and old static partitions can be exported once and excluded from regular dumps. Restoring a single partition from an archive, for example to answer a question about last year, is much easier than extracting a range of rows from a full dump of a huge table.
Measure before deciding
Before partitioning, collect evidence: table and index sizes, growth rate, the most frequent queries and their filters from pg_stat_statements, vacuum durations from logs, and retention requirements. If most top queries filter on a candidate key and retention or maintenance hurts, partitioning likely helps. If queries rarely filter on any single column consistently, partitioning will likely make them slower.
Partitioning and caching
Because recent data lives in a small number of partitions, the working set of a time partitioned table is easier to fit in memory. The current partition and its indexes stay hot in shared buffers and the operating system cache, while old partitions are read only when needed and do not push recent pages out of the cache.
Explaining the decision
Partitioning a table is a long term commitment, since undoing it is as much work as doing it. Writing a short design note with the evidence, the chosen key and the expected benefits lets reviewers check the reasoning, and gives future engineers context when they wonder whether the scheme still fits.
Partitioning routes rows to child tables by a key. It pays off for large growing tables with retention, maintenance pain and queries that filter on the key, where DROP replaces DELETE and pruning skips irrelevant partitions. Unique keys must include the partition key, and too many partitions add planning cost.