Partitioning & Sharding in PostgreSQL
"Dropping an individual partition using DROP TABLE, or doing ALTER TABLE DETACH PARTITION, is far faster than a bulk operation." — PostgreSQL documentation, Table Partitioning (Benefits of Partitioning)
Summary: Partitioning splits one big table into smaller tables on the same server; sharding splits the data across servers. The first is a PostgreSQL feature, the second is an architecture you build or buy. Focus: Declarative partitioning (RANGE, LIST, HASH), pruning, ATTACH/DETACH, the unique-key rule, rotation with pg_partman; then shard keys, routing, scatter-gather and resharding with Citus, postgres_fdw, application routing, and how MySQL, Vitess and MongoDB do the same jobs. Learning goal: Partition a large table so queries prune and retention is a DROP, know every lock and limit on the way, and decide whether (and how) to shard with a key you will not regret.
This page is the hands-on reference for splitting data in PostgreSQL. The conceptual question of when a system should scale out (vertical vs horizontal, read replicas, caches, the scale ladder) is on Storage & Data Scaling; the operational playbook for huge tables (statistics, BRIN, batch backfills, COPY) is on Working with Billion-Row Tables. Four neighbours get one sentence each here and a link: the hash ring, virtual nodes and jump hash are on Consistent Hashing; globally unique keys (UUIDv7, Snowflake) on ID Generation at Scale; tenant isolation models on Multi-Tenancy Strategies; and atomic commit across servers (2PC, consensus) on Distributed SQL, Consensus & 2PC. Reading EXPLAIN itself is taught on Query Planning.
Page map
| If you are looking for | Go to |
|---|---|
| A table you can memorise in one minute | Everything in one minute |
| Why split at all; partitioning vs sharding; vertical vs horizontal | Why partition, why shard |
Declarative partitioning vs inheritance; Citus, postgres_fdw, pg_partman | Where it comes from |
| RANGE, LIST, HASH, DEFAULT, sub-partitioning, pruning, partitionwise join, unique keys, indexes, foreign keys, ATTACH/DETACH, rotation | Partitioning, concept by concept |
| Shard key, hot shards, scatter-gather, resharding, global IDs, multi-tenant | Sharding, concept by concept |
| PostgreSQL vs MySQL vs Oracle vs SQL Server partitioning; Citus vs Vitess vs MongoDB vs CockroachDB vs Redis Cluster | What each product really does |
| Locks per DDL, tuple routing, every knob, error messages | Mechanics |
| SQL + Go + Laravel for retention, migrating a live table, unique IDs, indexing, routing | Solving the classic problems |
| Which strategy for which workload | Choosing a strategy |
| Monolith to distributed data | In architecture |
| 10M-row table, pruning in EXPLAIN, rotation, a 3-shard Docker Compose | Lab |
| Wrong beliefs, a cheat sheet, every term defined | Misconceptions, Cheat sheet, Glossary |
Everything in one minute
The concepts. Every row is unpacked further down.
| Concept | In plain words | Tiny example | Watch out |
|---|---|---|---|
| Partitioned table | A parent with no storage; rows live in child tables | events → events_2026_11, events_2026_12 | Cannot convert an existing table in place |
| Partition key | The column(s) that decide which child a row goes to | PARTITION BY RANGE (created_at) | Every unique key must include it |
| Partition pruning | The planner/executor skips children that cannot match | WHERE created_at >= '2026-12-01' scans one month | No key in WHERE = scan every child |
| Partitionwise join / aggregate | Join or GROUP BY child-by-child | Two tables hash-partitioned the same way | Off by default; costs planning time and memory |
| DEFAULT partition | Catch-all for rows that match no bound | cities_other PARTITION OF cities DEFAULT | Slows ATTACH; blocks DETACH CONCURRENTLY |
| ATTACH / DETACH | Plug a table in or out of the parent | Load a month offline, then attach it | Add a matching CHECK first to skip the scan |
| Sharding | Rows of one logical table on several servers | users 0–⅓ on shard0, ⅓–⅔ on shard1, ... | Every query must carry the shard key or fan out |
| Shard key | The column that decides the server | user_id, tenant_id | Low cardinality or skew = hot shard |
| Scatter-gather | Ask every shard, merge the answers | SELECT count(*) with no key | Latency = slowest shard; no shared snapshot |
| Resharding | Changing how rows map to shards | 3 → 4 shards | hash % n moves about three quarters of keys |
The methods.
| Method | Bound syntax (PostgreSQL) | Good for | Not good for |
|---|---|---|---|
| RANGE | FOR VALUES FROM ('2026-12-01') TO ('2027-01-01') (upper bound exclusive) | Time series, retention, archiving | Even spread of writes (the newest partition is hot) |
| LIST | FOR VALUES IN ('de', 'fr', 'nl') | Regions, tenants with known values, status archives | Unbounded value sets |
| HASH | FOR VALUES WITH (MODULUS 4, REMAINDER 0) | Spreading a large table without a natural range | Retention by time; adding buckets later |
| DEFAULT | DEFAULT (RANGE and LIST only) | Safety net for unexpected values | Long-term storage |
| Sub-partitioning | PARTITION OF ... PARTITION BY ... | One very large partition (time → tenant) | Partition count explodes |
The routes to sharding in a PostgreSQL shop.
| Route | Who routes | Cross-shard SQL | Rebalancing | Effort |
|---|---|---|---|---|
| Application-level routing | Your code (hash % n, directory table) | You merge in code | You write it | Low to start, high later |
| Citus | Coordinator node | Yes, distributed planner; co-located joins stay local | citus_rebalance_start() online | Medium |
postgres_fdw + partitioned parent | The local planner | Yes, pushes WHERE to remote servers | Manual | Medium; no 2PC |
| Vitess (MySQL) | VTGate | Yes, with scatter when no vindex | Online resharding | High (another stack) |
| MongoDB | mongos | Targeted or broadcast | Balancer moves chunks | Built in |
The three things to do.
| Situation | Do this |
|---|---|
| Table bigger than RAM, queries filter by time, old data must go | RANGE-partition by time, pre-create partitions, retire with DETACH ... CONCURRENTLY + DROP |
| One server is out of CPU, disk or write throughput | Shard by the key every hot query carries (tenant_id, user_id), co-locate related tables, plan resharding up front |
| Anything in between | Indexes, partial indexes, read replicas, connection pooling and partitioning first: they keep transactions, joins and foreign keys intact |
Why partition, why shard
A table that grows without bound hurts in three places at once: indexes deeper than memory, maintenance (VACUUM, CREATE INDEX, backups) that takes hours, and retention by DELETE that writes as much WAL as the original inserts. Partitioning fixes those on one server by turning one huge table into many ordinary ones with a router in front. The PostgreSQL manual gives a rule of thumb for when it pays: "the size of the table should exceed the physical memory of the database server". Sharding answers a different problem: one machine's CPU, RAM, disk or WAL throughput is no longer enough, so rows must live on several machines.
| Single table | Partitioned table (one server) | Sharded data (many servers) |
|---|---|---|
| One heap, one set of indexes | Many heaps and indexes, one per partition | Many databases, each with its own partitions |
Retention = DELETE + VACUUM | Retention = DETACH + DROP TABLE | Retention per shard |
| Every query sees all rows | Queries with the key prune to a few partitions | Queries with the key go to one shard; others fan out |
| Transactions, joins, FKs, unique keys: all normal | Same, except unique keys must include the partition key | Only inside a shard; across shards you need 2PC, sagas or a distributed database |
| Scale = bigger machine | Scale = bigger machine | Scale = more machines |
Vertical vs horizontal partitioning. Horizontal partitioning (what this page is mostly about) splits rows: January's rows here, February's there. Vertical partitioning splits columns: the rarely read bio text and avatar bytea of users go to a user_profiles table with the same key, so the hot users rows stay narrow (PostgreSQL's TOAST already does a little of this for large values automatically; see Database Internals). Sharding is horizontal partitioning across servers; moving whole tables to separate databases is the vertical cousin (Vitess calls it "vertical sharding").
The analogy we reuse on this page: a filing cabinet and branch offices. A filing cabinet with one drawer per month is partitioning: to find March's invoices you open one drawer (pruning), and at year end you carry the oldest drawer to the archive in one trip instead of pulling out ten thousand sheets (DETACH + DROP). It is still one cabinet in one office. Sharding is opening branch offices and deciding which branch keeps which customer's folder: each branch has its own staff (CPU) and shelves (disk), but a question about all customers means phoning every branch (scatter-gather), and moving customers between branches when one gets crowded is a project (resharding).
Three common misunderstandings, up front
- “Partitioning makes queries faster.” It makes queries that filter on the partition key faster, and makes bulk removal nearly free. A query without the key now touches every partition and plans more slowly than on one table.
- “Partitioning is sharding on one box.” Partitions share one server's CPU, RAM, disk and WAL. Partitioning adds no write throughput. Sharding does, and brings shard keys, hot shards, cross-shard queries and resharding with it.
- “I can partition by date and keep
PRIMARY KEY (id).” Not in PostgreSQL or MySQL: every unique constraint must include the partition key, because there is no global index to check uniqueness across partitions.
Where it comes from
Inheritance first, declarative later. PostgreSQL first supported partitioning through table inheritance: child tables with CHECK constraints, a trigger on the parent to route inserts, and constraint_exclusion to skip children at plan time. Declarative partitioning (PARTITION BY / PARTITION OF) replaced that hand-made scheme with a built-in router, bounds the planner understands, and pruning during execution. The manual still documents inheritance for cases declarative partitioning cannot express, warning that such methods "do not have some of the performance benefits of built-in declarative partitioning". The current manual (labelled PostgreSQL 19 when it was read for this page) describes three methods: range, list and hash; partitions "may themselves be defined as partitioned tables, resulting in sub-partitioning".
Scale limits are documented. The manual is specific about how far it goes:
"The query planner is generally able to handle partition hierarchies with up to a few thousand partitions fairly well, provided that typical queries allow the query planner to prune all but a small number of partitions." — PostgreSQL documentation, Table Partitioning (Declarative Partitioning Best Practices)
Sharding is outside core. PostgreSQL core has no sharding. The Postgres-native routes are the Citus extension (a coordinator plus workers, distributed and reference tables, an online rebalancer), postgres_fdw (foreign tables, which can be partitions of a local parent), and application-level routing. pg_partman is the de-facto extension for automating time- and number-based partition sets. Outside PostgreSQL, MySQL has its own partitioning (RANGE, LIST, HASH, KEY), Vitess shards MySQL behind a proxy (VTGate), and MongoDB shards collections by a shard key with a balancer. Citus's own documentation names the decision that matters most:
"Choosing the distribution column for each table is one of the most important modeling decisions because it determines how data is spread across nodes." — Citus documentation, Choosing Distribution Column
Partitioning, concept by concept
Each block: plain words, the usual wrong belief, the precise definition, a sequence, real scenarios, per-product behaviour where it differs, and the fix or usage in SQL (Go and Laravel follow in Solving the classic problems).
Partitioned table and partition key Must-know
In plain words: you create an empty parent that only knows how to split rows, then create child tables that each accept a slice. Inserts into the parent are routed to the right child.
Common misunderstanding: “I can ALTER TABLE events PARTITION BY ... on my existing table.” No: "It is not possible to turn a regular table into a partitioned table or vice versa." You create a new partitioned parent and move or attach the data (see migrating a live table).
Definition: the manual calls the partitioned table "a “virtual” table having no storage of its own"; partitions are ordinary tables with a partition bound. The partition key is the column list or expression list in PARTITION BY. For range and hash it may have several columns (up to 32). Rows are routed by key: "Updating the partition key of a row will cause it to be moved into a different partition if it no longer satisfies the partition bounds of its original partition." A row with no matching partition and no DEFAULT partition fails.
application PostgreSQL
1 INSERT INTO events (..., created_at = '2026-12-05')
2 parent "events": key = created_at
3 bound lookup -> events_2026_12 [2026-12-01, 2027-01-01)
4 row stored in events_2026_12 (ordinary heap + its indexes)
5 INSERT ... created_at = '2031-01-01'
6 no bound matches, no DEFAULT
7 ERROR: no partition of relation "events" found for row (SQLSTATE 23514)Real scenarios: an events or audit_log table keyed by time; an orders table keyed by region (LIST) to keep each region's data on its own tablespace; a sessions table hash-partitioned by user_id to keep each index small.
How to choose the key: the manual's advice is the column "which most commonly appear in WHERE clauses", tempered by two hard rules: unique constraints must include it, and data you will remove together should share a partition. A time column usually wins for append-only data; a tenant column for SaaS data that is deleted per tenant.
CREATE TABLE events (
id bigint GENERATED ALWAYS AS IDENTITY,
user_id bigint NOT NULL,
kind text NOT NULL,
payload jsonb,
created_at timestamptz NOT NULL,
PRIMARY KEY (id, created_at) -- must contain the partition key
) PARTITION BY RANGE (created_at);
SELECT tableoid::regclass AS partition, count(*) FROM events GROUP BY 1; -- which child holds whatRANGE partitioning Must-know
In plain words: each partition owns a contiguous, non-overlapping interval of the key, usually a time window.
Common misunderstanding: “FROM ('2026-12-01') TO ('2027-01-01') includes New Year's midnight.” Upper bounds are exclusive; adjacent partitions share the boundary value and the row belongs to the later one. A second trap: with timestamptz, a literal like '2026-12-01' is read in the session's TimeZone; create partitions from one job with a fixed time zone (UTC).
Definition: "The table is partitioned into “ranges” defined by a key column or set of columns, with no overlap between the ranges of values assigned to different partitions." Multi-column range keys compare lexicographically. MINVALUE/MAXVALUE express open ends.
time ─▶ 2026-10-01 2026-11-01 2026-12-01 2027-01-01
[ events_2026_10 )[ events_2026_11 )[ events_2026_12 )
INSERT created_at = '2026-12-01 00:00:00+00' -> events_2026_12 (lower bound inclusive)
INSERT created_at = '2026-11-30 23:59:59+00' -> events_2026_11Real scenarios: logs and events kept for 90 days; invoices kept 7 years and archived by year; IoT readings by day; a ledger partitioned by month so month-end jobs scan one partition.
| Product | Range partitioning |
|---|---|
| PostgreSQL | PARTITION BY RANGE; bounds per partition; DEFAULT allowed |
| MySQL InnoDB | PARTITION BY RANGE (expr) / RANGE COLUMNS; VALUES LESS THAN (...), MAXVALUE |
| Oracle | PARTITION BY RANGE; interval partitioning creates new ranges automatically |
| SQL Server | Partition function AS RANGE LEFT/RIGHT FOR VALUES (...) + partition scheme |
LIST partitioning Important
In plain words: you name the exact key values each partition holds.
Common misunderstanding: “LIST is for any category column.” Only for a small, known value set you want physically separated (and usually dropped or moved together). A status column whose rows move between values turns every status change into a cross-partition row movement (a delete plus insert).
Definition: "The table is partitioned by explicitly listing which key value(s) appear in each partition." List keys are a single column or expression.
INSERT country='fr' -> cities_eu (FOR VALUES IN ('de','fr','nl'))
INSERT country='br' -> cities_other (DEFAULT)
UPDATE cities SET country='de' WHERE ... country='br'
-> row moved: deleted from cities_other, inserted into cities_euReal scenarios: per-region data with region-specific retention (GDPR); a handful of very large tenants each in its own partition and the long tail in DEFAULT; archiving status = 'closed' orders.
HASH partitioning Important
In plain words: PostgreSQL hashes the key and the remainder of hash / modulus picks the partition: an even spread without a natural range.
Common misunderstanding: “Hash partitioning is sharding.” All buckets are on the same server; it spreads index size and VACUUM work, not load across machines. And it is useless for retention: you cannot drop "old" rows by dropping a bucket.
Definition: "The table is partitioned by specifying a modulus and a remainder for each partition." The manual's advice: initially choose "a modulus equal to the number of partitions and assign every table the same modulus". Hash partitions cannot have a DEFAULT partition. To split a bucket later, detach it and attach two partitions with a doubled modulus (e.g. remainder 1 of 4 becomes remainders 1 and 5 of 8), moving its rows yourself.
user_id = 42 -> hash(42) mod 4 = 2 -> sessions_p2
user_id = 43 -> hash(43) mod 4 = 0 -> sessions_p0
WHERE user_id = 42 -> prunes to sessions_p2
WHERE user_id > 40 -> cannot prune (hash destroys order): scans all fourReal scenarios: a large sessions or carts table with lookups by user_id; making two tables partitionwise-joinable (same key, same modulus); MySQL KEY partitioning plays the same role.
DEFAULT partition Important
In plain words: a catch-all child for rows that match no other bound, so inserts never fail with 23514.
Common misunderstanding: “A DEFAULT partition is free insurance.” It has three costs: rows silently pile up there (a forgotten month lands in DEFAULT and is never pruned well); attaching or creating a new partition must scan DEFAULT to prove none of its rows belong to the new range; and DETACH PARTITION ... CONCURRENTLY "is not allowed if the partitioned table contains a default partition".
Definition: CREATE TABLE ... PARTITION OF parent DEFAULT, for RANGE and LIST only. When a partition is added, "the default partition must be scanned to verify that it does not contain any rows which properly belong in the new partition", under ACCESS EXCLUSIVE on DEFAULT. The documented escape: a CHECK on the DEFAULT partition that excludes the new range.
1 rotate job fails for December; nobody notices
2 December rows land in events_default
3 January: ATTACH events_2026_12 ...
4 -> scans events_default under ACCESS EXCLUSIVE, finds December rows
5 ERROR: updated partition constraint for default partition "events_default" would be violated by some row
6 fix: move the rows out of DEFAULT first (INSERT ... SELECT + DELETE), then attachReal scenarios: LIST partitioning by country with a long tail; a safety net during a migration. Monitor it: SELECT count(*) FROM events_default should be zero for a time-partitioned table with healthy rotation. pg_partman creates a DEFAULT by default (p_default_table) and provides tools to move its rows out.
Sub-partitioning Good to know
In plain words: a partition can itself be partitioned: month first, then tenant hash inside the month.
Common misunderstanding: “More levels, more speed.” pg_partman's documentation is blunt that subpartitioning "provides next to NO PERFORMANCE BENEFIT outside of extremely large data in a single partition set", and the PostgreSQL manual warns that sub-partitioning and multi-column range keys "can easily lead to excessive numbers of partitions".
Definition: add PARTITION BY to a CREATE TABLE ... PARTITION OF. Unique constraints on the root must include the partition keys of every level. A sub-partition's bounds are not checked against its parent's: "the system does not try to check whether that's really the case".
events (RANGE created_at)
├── events_2026_12 (HASH tenant_id, modulus 4)
│ ├── events_2026_12_h0 ... events_2026_12_h3
└── events_2027_01 (HASH tenant_id, modulus 4)
WHERE created_at in December AND tenant_id = 7 -> one leaf scannedReal scenarios: a 2 TB month that must still be vacuumed and indexed in pieces; per-region then per-month for regulated data.
CREATE TABLE events_2026_12 PARTITION OF events
FOR VALUES FROM ('2026-12-01') TO ('2027-01-01')
PARTITION BY HASH (user_id);
CREATE TABLE events_2026_12_h0 PARTITION OF events_2026_12 FOR VALUES WITH (MODULUS 4, REMAINDER 0);
-- ... h1 to h3Partition pruning: plan time vs execution time Must-know
In plain words: before or while running a query, PostgreSQL crosses out partitions whose bounds prove they cannot contain matching rows.
Common misunderstanding: “Pruning needs an index on the partition key.” It does not: "partition pruning is driven only by the constraints defined implicitly by the partition keys, not by the presence of indexes". The opposite belief is also wrong: “a parameterised query cannot prune.” It can, at executor start.
Definition: three moments. Planning: constants in WHERE remove partitions; they never appear in the plan. Executor initialization: values known when execution starts (parameters of a generic prepared plan, stable functions such as now()); partitions "pruned during this stage will not show up in the query's EXPLAIN or EXPLAIN ANALYZE", and the plan shows Subplans Removed: N. During execution: values from subqueries or the inner side of a nested loop; pruned subplans show as (never executed). Controlled by enable_partition_pruning (default on). Legacy inheritance uses constraint_exclusion, which works from CHECK constraints and "is only applied at plan time".
-- plan time
EXPLAIN SELECT count(*) FROM events WHERE created_at >= '2026-12-05' AND created_at < '2026-12-06';
Aggregate
-> Seq Scan on events_2026_12 events <- only December
-- executor initialization (generic plan of a prepared statement, or now())
EXPLAIN (ANALYZE) EXECUTE day_count('2026-12-05', '2026-12-06');
Aggregate
-> Append
Subplans Removed: 11 <- pruned at startup
-> Seq Scan on events_2026_12 events
-- during execution (nested loop: one probe per outer row)
-> Append (actual loops=3)
-> Seq Scan on events_2026_10 (never executed)Real scenarios: dashboards filtering "last 24 hours" (now() prunes at startup); ORM queries with bound parameters; a join from a small campaigns table into events where each campaign's date range prunes per loop.
| Product | Pruning |
|---|---|
| PostgreSQL declarative | Plan time + executor startup + during execution; enable_partition_pruning |
| PostgreSQL inheritance | Plan time only, from CHECK constraints; constraint_exclusion = partition (default) |
| MySQL InnoDB | Optimizer prunes on the partitioning expression; EXPLAIN shows the partitions column; explicit SELECT ... PARTITION (p1) selection |
| Oracle / SQL Server | Partition elimination by the optimizer, static and dynamic |
Fix / how to use it: always put the partition key in WHERE as a plain comparison against a constant, parameter or stable expression; avoid wrapping the key in a function (date(created_at) = ... cannot prune; created_at >= ... AND created_at < ... can). The pruning demo is in this snippet:
-- Plan-time pruning: the constant is known while planning, so only the
-- matching partition appears in the plan.
EXPLAIN SELECT count(*) FROM events
WHERE created_at >= '2026-12-05' AND created_at < '2026-12-06';
-- Execution-time pruning: the parameter value is unknown at plan time, so
-- partitions are removed when the plan starts running. Look for
-- "Subplans Removed: N" in the output.
PREPARE day_count (timestamptz, timestamptz) AS
SELECT count(*) FROM events WHERE created_at >= $1 AND created_at < $2;
SET plan_cache_mode = force_generic_plan;
EXPLAIN (ANALYZE) EXECUTE day_count('2026-12-05', '2026-12-06');
-- Compare against the planner with pruning switched off (session only).
SET enable_partition_pruning = off;
EXPLAIN SELECT count(*) FROM events WHERE created_at >= '2026-12-05' AND created_at < '2026-12-06';
RESET enable_partition_pruning;Partitionwise join and partitionwise aggregate Good to know
In plain words: if two tables are partitioned the same way, PostgreSQL can join partition 1 with partition 1, 2 with 2, and so on, instead of one huge join; the same for GROUP BY.
Common misunderstanding: “It is on by default and always helps.” Both enable_partitionwise_join and enable_partitionwise_aggregate default to off, because with them "Query planning also becomes significantly more expensive in terms of memory and CPU", and each per-partition node gets its own work_mem.
Definition: a partition-wise join (spelled partitionwise in the GUC names) "currently applies only when the join conditions include all the partition keys, which must be of the same data type and have one-to-one matching sets of child partitions". Partitionwise aggregate runs GROUP BY per partition; "If the GROUP BY clause does not include the partition keys, only partial aggregation can be performed on a per-partition basis, and finalization must be performed later."
orders HASH(customer_id) mod 8 order_lines HASH(customer_id) mod 8
JOIN ON customer_id
off: Hash Join (Append of 8 orders parts) x (Append of 8 order_lines parts)
on : Append of 8 x (Hash Join orders_p_i x order_lines_p_i) <- smaller hash tables, parallel-friendlyReal scenarios: analytics over two large tables hash-partitioned on the same customer key; per-tenant rollups. Turn it on per session for those queries (SET enable_partitionwise_aggregate = on) rather than globally. Citus applies the same idea across servers as co-located joins.
Unique constraints, primary keys and the missing global index Must-know
In plain words: PostgreSQL has no index that spans all partitions, so it can only check uniqueness inside one partition; therefore the partition key must be part of every unique key, so that equal keys always land in the same partition.
Common misunderstanding: “PRIMARY KEY (id, created_at) still guarantees id is unique.” It guarantees the pair is unique. Two rows with the same id and different created_at are allowed. If you need id alone to be unique, generate it so collisions cannot happen (identity, UUIDv7) or enforce it elsewhere (see unique IDs across partitions).
Definition: "To create a unique or primary key constraint on a partitioned table, the partition keys must not include any expressions or function calls and the constraint's columns must include all of the partition key columns", because the per-partition indexes "can only directly enforce uniqueness within their own partitions". Exclusion constraints must also include the key, compared with equality. There is no global (cross-partition) index in PostgreSQL. MySQL has the same rule: "All columns used in the partitioning expression for a partitioned table must be part of every unique key that the table may have." Oracle is the exception: it offers global indexes for exactly this case ("If the index is unique and does not include the partitioning key columns, then use a global index").
ALTER TABLE events ADD PRIMARY KEY (id);
ERROR: unique constraint on partitioned table must include all partitioning columns
DETAIL: PRIMARY KEY constraint on table "events" lacks column "created_at" which is part of the partition key.
MySQL: ERROR 1503 (HY000): A PRIMARY KEY must include all columns in the table's partitioning function (prefixed columns are not considered)Real scenarios: an orders table partitioned by month whose API looks orders up by id only (no pruning, and no uniqueness on id alone); an idempotency-key table you wanted to partition by time (the key must then include the time, which breaks the lookup); ON CONFLICT (id) failing because no unique index on id alone exists.
| Product | Global index on a partitioned table | Unique key rule |
|---|---|---|
| PostgreSQL | No; every index is a set of per-partition indexes | Must include all partition key columns |
| MySQL InnoDB | No | Every unique key (including the PK) must use every column of the partitioning expression |
| Oracle | Yes: global partitioned and global nonpartitioned indexes | Any unique index allowed as a global index |
| SQL Server | Nonaligned indexes allowed (on a different scheme or filegroup) | Unique aligned index must include the partitioning column |
Partitioned indexes Important
In plain words: CREATE INDEX on the parent creates one index per partition (now and in the future) and ties them together as one logical "partitioned index".
Common misunderstanding: “I'll add the index with CREATE INDEX CONCURRENTLY on the parent.” Not possible: the manual lists "it is not possible to use the CONCURRENTLY qualifier" on a partitioned table as a limitation. The workaround is three steps.
Definition: CREATE INDEX ON ONLY parent creates an invalid parent index that is not applied to existing partitions; you then create each partition's index CONCURRENTLY and ALTER INDEX parent_idx ATTACH PARTITION child_idx. "Once indexes for all the partitions are attached to the parent index, the parent index will be marked valid automatically." ATTACH PARTITION reuses a matching index on the incoming table or builds one.
1 CREATE INDEX events_kind_idx ON ONLY events (kind); -- invalid, instant
2 CREATE INDEX CONCURRENTLY events_2026_11_kind_idx ON events_2026_11 (kind); -- no long lock
3 ALTER INDEX events_kind_idx ATTACH PARTITION events_2026_11_kind_idx;
4 ... repeat for each partition ...
5 pg_index.indisvalid for events_kind_idx becomes true after the last attachReal scenarios: adding an index to a 5 TB partitioned table in production; giving the hot current month a different index than archived months (partitions "may have their own indexes"). Full code in indexing without blocking.
Foreign keys to and from partitioned tables Important
In plain words: in declarative partitioning, a partitioned table can reference another table and can be referenced, like a normal table; the referenced side needs a unique key, which must include its partition key.
Common misunderstanding: “Partitioning means giving up foreign keys.” That was true for inheritance ("Indexes and foreign key constraints apply to single tables and not to their inheritance children") and is still true in MySQL ("Partitioned tables using the InnoDB storage engine do not support foreign keys"). It is not true for PostgreSQL declarative partitioning.
Definition: a foreign key from a partitioned table is cloned onto every partition. A foreign key to a partitioned table references its unique constraint, so the referencing table must carry the referenced partition key too: to reference events (id, created_at), event_tags needs both columns. Detaching a partition takes a SHARE lock on tables that reference the parent; detach fails if referencing rows still point into the partition.
order_lines(order_id, order_created_at) REFERENCES orders(id, created_at) -- orders partitioned by created_at
1 DETACH PARTITION orders_2020_01
2 -> checks order_lines for rows referencing orders_2020_01
3 -> fails while such rows exist: retire children first, or partition both tables by the same key and rotate togetherReal scenarios: orders and order_lines both partitioned by created_at and rotated together; a small customers table referenced by a huge partitioned events (FK from partitioned to plain: simple).
ATTACH and DETACH, CONCURRENTLY, and the CHECK trick Must-know
In plain words: you can build a partition offline as a normal table and plug it in, and unplug an old partition to archive or drop it, without rewriting the parent.
Common misunderstanding: “There is ATTACH PARTITION ... CONCURRENTLY.” There is not; only DETACH has CONCURRENTLY. ATTACH is already the low-lock way to add a partition: it takes SHARE UPDATE EXCLUSIVE on the parent, while CREATE TABLE ... PARTITION OF takes ACCESS EXCLUSIVE on it. The cost of ATTACH is a validation scan of the incoming table, which a matching CHECK constraint removes.
Definition: "when running the ATTACH PARTITION command, the table will be scanned to validate the partition constraint while holding an ACCESS EXCLUSIVE lock on that partition. As shown above, it is recommended to avoid this scan by creating a CHECK constraint matching the expected partition constraint on the table prior to attaching it." Afterwards, drop the redundant CHECK. DETACH PARTITION takes ACCESS EXCLUSIVE on the parent; DETACH ... CONCURRENTLY only SHARE UPDATE EXCLUSIVE, runs as two transactions, "cannot be run in a transaction block", and is refused with a DEFAULT partition. If it is interrupted, the partition stays pending detach until DETACH PARTITION ... FINALIZE; "At most one partition in a partitioned table can be pending detach at a time."
loader session app sessions
1 CREATE TABLE events_2027_01 (LIKE events INCLUDING DEFAULTS);
2 ADD CONSTRAINT ... CHECK (created_at >= '2027-01-01' AND created_at < '2027-02-01');
3 COPY events_2027_01 FROM ...; INSERT/SELECT on events continue
4 SET lock_timeout = '5s';
5 ALTER TABLE events ATTACH PARTITION events_2027_01 FOR VALUES FROM (...) TO (...);
-- parent: SHARE UPDATE EXCLUSIVE; reads and writes continue
6 ALTER TABLE events_2027_01 DROP CONSTRAINT ...;
7 ALTER TABLE events DETACH PARTITION events_2026_10 CONCURRENTLY;
-- waits for queries that may still see events_2026_10
8 DROP TABLE events_2026_10; -- instant; no dead tuplesReal scenarios: monthly rotation; bulk loading a backfill offline; swapping in a rebuilt (re-clustered, re-compressed) copy of an old partition; moving a partition to cheaper storage (ALTER TABLE ... SET TABLESPACE on the detached table, then re-attach).
| Operation | Lock on parent | Lock on the partition / table | Notes |
|---|---|---|---|
CREATE TABLE ... PARTITION OF | ACCESS EXCLUSIVE | n/a (new) | Scans DEFAULT if one exists |
ATTACH PARTITION | SHARE UPDATE EXCLUSIVE | ACCESS EXCLUSIVE on the attached table during validation | Skip scan with a matching CHECK |
DETACH PARTITION | ACCESS EXCLUSIVE | ACCESS EXCLUSIVE | Allowed in a transaction |
DETACH PARTITION ... CONCURRENTLY | SHARE UPDATE EXCLUSIVE | No transaction block; no DEFAULT partition; FINALIZE after interruption | |
DROP TABLE partition | ACCESS EXCLUSIVE | ACCESS EXCLUSIVE | Detach concurrently first to avoid blocking the parent |
MySQL ALTER TABLE pt EXCHANGE PARTITION p WITH TABLE nt | (see MySQL docs) | Swaps a partition with a plain table | |
| SQL Server partition switch | (see SQL Server docs) | Moves a partition in or out of an aligned table quickly |
The full SQL is in this snippet (the DETACH targets events, which has no DEFAULT partition):
-- Load and validate a month offline, then attach it.
CREATE TABLE events_2027_01 (LIKE events INCLUDING DEFAULTS INCLUDING INDEXES);
-- A CHECK constraint that matches the partition bound lets ATTACH skip the
-- validation scan, which would otherwise run under ACCESS EXCLUSIVE on this table.
ALTER TABLE events_2027_01 ADD CONSTRAINT events_2027_01_bound
CHECK (created_at >= '2027-01-01' AND created_at < '2027-02-01');
-- ... bulk load events_2027_01 here ...
ALTER TABLE events ATTACH PARTITION events_2027_01
FOR VALUES FROM ('2027-01-01') TO ('2027-02-01');
ALTER TABLE events_2027_01 DROP CONSTRAINT events_2027_01_bound;
-- Retire the oldest month. ATTACH PARTITION has no CONCURRENTLY form;
-- DETACH PARTITION does, and it is refused if the table has a DEFAULT partition.
ALTER TABLE events DETACH PARTITION events_2026_11 CONCURRENTLY;
-- Archive with COPY or pg_dump if needed, then:
DROP TABLE events_2026_11;Tuple routing, row movement and triggers Good to know
In plain words: PostgreSQL decides each row's partition on insert and on key update; your triggers cannot override that.
Common misunderstanding: “A BEFORE INSERT trigger can redirect rows like in the old inheritance setup.” With declarative partitioning, "BEFORE ROW triggers on INSERT cannot change which partition is the final destination for a new row."
Definition: inserts into the parent are routed by key; an UPDATE that changes the key moves the row (internally a delete from one partition and an insert into another, so a concurrent transaction that tries to update the old version gets a serialization-style error). Inserting directly into a partition is allowed if the row satisfies its bound. COPY into the parent routes too.
T1: UPDATE events SET created_at = '2026-12-02' WHERE id = 5 AND created_at = '2026-11-30';
-> row deleted from events_2026_11, inserted into events_2026_12
T2 (concurrently): UPDATE events SET kind = 'x' WHERE id = 5 AND created_at = '2026-11-30';
-> waits for T1, then fails: the tuple was moved to another partition (SQLSTATE 40001) -> retryReal scenarios: "fixing" timestamps after a clock bug moves rows between months; status-based LIST partitions move rows on every status change. If key updates are frequent, the key is wrong.
Inheritance-based partitioning (legacy) Good to know
In plain words: the old way: child tables INHERITS (parent), a trigger routes inserts, CHECK constraints let the planner skip children.
Common misunderstanding: “Inheritance partitioning is obsolete and unsupported.” It is supported and still has uses the manual lists: children "may have extra columns not present in the parent", multiple inheritance, and splitting "in a manner of the user's choosing". But it is slower to plan and does more by hand.
Definition: routing is your trigger; pruning is constraint_exclusion at plan time only; indexes and foreign keys are per table; ON CONFLICT "only taken in case of unique violations on the specified target relation, not its child relations". The manual's scale advice: "the legacy inheritance based partitioning will work well with up to perhaps a hundred child tables; don't try to use many thousands of children."
INSERT INTO measurement ... -> BEFORE INSERT trigger on parent -> INSERT INTO measurement_y2026m12 ...; RETURN NULL
SELECT ... WHERE logdate >= '2026-12-01' -> constraint_exclusion reads CHECKs of all children at plan timeReal scenarios: an old schema you must migrate (attach the children to a new declarative parent one by one); TimescaleDB-style or pg_partman 4.x setups you inherit. New designs: declarative.
Partition count, planning time and memory Important
In plain words: each partition costs planning work and session memory; thousands are fine if queries prune, tens of thousands are not.
Common misunderstanding: “Smaller partitions are always better.” Too many partitions make every query that does not prune plan slowly and hold more locks; too few leave each index large. The manual: "Planning times become longer and memory consumption becomes higher when more partitions remain after the planner performs partition pruning", and "each partition requires its metadata to be loaded into the local memory of each session that touches it".
Definition: practical limits are planning time (EXPLAIN (SUMMARY) shows Planning Time), relcache memory per backend, and the lock table: a query that touches N partitions and their indexes takes N+ locks, which can exhaust max_locks_per_transaction (pg_partman's docs mention raising it "above the default of 64" for very large partition sets).
| Product | Documented ceiling |
|---|---|
| PostgreSQL declarative | "up to a few thousand partitions fairly well" when queries prune |
| PostgreSQL inheritance | "up to perhaps a hundred child tables" |
| MySQL | "The maximum possible number of partitions for a given table not using the NDB storage engine is 8192" |
| SQL Server | "The database engine supports up to 15,000 partitions" |
Real scenarios: daily partitions kept for 10 years (3,650) behind an ORM that never sends the date: every query plans across all of them. Fix: monthly partitions, or always send the date.
Time-based rotation, retention and pg_partman Must-know
In plain words: a scheduled job creates the next partitions before they are needed and removes the oldest ones; pg_partman does this for you.
Common misunderstanding: “I'll create next month's partition when I remember.” The first time you forget, inserts fail with 23514 (or pile into DEFAULT). Always pre-create several intervals ahead and alert on failure.
Definition: rotation = premake (create N future partitions) + retention (detach/drop partitions older than the window). pg_partman manages "both time-based and number-based table partition sets" on top of native partitioning: partman.create_parent(p_parent_table, p_control, p_interval, ...) with p_premake "how many additional partitions to always stay ahead of the current partition. Default value is 4"; p_type supports range and list (not hash); retention is a retention interval in part_config, and by default old children "are only uninherited/detached not actually dropped". run_maintenance() does the work; the background worker (pg_partman_bgw in shared_preload_libraries, interval pg_partman_bgw.interval, default 3600 s) calls it so you need no cron.
day 1 of month M, 02:00 rotate job
1 ensure M, M+1, M+2 exist (create + CHECK + ATTACH, lock_timeout 5s)
2 DETACH events_(M-3) CONCURRENTLY
3 archive (COPY / pg_dump) if required
4 DROP TABLE events_(M-3)
5 alert if step 1 failed: inserts start failing on day 1 of M+1 at the earliest (premake = 2)Real scenarios: 90-day event retention; 13 months of metrics for year-over-year; GDPR deletion by dropping a tenant's LIST partition.
-- pg_partman: monthly partitions, 4 ahead, keep 3 months, drop (not just detach) old ones
CREATE EXTENSION pg_partman SCHEMA partman;
SELECT partman.create_parent(
p_parent_table => 'public.events',
p_control => 'created_at',
p_interval => '1 month',
p_premake => 4);
UPDATE partman.part_config
SET retention = '3 months', retention_keep_table = false
WHERE parent_table = 'public.events';
CALL partman.run_maintenance_proc(); -- or let pg_partman_bgw call run_maintenance() hourlyThe hand-written Go and Laravel rotation jobs are in retention without DELETE.
Sharding, concept by concept
Partitioning vs sharding Must-know
In plain words: partitioning is many drawers in one cabinet; sharding is many cabinets in different buildings.
Common misunderstanding: “We have 64 hash partitions, so we are sharded.” All 64 share one server's CPU, memory, disk and WAL, one primary's write throughput, and one failure domain.
Definition: sharding places disjoint subsets of rows on separate database servers, each with its own storage and (usually) its own replicas. What partitioning gives you for free inside one server (one transaction, one snapshot, foreign keys, unique keys, joins) stops at the shard boundary.
partitioned: app -> PostgreSQL primary [events_2026_10 | events_2026_11 | events_2026_12] one WAL, one CPU pool
sharded: app -> router -> shard0 (primary + replica)
-> shard1 (primary + replica)
-> shard2 (primary + replica) three WALs, three CPU poolsReal scenarios: you partition when the table is big; you shard when the server is full: write throughput above what one primary can take, a working set larger than the biggest machine's RAM, or a regulatory need to keep tenants in different regions.
Shard key choice Must-know
In plain words: the column that decides which server owns a row. Every query that carries it goes to one shard; every query that does not, goes to all.
Common misunderstanding: “Pick the primary key; it's unique, so it spreads well.” It spreads well and is useless for routing if your queries ask "all orders of customer 42": those orders are on every shard. Pick the key your hot queries and your transactions are scoped by.
Definition: good shard keys have high cardinality, even frequency, no monotonic growth (or are hashed), are present in nearly every query, and group the rows that must be transactionally consistent. MongoDB's checklist is the same: "the cardinality of the shard key", "the frequency with which shard key values occur", and "whether a potential shard key grows monotonically". Citus calls it the distribution column; Vitess the primary vindex.
key = order_id : WHERE customer_id = 42 -> all shards (scatter)
key = customer_id: WHERE customer_id = 42 -> one shard
order + order_lines + payments of customer 42 -> one shard, one local transaction
key = created_at : all new writes -> the "latest" shard (range) -> hot shard
key = country : 200 values, 40% 'US' -> one shard holds 40%Real scenarios: SaaS: tenant_id; social: user_id; marketplace: two access paths (by buyer, by seller), which forces either a second copy keyed the other way or a lookup index (Vitess lookup vindex).
| Product | Name for the shard key | Changeable later? |
|---|---|---|
| Citus | Distribution column (create_distributed_table(table, column)) | alter_distributed_table rewrites the table |
| Vitess | Primary vindex → keyspace ID | Via resharding / VReplication workflows |
| MongoDB | Shard key | Can be refined (refineCollectionShardKey adds suffix fields) or resharded |
| Application routing | Whatever your router hashes | Only by migrating data |
Hot shards and skew Important
In plain words: one shard gets far more data or traffic than the others and becomes the bottleneck, while the rest sit idle.
Common misunderstanding: “Hashing the key prevents hot spots.” Hashing spreads distinct keys evenly; it cannot split one key. A single huge tenant or a celebrity user is still one key on one shard.
Definition: Citus: "If you distribute a table on a column skewed to certain common values, then data in the table will tend to accumulate in certain shards." MongoDB on monotonic keys: "If the shard key value is always increasing, all new inserts are routed to the chunk with maxKey as the upper bound", and "The shard containing that chunk becomes the bottleneck for write operations."
tenants: 10,000 small + 1 giant (30% of rows)
hash(tenant_id) % 4 -> shard2 owns the giant -> 3 shards at 25% CPU, shard2 at 95%
fixes: isolate the giant on its own shard (Citus: isolate_tenant_to_new_shard),
or shard the giant by (tenant_id, sub-key), or move it to a dedicated databaseReal scenarios: the biggest customer of a B2B SaaS; a viral account in a social app; time-ordered IDs used as a range shard key.
Cross-shard joins, aggregations and scatter-gather Must-know
In plain words: a query without the shard key must ask every shard and merge the partial answers; a join between rows on different shards must move data over the network.
Common misunderstanding: “Scatter-gather is just N times the same query, so N times the cost.” Worse: its latency is the slowest shard's (tail latency grows with N), one unavailable shard fails or degrades the whole answer, and the shards are read at different moments, so the result is not a consistent snapshot.
Definition: scatter-gather = fan out the query to all shards, then merge (sum counts, merge-sort for ORDER BY ... LIMIT k by taking top k from each shard, re-aggregate averages as sum/count). Cross-shard joins are avoided by co-location (Citus: "rows with the same distribution column value are always on the same machine, even across different tables") or by reference tables copied to every node; otherwise data is repartitioned at query time. Vitess: "In the absence of a Secondary Vindex, VTGate would have to scatter the query to all shards." MongoDB: queries without the shard key "are broadcast to all shards for evaluation".
GET /admin/top-customers?limit=10
1 router sends to shard0, shard1, shard2 in parallel:
SELECT customer_id, sum(total) s FROM orders GROUP BY 1 ORDER BY s DESC LIMIT 10
2 shard0: 120 ms, shard1: 95 ms, shard2: 1.8 s (vacuum running)
3 router waits for all three -> 1.8 s
4 merge 30 rows, sort, take 10 (correct only because a customer lives on one shard)
5 AVG would be wrong if averaged per shard: sum the sums and the counts insteadReal scenarios: admin dashboards; global search; "count all events"; reports. Move them to a read model (a warehouse fed by CDC, see OLTP vs OLAP) when they are frequent.
Resharding and rebalancing Important
In plain words: changing the number of shards or which shard owns which keys, while the system keeps running.
Common misunderstanding: “Going from 3 to 4 shards moves a quarter of the data.” With hash(key) % n it moves most of it: in this page's lab, 7,507 of 10,000 users change shard from 3 to 4. Consistent hashing or a fixed number of virtual shards limits movement to roughly what the new node should own.
Definition: three strategies. Many logical shards, few servers: create far more shards than servers (Citus recommends 32–128 shards for multi-tenant SaaS) and move whole shards; the key-to-shard mapping never changes. Consistent hashing / ranges: keys map to ranges of a hash space, and a new node takes over ranges (Consistent Hashing); Vitess splits key ranges of keyspace IDs, CockroachDB splits ranges automatically when they reach the default range size, Redis Cluster moves some of its 16384 hash slots. Directory (lookup) table: a table maps each tenant to a shard; moving a tenant is copy, switch the directory row, delete. Data copying is done with logical replication so writes continue: Citus's rebalancer "uses PostgreSQL logical replication to move data"; Vitess "copies, verifies, and keeps data up-to-date on new shards while the existing shards continue to serve live read and write traffic".
Citus, add a worker:
1 SELECT citus_add_node('worker-4', 5432); -- new node gets shards of NEW tables only
2 SELECT citus_rebalance_start(); -- moves existing shards, logical replication, writes continue
3 SELECT * FROM citus_rebalance_status();
app routing with a directory:
1 copy tenant 77 from shard1 to shard3 (logical replication or dump/restore + catch-up)
2 brief write freeze for tenant 77; UPDATE tenant_directory SET shard = 3 WHERE tenant_id = 77;
3 delete tenant 77 from shard1Real scenarios: adding capacity before a sales season; moving a noisy tenant away; merging under-used shards to cut cost (Vitess: "Merge shards").
Global unique IDs across shards Important
In plain words: each shard's bigserial / identity counts from 1, so two shards hand out the same IDs.
Common misunderstanding: “IDs are unique because the primary key is unique.” Unique per shard only. The first cross-shard merge, export or cache key collides. In this page's lab the shards use application-generated UUIDs for this reason.
Definition: use IDs that are unique without coordination: UUIDv7 (time-ordered, index-friendly), Snowflake-style IDs (timestamp + node + sequence), or per-shard sequences with disjoint ranges or strides (INCREMENT BY 3 START 1/2/3). Vitess provides sequences backed by an unsharded table. The trade-offs are on ID Generation at Scale.
shard0: INSERT ... RETURNING id -> 1001
shard1: INSERT ... RETURNING id -> 1001 <- same id, different rows
fix: id = uuidv7() (or Snowflake) generated in the app or by the databaseMulti-tenant sharding Important
In plain words: put all of one customer's rows on one shard, keyed by tenant_id, so every request is a single-shard request.
Common misunderstanding: “Multi-tenant sharding means a database per tenant.” That is one model; row-based sharding with tenant_id in every table and every primary key scales to far more tenants. Citus also offers schema-based sharding (one schema per tenant, "Fewer tenants per node compared to row-based sharding").
Definition: add tenant_id to every table and to every primary and foreign key, distribute all tenant tables by it (so they are co-located), make global data reference tables, and route per request by tenant. Isolation models and their security trade-offs are on Multi-Tenancy Strategies.
request for tenant 77 -> resolver: tenant 77 -> shard1
all queries carry tenant_id = 77 -> single shard, local joins, local transactions, local FKs
cross-tenant analytics -> warehouse, not the shardsRouting options: application, Citus, postgres_fdw Must-know
In plain words: something must translate "tenant 77" into "that server". It can be your code, a coordinator node, or the planner of a "head" PostgreSQL with foreign tables.
Common misunderstanding: “postgres_fdw gives me a distributed database.” It gives you remote tables. Writes across two servers in one transaction are not atomic: "it is currently not supported by postgres_fdw to prepare the remote transaction for two-phase commit".
Definition:
| Route | How a query finds its shard | Transactions across shards | Strength | Weakness |
|---|---|---|---|---|
| Application-level routing | hash(key) % n, consistent hash, or directory table in your code; one pool per shard | None (or sagas) | Simple, no new infrastructure, shards fully independent | Every query path must know the key; cross-shard work is yours; resharding is yours |
| Citus | Coordinator consults metadata, routes to one worker or parallelises; workers hold shards | Yes (2PC across workers; reference tables use 2PC automatically) | Distributed SQL, co-located joins, reference tables, online rebalancer | Another component; some SQL restrictions across non-co-located tables |
postgres_fdw + partitioned parent | Local planner prunes partitions; foreign partitions push WHERE to remote servers | Not atomic (no 2PC) | Pure PostgreSQL, good for archives and read-mostly fan-out | One connection per server by default runs sequentially unless async_capable; no unique index on the parent |
| Vitess (MySQL) | VTGate computes keyspace ID from the vindex | Configurable (best effort or 2PC) | Online resharding, lookup vindexes | MySQL only, large operational surface |
-- Citus (on the coordinator)
CREATE EXTENSION citus;
SELECT create_distributed_table('events', 'user_id');
SELECT create_distributed_table('orders', 'user_id', colocate_with => 'events');
SELECT create_reference_table('countries');
-- postgres_fdw: one parent spanning servers; enable parallel remote scans
ALTER SERVER shard1 OPTIONS (ADD async_capable 'true');The full Citus and postgres_fdw setup:
-- Route 1: Citus. Run on the coordinator.
CREATE EXTENSION citus;
-- Hash-distribute by the column most queries filter and join on.
SELECT create_distributed_table('events', 'user_id');
-- A table that is joined on the same key is co-located with it, so the join
-- runs inside each worker with no data crossing the network.
SELECT create_distributed_table('orders', 'user_id', colocate_with => 'events');
-- A small lookup table is copied to every node, so it joins with anything.
SELECT create_reference_table('countries');
-- Route 2: postgres_fdw. Each remote database is a foreign server.
CREATE EXTENSION postgres_fdw;
CREATE SERVER shard1 FOREIGN DATA WRAPPER postgres_fdw
OPTIONS (host 'shard1.internal', dbname 'app');
CREATE USER MAPPING FOR CURRENT_USER SERVER shard1
OPTIONS (user 'app', password 'secret');
-- A foreign table can be a partition, so one parent spans several servers.
-- The parent has no PRIMARY KEY: a foreign table cannot be attached as a
-- partition when the parent has UNIQUE indexes.
CREATE TABLE audit_log (
user_id bigint NOT NULL,
action text NOT NULL
) PARTITION BY HASH (user_id);
CREATE TABLE audit_log_p0 PARTITION OF audit_log
FOR VALUES WITH (MODULUS 2, REMAINDER 0);
CREATE FOREIGN TABLE audit_log_p1 PARTITION OF audit_log
FOR VALUES WITH (MODULUS 2, REMAINDER 1)
SERVER shard1 OPTIONS (table_name 'audit_log');What each product really does
Partitioning across engines
| Feature | PostgreSQL | MySQL InnoDB | Oracle | SQL Server |
|---|---|---|---|---|
| Methods | RANGE, LIST, HASH (+ DEFAULT, sub-partitioning) | RANGE, LIST, HASH, KEY, [LINEAR] variants, RANGE/LIST COLUMNS, subpartitioning | Range, list, hash, interval, reference, composite | Range only (partition function + scheme) |
| Declared as | Separate CREATE TABLE ... PARTITION OF per partition | Inside CREATE TABLE ... PARTITION BY ... (PARTITION p0 VALUES ...) | Inside CREATE TABLE | CREATE PARTITION FUNCTION, CREATE PARTITION SCHEME, table ON scheme(col) |
| Max partitions | Planner handles "a few thousand" well | 8192 (non-NDB) | Very large | 15,000 |
| Unique keys | Must include the partition key | Must include every column of the partitioning expression | Global index allowed | Aligned unique index must include the column |
| Global index | No | No | Yes | Nonaligned index |
| Foreign keys | Supported to and from partitioned tables | Not supported on partitioned tables | Supported (reference partitioning) | Supported |
| Pruning | Plan + execution time | Optimizer pruning; EXPLAIN partitions column | Static and dynamic elimination | Static and dynamic elimination |
| Swap in/out | ATTACH / DETACH [CONCURRENTLY] | EXCHANGE PARTITION ... WITH TABLE, DROP PARTITION, REORGANIZE PARTITION | EXCHANGE PARTITION, TRUNCATE PARTITION | switch partitions in or out (aligned tables) |
| Other limits | No CREATE INDEX CONCURRENTLY on the parent | No FULLTEXT indexes ("Partitioned tables do not support FULLTEXT indexes or searches") | Partition function/scheme scoped to one database |
MySQL in one paragraph. MySQL's "partitioning function" can be "the modulus, simple matching against a set of ranges or value lists, an internal hashing function, or a linear hashing function". KEY partitioning is HASH with a server-supplied hash ("NDB Cluster uses MD5() for this purpose; for tables using other storage engines, the server employs its own internal hashing function"); LINEAR HASH/LINEAR KEY use powers-of-two arithmetic so adding partitions moves less data at the cost of a less even spread. The rule that surprises people: "every unique key on the table must use every column in the table's partitioning expression", and foreign keys are not supported ("No definition of an InnoDB table employing user-defined partitioning may contain foreign key references"). SQLite has no table partitioning; the closest tool is splitting data across database files with ATTACH DATABASE.
-- MySQL 8.4: monthly RANGE COLUMNS, retention by DROP PARTITION
CREATE TABLE events (
id bigint NOT NULL AUTO_INCREMENT,
user_id bigint NOT NULL,
created_at datetime NOT NULL,
PRIMARY KEY (id, created_at) -- error 1503 without created_at
) PARTITION BY RANGE COLUMNS (created_at) (
PARTITION p2026_11 VALUES LESS THAN ('2026-12-01'),
PARTITION p2026_12 VALUES LESS THAN ('2027-01-01'),
PARTITION pmax VALUES LESS THAN (MAXVALUE)
);
ALTER TABLE events REORGANIZE PARTITION pmax INTO (
PARTITION p2027_01 VALUES LESS THAN ('2027-02-01'),
PARTITION pmax VALUES LESS THAN (MAXVALUE));
ALTER TABLE events DROP PARTITION p2026_11; -- retention
EXPLAIN SELECT * FROM events WHERE created_at >= '2026-12-05'; -- partitions: p2026_12,p2027_01,pmaxSharding across products
| Product | Unit of distribution | Router | Shard key name | Rebalancing | Cross-shard queries |
|---|---|---|---|---|---|
| Citus (PostgreSQL extension) | Shards (PostgreSQL tables on workers), citus.shard_count per table | Coordinator | Distribution column | citus_rebalance_start(), online via logical replication | Distributed planner; co-located joins local; reference tables everywhere |
postgres_fdw | Foreign tables, optionally as partitions | Local planner | Partition key of the parent | Manual | Pushes down WHERE; no 2PC |
| Application routing | Whole databases | Your code | Whatever you hash | Manual | Your code merges |
| Vitess (MySQL) | Shards = key ranges of keyspace IDs | VTGate | Primary vindex | Online resharding (copy, verify, switch traffic) | Scatter when no vindex; lookup vindexes as "cross-shard indexes" |
| MongoDB | Chunks (ranges of shard key values) | mongos | Shard key (ranged or hashed) | Balancer moves chunks | Targeted with the key, broadcast without it |
| CockroachDB | Ranges of the sorted key space | Any node (gateway) | Primary key order | Automatic split/merge/rebalance | Distributed SQL, serializable transactions |
| Redis Cluster | 16384 hash slots | Client (redirects MOVED/ASK) | Key, or {hash tag} | Move slots between masters | Multi-key operations only within one slot |
Vitess in one paragraph. A keyspace is a logical database; "If sharded, the rows of the keyspace are partitioned into different databases of identical schema." Each row gets a keyspace ID computed by the table's primary vindex; each shard owns a contiguous key range (-80, 80-). Vitess supports "Horizontal sharding: Splitting or merging shards" and "Vertical sharding: Moving tables from an unsharded keyspace to a different keyspace". A lookup vindex "is implemented as a MySQL lookup table that maps a column value to keyspace IDs", which is how a second access path avoids scatter.
MongoDB in one paragraph. A sharded collection is split into chunks by shard key; "the mongos routes queries to only the shards that contain the relevant data if the queries contain the shard key"; otherwise they are broadcast. Low cardinality caps the number of chunks ("A cardinality of 7 means there can be no more than 7 chunks"); monotonically increasing keys send all inserts to one chunk, so "consider using Hashed Sharding".
Mechanics
How a row reaches its partition, and how a query avoids the others Important
On INSERT or COPY into the parent, the executor computes the key of each row, finds the partition by binary search over the sorted bounds (RANGE, LIST) or by modulus (HASH), and inserts into that partition's heap and indexes; with sub-partitioning it repeats per level. For reads, the planner builds an Append (or MergeAppend for ordered output) over the surviving partitions; pruning removes children from that list at the three moments shown in the pruning diagram. Each partition is planned separately, so different partitions can use different scan types (sequential scan on a small old month, index scan on the big current one).
INSERT INTO events VALUES (..., '2026-12-05')
ExecFindPartition: bounds [.., 2026-11-01, 2026-12-01, 2027-01-01, ..] -> binary search -> events_2026_12
SELECT ... WHERE created_at >= $1
plan: Append [events_2026_10, events_2026_11, events_2026_12] -> at executor start $1 = 2026-12-01 -> keep 1, Subplans Removed: 2Locks taken by partition DDL Must-know
ACCESS EXCLUSIVE on the parent blocks every query on the whole table and queues behind any running query; while it waits, every later query queues behind it. That is why partition maintenance uses the operations that take SHARE UPDATE EXCLUSIVE and sets lock_timeout. Lock modes themselves are explained on Locks & Concurrency.
| Statement | Parent | Partition / other | Blocks normal reads/writes on the parent? |
|---|---|---|---|
CREATE TABLE p PARTITION OF parent | ACCESS EXCLUSIVE | DEFAULT partition scanned | Yes, briefly (longer if DEFAULT is large) |
ALTER TABLE parent ATTACH PARTITION p | SHARE UPDATE EXCLUSIVE | ACCESS EXCLUSIVE on p while validating | No |
ALTER TABLE parent DETACH PARTITION p | ACCESS EXCLUSIVE | Yes | |
ALTER TABLE parent DETACH PARTITION p CONCURRENTLY | SHARE UPDATE EXCLUSIVE (both transactions) | SHARE UPDATE EXCLUSIVE on p, then ACCESS EXCLUSIVE on p in the second transaction; SHARE on tables referencing the parent | No |
DROP TABLE p (attached partition) | ACCESS EXCLUSIVE | Yes | |
CREATE INDEX ON parent | SHARE | SHARE on every partition | Blocks writes for the whole build |
CREATE INDEX ON ONLY parent + per-partition CONCURRENTLY + ALTER INDEX ... ATTACH PARTITION | Brief | SHARE UPDATE EXCLUSIVE per partition | No |
ALTER TABLE p ADD CONSTRAINT ... CHECK ... NOT VALID then VALIDATE CONSTRAINT | n/a | ACCESS EXCLUSIVE briefly, then SHARE UPDATE EXCLUSIVE while validating | No long block |
DETACH CONCURRENTLY, step by step Good to know
DETACH ... CONCURRENTLY runs in two transactions. In the first, "a SHARE UPDATE EXCLUSIVE lock is taken on both parent table and partition, and the partition is marked as undergoing detach"; it commits and then waits for all other transactions using the partitioned table; the second transaction takes SHARE UPDATE EXCLUSIVE on the parent and ACCESS EXCLUSIVE on the partition and completes the detach. If the session is cancelled between the two, the partition remains pending detach (pg_inherits.inhdetachpending = true): queries no longer see it, and ALTER TABLE ... DETACH PARTITION ... FINALIZE completes the job.
rotate job long report (started earlier)
1 SELECT ... FROM events WHERE ... (running)
2 DETACH PARTITION events_2026_09 CONCURRENTLY
txn 1: mark detach pending; COMMIT
3 wait for snapshots that can still see the partition <- waits for the report
4 report finishes
5 txn 2: remove partition from parent; COMMIT
-- if step 3 is cancelled: partition stays pending; run DETACH PARTITION events_2026_09 FINALIZEEvery knob Must-know
| Knob | Where | Default | What it does |
|---|---|---|---|
enable_partition_pruning | PostgreSQL | on | Plan- and execution-time pruning of declarative partitions |
enable_partitionwise_join | PostgreSQL | off | Join matching partitions pairwise |
enable_partitionwise_aggregate | PostgreSQL | off | Aggregate per partition (partial if GROUP BY lacks the key) |
constraint_exclusion | PostgreSQL | partition | CHECK-based exclusion for inheritance children, plan time only |
plan_cache_mode | PostgreSQL | auto | force_generic_plan shows execution-time pruning in EXPLAIN EXECUTE |
max_locks_per_transaction | PostgreSQL | 64 | Lock table size; raise for queries touching many partitions |
lock_timeout | PostgreSQL | 0 (off) | Make partition DDL give up instead of queueing everyone behind it |
citus.shard_count | Citus | (see docs) | Shards per newly distributed table |
citus.max_background_task_executors_per_node | Citus | Parallel shard moves during rebalance | |
async_capable | postgres_fdw server/table | false | Scan foreign partitions concurrently |
fetch_size, batch_size | postgres_fdw | 100 / 1 | Rows per remote fetch; rows per remote insert |
use_remote_estimate | postgres_fdw | false | Ask the remote server for row estimates |
p_premake, retention, pg_partman_bgw.interval | pg_partman | 4, none, 3600 s | Future partitions, retention window, maintenance interval |
refineCollectionShardKey | MongoDB | Add suffix fields to an existing shard key |
Error messages you will meet Must-know
| Product | Message / code | Cause | Fix |
|---|---|---|---|
| PostgreSQL | no partition of relation "events" found for row (23514) | No bound matches and no DEFAULT | Pre-create partitions (premake), alert on rotation failure |
| PostgreSQL | unique constraint on partitioned table must include all partitioning columns | PK/UNIQUE without the key | Add the key, or enforce uniqueness elsewhere |
| PostgreSQL | partition "x" would overlap partition "y" (42P17) | Bounds overlap | Fix bounds; check with pg_get_expr(relpartbound, oid) |
| PostgreSQL | partition constraint of relation "x" is violated by some row (23514) | ATTACH found rows outside the bound | Clean the table, or the CHECK you added was wrong |
| PostgreSQL | updated partition constraint for default partition "d" would be violated by some row | DEFAULT holds rows of the new range | Move them out of DEFAULT first |
| PostgreSQL | cannot detach partitions concurrently when a default partition exists | DETACH ... CONCURRENTLY with DEFAULT | Plain DETACH in a quiet window, or drop the DEFAULT |
| PostgreSQL | ALTER TABLE ... DETACH CONCURRENTLY cannot run inside a transaction block (25001) | Wrapped in BEGIN / DB::transaction | Run it alone, in autocommit |
| PostgreSQL | canceling statement due to lock timeout (55P03) | DDL could not get its lock within lock_timeout | Retry later; find the blocker in pg_stat_activity |
| PostgreSQL | tuple to be locked was already moved to another partition due to concurrent update (40001) | Row moved by a key update | Retry the transaction |
| MySQL | 1503 (ER_UNIQUE_KEY_NEED_ALL_FIELDS_IN_PF) A PRIMARY KEY must include all columns in the table's partitioning function | Unique key rule | Add the column |
| MySQL | 1526 (ER_NO_PARTITION_FOR_GIVEN_VALUE) Table has no partition for value ... | No partition (no MAXVALUE) | Keep a MAXVALUE partition and reorganise it |
| MySQL | 1506 (ER_FOREIGN_KEY_ON_PARTITIONED) Foreign keys are not yet supported in conjunction with partitioning | FK on a partitioned InnoDB table | Enforce in the application |
| Redis Cluster | Multi-key command rejected | Keys hash to different slots; multi-key operations need one slot | Use {hash tags} |
Solving the classic problems
The Go code uses database/sql with the pgx stdlib driver and PostgreSQL placeholders; the Laravel code targets Laravel 13 on PostgreSQL.
Retention without DELETE
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
Bulk DELETE (the before) | DELETE ... WHERE created_at < now() - '90 days' | No schema change | WAL and dead tuples for every row, VACUUM debt, long row locks, bloat |
Batched DELETE | Delete 10k rows per transaction in a loop | Shorter locks | Same total WAL and VACUUM work |
| Partition rotation | Pre-create + DETACH CONCURRENTLY + DROP TABLE | Near-instant, no dead tuples | Requires partitioning by the retention column |
| pg_partman retention | retention in part_config + run_maintenance() | No custom code; background worker | Another extension to operate |
Before. One giant table and a nightly bulk DELETE:
// Package before keeps every event in one giant table and trims it with a
// nightly bulk DELETE.
package before
import (
"context"
"database/sql"
"fmt"
"time"
)
// PurgeOldEvents deletes rows older than 90 days. On a table with billions of
// rows this touches every old tuple: it writes WAL for each one, leaves dead
// tuples behind for VACUUM, and holds row locks while it runs.
func PurgeOldEvents(ctx context.Context, db *sql.DB) (int64, error) {
res, err := db.ExecContext(ctx,
`DELETE FROM events WHERE created_at < now() - interval '90 days'`)
if err != nil {
return 0, fmt.Errorf("purge events: %w", err)
}
return res.RowsAffected()
}
// RunNightly calls PurgeOldEvents once per day until ctx is cancelled.
func RunNightly(ctx context.Context, db *sql.DB) error {
t := time.NewTicker(24 * time.Hour)
defer t.Stop()
for {
select {
case <-ctx.Done():
return ctx.Err()
case <-t.C:
if _, err := PurgeOldEvents(ctx, db); err != nil {
return err
}
}
}
}<?php
// app/Models/Event.php and a controller, before partitioning.
// One connection, one monolithic table, one nightly bulk DELETE.
namespace App\Models;
use Illuminate\Console\Command;
use Illuminate\Database\Eloquent\Model;
final class Event extends Model
{
// The events table has created_at but no updated_at column.
public const UPDATED_AT = null;
protected $guarded = [];
}
final class PurgeOldEvents extends Command
{
protected $signature = 'events:purge';
public function handle(): int
{
// Touches every old row: WAL for each tuple, dead tuples for VACUUM,
// and long row locks on a table that is still taking writes.
$deleted = Event::where('created_at', '<', now()->subDays(90))->delete();
$this->info("Deleted {$deleted} rows.");
return self::SUCCESS;
}
}After. The partitioned schema (RANGE, LIST and HASH examples) and the Laravel migration that creates it (the schema builder has no PARTITION BY, so it uses DB::statement):
-- RANGE partitioning by month. The primary key must contain the partition key.
CREATE TABLE events (
id bigint GENERATED ALWAYS AS IDENTITY,
user_id bigint NOT NULL,
kind text NOT NULL,
payload jsonb,
created_at timestamptz NOT NULL,
PRIMARY KEY (id, created_at)
) PARTITION BY RANGE (created_at);
-- Created on the parent, so every current and future partition gets one.
CREATE INDEX events_user_created_idx ON events (user_id, created_at);
-- Upper bounds are exclusive, so adjacent partitions share a boundary value.
CREATE TABLE events_2026_11 PARTITION OF events
FOR VALUES FROM ('2026-11-01') TO ('2026-12-01');
CREATE TABLE events_2026_12 PARTITION OF events
FOR VALUES FROM ('2026-12-01') TO ('2027-01-01');
-- LIST: one partition per explicit set of values.
CREATE TABLE cities (
id bigint NOT NULL,
country text NOT NULL,
PRIMARY KEY (id, country)
) PARTITION BY LIST (country);
CREATE TABLE cities_eu PARTITION OF cities FOR VALUES IN ('de', 'fr', 'nl');
CREATE TABLE cities_other PARTITION OF cities DEFAULT;
-- HASH: a fixed number of buckets, useful when no natural range exists.
CREATE TABLE sessions (
user_id bigint NOT NULL,
token text NOT NULL,
PRIMARY KEY (user_id, token)
) PARTITION BY HASH (user_id);
CREATE TABLE sessions_p0 PARTITION OF sessions FOR VALUES WITH (MODULUS 4, REMAINDER 0);
CREATE TABLE sessions_p1 PARTITION OF sessions FOR VALUES WITH (MODULUS 4, REMAINDER 1);
CREATE TABLE sessions_p2 PARTITION OF sessions FOR VALUES WITH (MODULUS 4, REMAINDER 2);
CREATE TABLE sessions_p3 PARTITION OF sessions FOR VALUES WITH (MODULUS 4, REMAINDER 3);<?php
// database/migrations/2026_11_25_000000_create_partitioned_events_table.php
//
// Laravel's schema builder cannot express PARTITION BY or PARTITION OF, so the
// parent table and its partitions are created with raw statements.
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
return new class extends Migration
{
public function up(): void
{
// The primary key must include the partition key (created_at).
DB::statement(<<<'SQL'
CREATE TABLE events (
id bigint GENERATED ALWAYS AS IDENTITY,
user_id bigint NOT NULL,
kind text NOT NULL,
payload jsonb,
created_at timestamptz NOT NULL,
PRIMARY KEY (id, created_at)
) PARTITION BY RANGE (created_at)
SQL);
// Created on the parent, so every partition inherits it.
DB::statement('CREATE INDEX events_user_created_idx ON events (user_id, created_at)');
DB::statement(<<<'SQL'
CREATE TABLE events_2026_12 PARTITION OF events
FOR VALUES FROM ('2026-12-01') TO ('2027-01-01')
SQL);
}
public function down(): void
{
DB::statement('DROP TABLE IF EXISTS events CASCADE');
}
};The Go rotation job creates future months as plain tables, proves their bound with a CHECK, attaches them under lock_timeout on one dedicated connection, and retires the oldest month with DETACH ... CONCURRENTLY (no transaction block):
// Command rotate pre-creates the coming months of the events table and
// retires the oldest one. Run it from cron or a Kubernetes CronJob, not from
// the request path.
//
// New months are created as plain tables and then attached, because
// CREATE TABLE ... PARTITION OF takes ACCESS EXCLUSIVE on the parent while
// ATTACH PARTITION takes only SHARE UPDATE EXCLUSIVE on it.
package main
import (
"context"
"database/sql"
"fmt"
"log"
"os"
"time"
_ "github.com/jackc/pgx/v5/stdlib"
)
const (
retentionMonths = 3
premakeMonths = 2
)
// partitionName and the bounds below are built from time.Time values only,
// never from user input, because SQL identifiers cannot be bind parameters.
func partitionName(month time.Time) string {
return "events_" + month.Format("2006_01")
}
func firstOfMonth(t time.Time) time.Time {
return time.Date(t.Year(), t.Month(), 1, 0, 0, 0, 0, time.UTC)
}
func isAttached(ctx context.Context, conn *sql.Conn, name string) (bool, error) {
var ok bool
err := conn.QueryRowContext(ctx, `
SELECT EXISTS (
SELECT 1 FROM pg_inherits
WHERE inhparent = 'events'::regclass AND inhrelid = to_regclass($1))`,
name).Scan(&ok)
return ok, err
}
// ensurePartition creates and attaches the partition for the month starting
// at start. The CHECK constraint matches the bound, so ATTACH skips the
// validation scan; it is dropped afterwards because it is now redundant.
func ensurePartition(ctx context.Context, conn *sql.Conn, start time.Time) error {
name := partitionName(start)
attached, err := isAttached(ctx, conn, name)
if err != nil || attached {
return err
}
from := start.Format("2006-01-02")
to := start.AddDate(0, 1, 0).Format("2006-01-02")
stmts := []string{
fmt.Sprintf(`CREATE TABLE IF NOT EXISTS %s (LIKE events INCLUDING DEFAULTS)`, name),
// A previous run may have stopped after ADD CONSTRAINT (for example on
// lock_timeout); drop the leftover so this run can start over.
fmt.Sprintf(`ALTER TABLE %s DROP CONSTRAINT IF EXISTS %s_bound`, name, name),
fmt.Sprintf(`ALTER TABLE %s ADD CONSTRAINT %s_bound
CHECK (created_at >= '%s' AND created_at < '%s')`, name, name, from, to),
// Fail fast instead of queueing behind a long query and blocking
// every later query on events while waiting for the lock.
`SET lock_timeout = '5s'`,
fmt.Sprintf(`ALTER TABLE events ATTACH PARTITION %s FOR VALUES FROM ('%s') TO ('%s')`,
name, from, to),
`RESET lock_timeout`,
fmt.Sprintf(`ALTER TABLE %s DROP CONSTRAINT %s_bound`, name, name),
}
for _, s := range stmts {
if _, err := conn.ExecContext(ctx, s); err != nil {
return fmt.Errorf("%s: %w", name, err)
}
}
return nil
}
// retire detaches and drops the partition for the given month. DETACH ...
// CONCURRENTLY cannot run inside a transaction block, so each statement is
// sent on its own, and it is refused when the table has a DEFAULT partition.
func retire(ctx context.Context, conn *sql.Conn, month time.Time) error {
name := partitionName(month)
attached, err := isAttached(ctx, conn, name)
if err != nil || !attached {
return err
}
if _, err := conn.ExecContext(ctx,
fmt.Sprintf(`ALTER TABLE events DETACH PARTITION %s CONCURRENTLY`, name)); err != nil {
// If this was interrupted, finish it later with
// ALTER TABLE events DETACH PARTITION <name> FINALIZE.
return fmt.Errorf("detach %s: %w", name, err)
}
// Archive the detached table here (COPY, pg_dump) if you must keep it.
if _, err := conn.ExecContext(ctx, fmt.Sprintf(`DROP TABLE IF EXISTS %s`, name)); err != nil {
return fmt.Errorf("drop %s: %w", name, err)
}
return nil
}
func main() {
dsn := os.Getenv("DATABASE_URL")
if dsn == "" {
log.Fatal("DATABASE_URL is not set")
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
defer cancel()
db, err := sql.Open("pgx", dsn)
if err != nil {
log.Fatal(err)
}
defer db.Close()
// One dedicated connection, so SET lock_timeout applies to the ATTACH
// that follows it rather than to a random pooled connection.
conn, err := db.Conn(ctx)
if err != nil {
log.Fatal(err)
}
defer conn.Close()
this := firstOfMonth(time.Now().UTC())
// Stay premakeMonths ahead so a skipped run never leaves inserts without
// a partition (they would fail with SQLSTATE 23514).
for i := 0; i <= premakeMonths; i++ {
if err := ensurePartition(ctx, conn, this.AddDate(0, i, 0)); err != nil {
log.Fatal(err)
}
}
if err := retire(ctx, conn, this.AddDate(0, -retentionMonths, 0)); err != nil {
log.Fatal(err)
}
}The Laravel equivalent is a scheduled Artisan command; it must not run inside DB::transaction, and onOneServer() keeps two app servers from rotating at once:
<?php
// app/Console/Commands/RotateEventPartitions.php
// Schedule it in routes/console.php:
//
// use Illuminate\Support\Facades\Schedule;
// Schedule::command('events:rotate-partitions')->dailyAt('02:00')->onOneServer();
namespace App\Console\Commands;
use Carbon\CarbonImmutable;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
final class RotateEventPartitions extends Command
{
protected $signature = 'events:rotate-partitions
{--retention=3 : Months to keep}
{--premake=2 : Months to create ahead}';
protected $description = 'Attach upcoming events partitions and drop the oldest one';
public function handle(): int
{
$thisMonth = CarbonImmutable::now('UTC')->startOfMonth();
// Stay ahead, so a skipped run never leaves inserts without a partition
// (they would fail with SQLSTATE 23514 "no partition of relation").
for ($offset = 0; $offset <= (int) $this->option('premake'); $offset++) {
$this->ensurePartition($thisMonth->addMonthsNoOverflow($offset));
}
$oldest = $this->partitionName($thisMonth->subMonthsNoOverflow((int) $this->option('retention')));
if (! $this->isAttached($oldest)) {
$this->info("No partition {$oldest} to drop.");
return self::SUCCESS;
}
// DETACH ... CONCURRENTLY cannot run inside a transaction block, so do
// not wrap this command in DB::transaction(). If it is interrupted, run
// ALTER TABLE events DETACH PARTITION <name> FINALIZE.
DB::statement("ALTER TABLE events DETACH PARTITION {$oldest} CONCURRENTLY");
DB::statement("DROP TABLE IF EXISTS {$oldest}");
$this->info("Dropped {$oldest}.");
return self::SUCCESS;
}
// Create a plain table, prove its bound with CHECK, then ATTACH: the parent
// gets SHARE UPDATE EXCLUSIVE instead of the ACCESS EXCLUSIVE that
// CREATE TABLE ... PARTITION OF would take, and the CHECK skips the scan.
private function ensurePartition(CarbonImmutable $start): void
{
$name = $this->partitionName($start);
if ($this->isAttached($name)) {
return;
}
// Names and bounds come from Carbon, never from user input,
// because identifiers cannot be bound as parameters.
$from = $start->toDateString();
$to = $start->addMonthNoOverflow()->toDateString();
DB::statement("CREATE TABLE IF NOT EXISTS {$name} (LIKE events INCLUDING DEFAULTS)");
// A previous run may have stopped after ADD CONSTRAINT (lock timeout);
// drop the leftover so this run can start over.
DB::statement("ALTER TABLE {$name} DROP CONSTRAINT IF EXISTS {$name}_bound");
DB::statement("ALTER TABLE {$name} ADD CONSTRAINT {$name}_bound
CHECK (created_at >= '{$from}' AND created_at < '{$to}')");
DB::statement("SET lock_timeout = '5s'");
DB::statement("ALTER TABLE events ATTACH PARTITION {$name} FOR VALUES FROM ('{$from}') TO ('{$to}')");
DB::statement('RESET lock_timeout');
DB::statement("ALTER TABLE {$name} DROP CONSTRAINT {$name}_bound");
$this->info("Attached {$name}.");
}
private function isAttached(string $name): bool
{
return (bool) DB::scalar(
"select exists (select 1 from pg_inherits
where inhparent = 'events'::regclass and inhrelid = to_regclass(?))",
[$name],
);
}
private function partitionName(CarbonImmutable $month): string
{
return 'events_'.$month->format('Y_m');
}
}Partitioning a live table that already has data
The documented building blocks: a regular table cannot be converted, but "it is possible to add an existing regular or partitioned table as a partition". So the old table becomes the "history" partition and new months are normal partitions.
-- 1. Prove the bound without blocking writes for the scan
ALTER TABLE events ADD CONSTRAINT events_hist_bound
CHECK (created_at < '2026-12-01') NOT VALID; -- brief lock, no scan
ALTER TABLE events VALIDATE CONSTRAINT events_hist_bound; -- scans under SHARE UPDATE EXCLUSIVE
-- 2. The partition's unique key must include created_at too
CREATE UNIQUE INDEX CONCURRENTLY events_id_created ON events (id, created_at);
-- 3. One short transaction: swap names, create parent, attach history
BEGIN;
SET LOCAL lock_timeout = '5s';
ALTER TABLE events RENAME TO events_hist;
ALTER TABLE events_hist DROP CONSTRAINT events_pkey,
ADD CONSTRAINT events_hist_pkey PRIMARY KEY USING INDEX events_id_created;
CREATE TABLE events (LIKE events_hist INCLUDING DEFAULTS) PARTITION BY RANGE (created_at);
ALTER TABLE events ADD PRIMARY KEY (id, created_at);
ALTER TABLE events ATTACH PARTITION events_hist FOR VALUES FROM (MINVALUE) TO ('2026-12-01'); -- no scan: CHECK proves it
CREATE TABLE events_2026_12 PARTITION OF events FOR VALUES FROM ('2026-12-01') TO ('2027-01-01');
COMMIT;
ALTER TABLE events_hist DROP CONSTRAINT events_hist_bound;
-- 4. Later: move history into monthly partitions in batches, or keep it until it ages out.Two caveats. The CHECK bound must lie in the future when you add it (here a few days ahead), because it rejects every write above it until the switch in step 3. And columns must match exactly: the recipe assumes id is a bigserial-style sequence default, which LIKE ... INCLUDING DEFAULTS copies to the parent; if id is an identity column, check your version's rules first, because recent PostgreSQL versions refuse to attach a table that has its own identity column. Rehearse on a restored copy; Zero-Downtime Schema Migrations covers the general pattern.
Unique IDs across partitions (and shards)
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Composite key | PRIMARY KEY (id, created_at) with id from one identity/sequence | Built in; ids unique in practice because one sequence feeds all partitions | Database does not enforce uniqueness of id alone |
| Uniqueness side table | Non-partitioned event_ids (id PRIMARY KEY) written in the same transaction | Enforced uniqueness on id | Extra write and index; a hot table |
| Coordination-free IDs | UUIDv7 or Snowflake generated in the app | Unique across partitions and shards; no sequence | 16 bytes (UUID); clock assumptions (ID Generation) |
| Lookup by id | Encode the time in the id (UUIDv7, Snowflake) so WHERE id = $1 can be turned into a time range | Lookups by id prune again | Application must derive the range |
CREATE TABLE event_ids (id bigint PRIMARY KEY); -- not partitioned
BEGIN;
INSERT INTO event_ids VALUES (9001); -- 23505 if 9001 exists anywhere
INSERT INTO events (id, user_id, kind, created_at) OVERRIDING SYSTEM VALUE VALUES (9001, 42, 'buy', now());
COMMIT;// Idempotent insert into a partitioned table: the side table is the arbiter.
func insertOnce(ctx context.Context, db *sql.DB, id, userID int64, kind string) (bool, error) {
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return false, err
}
defer tx.Rollback()
res, err := tx.ExecContext(ctx, `INSERT INTO event_ids (id) VALUES ($1) ON CONFLICT DO NOTHING`, id)
if err != nil {
return false, err
}
if n, _ := res.RowsAffected(); n == 0 {
return false, nil // already stored
}
if _, err := tx.ExecContext(ctx,
`INSERT INTO events (id, user_id, kind, created_at) OVERRIDING SYSTEM VALUE VALUES ($1, $2, $3, now())`,
id, userID, kind); err != nil {
return false, err
}
return true, tx.Commit()
}// Laravel: the same, with insertOrIgnore() on the side table.
$stored = DB::transaction(function () use ($id, $userId, $kind) {
if (DB::table('event_ids')->insertOrIgnore(['id' => $id]) === 0) {
return false;
}
DB::insert(
'INSERT INTO events (id, user_id, kind, created_at) OVERRIDING SYSTEM VALUE VALUES (?, ?, ?, now())',
[$id, $userId, $kind],
);
return true;
});Adding an index without blocking
CREATE INDEX events_kind_idx ON ONLY events (kind); -- invalid parent index
CREATE INDEX CONCURRENTLY events_2026_11_kind_idx ON events_2026_11 (kind);
ALTER INDEX events_kind_idx ATTACH PARTITION events_2026_11_kind_idx;
CREATE INDEX CONCURRENTLY events_2026_12_kind_idx ON events_2026_12 (kind);
ALTER INDEX events_kind_idx ATTACH PARTITION events_2026_12_kind_idx;
SELECT indisvalid FROM pg_index WHERE indexrelid = 'events_kind_idx'::regclass; -- true after the last attach// Build one partition's index concurrently and attach it. CONCURRENTLY cannot
// run inside a transaction, so use plain ExecContext calls (autocommit).
func indexPartition(ctx context.Context, db *sql.DB, partition string) error {
idx := partition + "_kind_idx" // partition names come from pg_inherits, not user input
if _, err := db.ExecContext(ctx, fmt.Sprintf(
`CREATE INDEX CONCURRENTLY IF NOT EXISTS %s ON %s (kind)`, idx, partition)); err != nil {
return err
}
_, err := db.ExecContext(ctx, fmt.Sprintf(`ALTER INDEX events_kind_idx ATTACH PARTITION %s`, idx))
return err
}// Laravel migration: CONCURRENTLY needs the migration outside a transaction.
return new class extends Migration
{
public $withinTransaction = false;
public function up(): void
{
DB::statement('CREATE INDEX IF NOT EXISTS events_kind_idx ON ONLY events (kind)');
$partitions = DB::select("select inhrelid::regclass::text as name from pg_inherits
where inhparent = 'events'::regclass");
foreach ($partitions as $p) {
DB::statement("CREATE INDEX CONCURRENTLY IF NOT EXISTS {$p->name}_kind_idx ON {$p->name} (kind)");
DB::statement("ALTER INDEX events_kind_idx ATTACH PARTITION {$p->name}_kind_idx");
}
}
};Queries that do not prune
| Symptom | Cause | Fix |
|---|---|---|
| Plan lists every partition | No partition key in WHERE | Add a time window (created_at >= now() - interval '30 days') |
| Still every partition | Key wrapped in a function: date(created_at) = '2026-12-05', created_at::date | Half-open range on the raw column |
Pruned in psql, not from the app | Generic plan; check Subplans Removed with EXPLAIN (ANALYZE) | Usually fine: executor-start pruning; ensure parameters are typed timestamptz |
Lookup by id scans all months | id is not the partition key | Carry the time with the id (UUIDv7/Snowflake) or a lookup table |
| Slow planning, little data | Thousands of partitions remain after pruning | Fewer, larger partitions; always send the key |
// Half-open range on the raw column: prunes at plan or executor start.
rows, err := db.QueryContext(ctx,
`SELECT kind, count(*) FROM events
WHERE user_id = $1 AND created_at >= $2 AND created_at < $3
GROUP BY kind`, userID, from, to)// Laravel: a scope that always adds the partition key; whereBetween() is inclusive
// at both ends, so use two where() calls for a half-open range.
public function scopeInMonth(Builder $q, CarbonImmutable $month): Builder
{
return $q->where('created_at', '>=', $month->startOfMonth())
->where('created_at', '<', $month->startOfMonth()->addMonthNoOverflow());
}
// Event::inMonth($month)->where('user_id', $userId)->count();Routing to shards
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
hash(key) % n | Stable hash (FNV, CRC32) modulo shard count | Trivial, stateless | Changing n moves most keys |
| Many virtual shards | hash(key) % 1024 → shard id → server map | Move whole virtual shards; mapping is stable | One more lookup (in memory) |
| Consistent hashing | Ring with virtual nodes (Consistent Hashing) | Adding a node moves ~1/N | More code; still needs data copy |
| Directory table | tenant_directory(tenant_id, shard) cached in the app | Any placement; move one tenant at a time | Directory is a dependency; cache invalidation |
| Citus | create_distributed_table | SQL across shards, rebalancer | Extension and coordinator to operate |
The Go router: one *sql.DB per shard, a stable FNV hash, and a parallel scatter-gather with a per-shard deadline:
// Package shard routes a user to one of several independent PostgreSQL
// databases with a stable hash. This is application-level sharding: the
// databases know nothing about each other.
package shard
import (
"context"
"database/sql"
"encoding/binary"
"errors"
"fmt"
"hash/fnv"
"sync"
"time"
)
// Router holds one *sql.DB (itself a pool) per shard. The slice order is part
// of the data layout: changing it or its length moves users to other shards.
type Router struct {
shards []*sql.DB
}
func NewRouter(shards []*sql.DB) (*Router, error) {
if len(shards) == 0 {
return nil, errors.New("shard: need at least one shard")
}
return &Router{shards: shards}, nil
}
// ShardFor maps a user to a shard index: hash(userID) % n. Changing n remaps
// most users; see consistent hashing or a directory table for alternatives.
func ShardFor(userID int64, n int) int {
var buf [8]byte
binary.BigEndian.PutUint64(buf[:], uint64(userID))
h := fnv.New32a()
_, _ = h.Write(buf[:])
return int(h.Sum32() % uint32(n))
}
// Len reports the number of shards.
func (r *Router) Len() int { return len(r.shards) }
// For returns the database that owns this user's rows.
func (r *Router) For(userID int64) *sql.DB {
return r.shards[ShardFor(userID, len(r.shards))]
}
// InsertEvent writes to the one shard that owns userID. The event id comes
// from the caller (for example a UUIDv7 or Snowflake id), because identity
// columns on separate shards would hand out the same numbers.
func (r *Router) InsertEvent(ctx context.Context, eventID string, userID int64, kind string) error {
_, err := r.For(userID).ExecContext(ctx,
`INSERT INTO events (id, user_id, kind, created_at) VALUES ($1, $2, $3, now())`,
eventID, userID, kind)
return err
}
// CountAll is a scatter-gather query: it asks every shard in parallel, each
// with its own deadline, and merges the answers. There is no transaction and
// no common snapshot across the shards, so the total is approximate under
// concurrent writes. One failed shard fails the whole answer.
func (r *Router) CountAll(ctx context.Context, perShard time.Duration) (int64, error) {
counts := make([]int64, len(r.shards))
errs := make([]error, len(r.shards))
var wg sync.WaitGroup
for i, db := range r.shards {
wg.Add(1)
go func(i int, db *sql.DB) {
defer wg.Done()
sctx, cancel := context.WithTimeout(ctx, perShard)
defer cancel()
if err := db.QueryRowContext(sctx, `SELECT count(*) FROM events`).Scan(&counts[i]); err != nil {
errs[i] = fmt.Errorf("shard %d: %w", i, err)
}
}(i, db)
}
wg.Wait()
if err := errors.Join(errs...); err != nil {
return 0, err
}
var total int64
for _, n := range counts {
total += n
}
return total, nil
}The lab driver for the 3-shard Docker Compose below writes 300 events and runs the scatter-gather:
// Command lab writes events for 100 users across the three shards started by
// lab/docker-compose.yml, then runs a scatter-gather count and shows how many
// users would move if the shard count changed from 3 to 4.
//
// SHARD_DSNS="postgres://app:app@localhost:5433/app,postgres://app:app@localhost:5434/app,postgres://app:app@localhost:5435/app" go run ./after/lab
package main
import (
"context"
"crypto/rand"
"database/sql"
"fmt"
"log"
"os"
"strings"
"time"
_ "github.com/jackc/pgx/v5/stdlib"
"academy/partitioning-sharding-postgresql/after/shard"
)
// newID returns a random UUID string. Production code would use UUIDv7 or a
// Snowflake-style id so ids are unique across shards and roughly time-ordered.
func newID() string {
var b [16]byte
_, _ = rand.Read(b[:])
b[6] = (b[6] & 0x0f) | 0x40
b[8] = (b[8] & 0x3f) | 0x80
return fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:16])
}
func main() {
raw := os.Getenv("SHARD_DSNS")
if raw == "" {
log.Fatal("SHARD_DSNS is not set (comma-separated DSNs)")
}
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
var dbs []*sql.DB
for _, dsn := range strings.Split(raw, ",") {
db, err := sql.Open("pgx", dsn)
if err != nil {
log.Fatal(err)
}
defer db.Close()
dbs = append(dbs, db)
}
r, err := shard.NewRouter(dbs)
if err != nil {
log.Fatal(err)
}
perShard := make([]int, r.Len())
for user := int64(1); user <= 100; user++ {
perShard[shard.ShardFor(user, r.Len())]++
for i := 0; i < 3; i++ {
if err := r.InsertEvent(ctx, newID(), user, "page_view"); err != nil {
log.Fatal(err)
}
}
}
fmt.Println("users per shard:", perShard)
total, err := r.CountAll(ctx, 2*time.Second)
if err != nil {
log.Fatal(err)
}
fmt.Println("scatter-gather count:", total)
moved := 0
for user := int64(1); user <= 10000; user++ {
if shard.ShardFor(user, 3) != shard.ShardFor(user, 4) {
moved++
}
}
fmt.Printf("hash %% n, 3 -> 4 shards: %d of 10000 users change shard\n", moved)
}The Laravel resolver uses the same FNV-1a hash over the same 8 big-endian bytes (hash('fnv1a32', pack('J', $id))), so PHP and Go services agree on every user's shard; it maps the shard to a connection name from config/database.php, uses Model::on() / setConnection(), and lets HasUuids fill a UUIDv7 id:
<?php
// app/Sharding/ShardResolver.php
//
// config/database.php defines one connection per shard, matching the three
// shards of the lab's docker-compose.yml:
//
// 'connections' => [
// 'shard_0' => [...], // pgsql, port 5433
// 'shard_1' => [...], // pgsql, port 5434
// 'shard_2' => [...], // pgsql, port 5435
// ],
namespace App\Sharding;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Concerns\HasUuids;
use Illuminate\Database\Eloquent\Model;
// The events table on every shard (lab/init-shard.sql): uuid id, no updated_at.
// HasUuids fills the id with a UUIDv7, so ids never collide across shards.
final class ShardedEvent extends Model
{
use HasUuids;
public const UPDATED_AT = null;
protected $table = 'events';
protected $guarded = [];
}
final class ShardResolver
{
public function __construct(private readonly int $shardCount = 3) {}
// Same function as the Go router: FNV-1a 32-bit over the user id as 8
// big-endian bytes, modulo the shard count. pack('J') is an unsigned
// 64-bit big-endian integer, like binary.BigEndian.PutUint64 in Go, so a
// PHP and a Go service agree on every user's shard.
public function shardFor(int $userId): int
{
return hexdec(hash('fnv1a32', pack('J', $userId))) % $this->shardCount;
}
public function connectionFor(int $userId): string
{
return 'shard_'.$this->shardFor($userId);
}
// Model::on() returns a query builder bound to the named connection.
public function eventsFor(int $userId): Builder
{
return ShardedEvent::on($this->connectionFor($userId))
->where('user_id', $userId);
}
public function record(int $userId, string $kind): ShardedEvent
{
$event = new ShardedEvent([
'user_id' => $userId,
'kind' => $kind,
'created_at' => now(),
]);
// Write to the shard that owns this user.
$event->setConnection($this->connectionFor($userId));
$event->save();
return $event;
}
// A cross-shard query: ask every shard and merge in PHP. No single
// transaction or snapshot covers the shards.
public function countAll(): int
{
$total = 0;
for ($i = 0; $i < $this->shardCount; $i++) {
$total += ShardedEvent::on("shard_{$i}")->count();
}
return $total;
}
}// config/database.php: one connection per shard (read/write split is a separate axis).
'shard_0' => ['driver' => 'pgsql', 'host' => env('SHARD0_HOST'), 'port' => 5432,
'database' => 'app', 'username' => env('DB_USERNAME'), 'password' => env('DB_PASSWORD')],
'shard_1' => [/* ... */],
'shard_2' => [/* ... */],
// Cross-shard read: ask each connection and merge in PHP (no common snapshot).
$total = collect(['shard_0', 'shard_1', 'shard_2'])
->sum(fn (string $c) => DB::connection($c)->table('events')->count());The Go angle
database/sql has no notion of shards: *sql.DB is a pool for one database, so a router is a slice of pools plus a function, and you own consistency across them. hash/fnv has a fixed, documented algorithm, so every process (and every language that implements FNV-1a) computes the same shard; never route with Go's map iteration or a seeded hash. DDL cannot take bind parameters for identifiers, so partition names are built from time.Time or catalog values only. Session settings such as SET lock_timeout apply to one connection, so use db.Conn(ctx) to pin a connection for multi-statement DDL. CREATE INDEX CONCURRENTLY and DETACH ... CONCURRENTLY must run outside BeginTx. Each shard pool multiplies connections: put PgBouncer in front (Connection Pooling).
The Laravel angle
Laravel's database docs cover named connections ("you may access each connection via the connection method provided by the DB facade") and read/write splitting (read, write, sticky), which is replication, not sharding (Replication & Failover). The schema builder cannot express PARTITION BY or PARTITION OF; use DB::statement in migrations and $withinTransaction = false for CONCURRENTLY. Migrations run per connection, so run them once per shard (php artisan migrate --database=shard_0, ...). Eloquent has no shard key: the resolver is yours, and relationships between models on different connections cannot be joined in SQL (eager loading issues one query per connection). Never wrap DETACH ... CONCURRENTLY in DB::transaction. For tenant-per-request routing see Multi-Tenancy Strategies.
Choosing a strategy
| Workload | Recommendation | Extra technique | Reason |
|---|---|---|---|
| Append-only events, logs, metrics with retention | RANGE by time, monthly or daily | pg_partman or a rotation job; BRIN on time | Retention becomes DROP; queries filter by time |
| Big table, no time filter, lookups by user | HASH by user_id (8–32 buckets) or no partitioning | Good B-tree indexes first | Smaller indexes and VACUUM units; pruning on equality |
| Regulated data per region | LIST by region | Tablespaces per region; per-region retention | Physical separation and per-region drop |
| SaaS, a few giant tenants | LIST for the giants + DEFAULT (or HASH) for the rest | Later: shard by tenant_id | Isolate the noisy few |
| Orders + lines that must stay consistent | Partition both by the same key and rotate together | Composite FKs including the key | FKs to partitioned tables need the key |
| Single server out of write capacity | Shard by the key every hot query carries | Citus (SQL across shards) or app routing (independent shards) | Partitioning adds no write throughput |
| Multi-tenant SaaS outgrowing one node | Citus row-based sharding on tenant_id | Reference tables for global data; 32–128 shards | Co-located joins and transactions per tenant |
| Archive of cold data on cheaper servers | postgres_fdw foreign partitions for old months | async_capable | Pure PostgreSQL; reads only |
| MySQL shop at shard scale | Vitess | Lookup vindexes for secondary access paths | Online resharding |
| Document data, flexible schema | MongoDB sharding with a hashed or compound key | refineCollectionShardKey | Built-in balancer |
| Unsure | Do not partition or shard yet | Indexes, replicas, pooling, caching (Storage & Data Scaling) | Every split costs features |
In architecture: from a single process to a distributed system
Partitioning is a storage decision inside one database: the application barely notices. Sharding is an architecture decision: the shard key becomes part of every API, every transaction boundary and every report. The rule of thumb that falls out: partition early when data is time-shaped, shard late and only along a key the business already scopes work by.
Monolith: one process, one database
How it shows up: a Laravel or Go monolith with one PostgreSQL. The only visible change after partitioning is that queries should carry the partition key and the rotation job must run.
Simplest correct usage: RANGE by time for the few append-only giants (events, audit_log, notifications); everything else stays unpartitioned. Pre-create partitions with pg_partman or the rotation job, monitor the DEFAULT partition (or have none), and keep id lookups cheap with a time-bearing id.
Example (simple): audit_log grows 50 GB per month and is kept 12 months. Monthly partitions turn the nightly 3-hour DELETE into a 50 ms DROP TABLE, and the "last 7 days" admin view prunes to one or two partitions.
Example (complex): orders (partitioned by created_at) referenced by order_lines, payments and shipments. All four carry order_created_at, all four are partitioned by it with the same monthly bounds, and the rotation job detaches children before parents. The API's GET /orders/{id} uses a UUIDv7 id from which the month is derived, so the lookup prunes.
Modular monolith and multiple databases
How it shows up: modules own their tables; some may already live in separate databases (billing in one, analytics in another). This is vertical partitioning by module, and it is the cheapest "scale-out" there is: each module's database can be sized, tuned and backed up on its own.
Example: the Tracking module's events table outgrows the shared PostgreSQL. Moving the module's tables to their own database (the same move Vitess calls vertical sharding) frees the main database, and nothing else changes because no other module joins to events directly; they read through the module's interface.
Rules: never join across module databases in SQL; keep each invariant inside one module's database; publish changes with an outbox so other modules can build their own read copies.
Microservices: each service owns its data, and maybe its shards
What survives: a service can partition and shard its own database freely; the rest of the system sees only its API and events. What does not: a cross-service query is already a scatter-gather over the network, and a sharded service adds a second fan-out inside it.
GET /customers/42/summary
1 API gateway -> customer-service: GET /customers/42 (customer-service sharded by customer_id: 1 shard)
2 -> order-service: GET /orders?customer=42 (order-service sharded by customer_id: 1 shard)
3 -> analytics-service: GET /spend/42 (reads a warehouse, not the shards)
4 gateway merges three responses
GET /admin/orders?status=failed (no customer_id)
1 order-service scatters to its 8 shards, merges, paginates by (created_at, id) keyset
2 p99 = slowest shard; one shard down = partial result flagged to the callerRules: choose each service's shard key from the service's own dominant access path; make cross-shard admin queries asynchronous or move them to a read model fed by change data capture; propagate the shard key (tenant, customer) in request context and message headers so downstream services can route without a lookup.
Distributed data: replicas, distributed SQL, multi-region
Shards and replicas are orthogonal. Each shard is a primary with its own replicas and its own failover (Replication & Failover); a 3-shard cluster with one replica each is six servers, and the router must know which node is primary per shard. Read-your-writes and replica lag apply per shard.
Cross-shard transactions. A transfer between two users on different shards is not atomic without two-phase commit. Citus runs 2PC for multi-shard writes; postgres_fdw does not prepare remote transactions; application routing has nothing. The usual answer is to choose the shard key so such transactions are rare and to handle the rest as sagas with idempotent steps (Distributed SQL, Consensus & 2PC).
Distributed SQL instead of sharding by hand. CockroachDB, Spanner and Citus hide the routing and offer cross-shard transactions, at the cost of per-transaction latency and new failure modes. CockroachDB splits its key space into ranges automatically; you still choose primary keys that avoid hot ranges (no monotonically increasing keys at high write rates).
Multi-region. LIST partitioning by region (PostgreSQL) or region-pinned shards keeps data where the law requires; queries that need several regions become cross-region scatter-gathers with round trips of tens to hundreds of milliseconds.
Scaling path: 1×, 10×, 100×
| Load | What changes | Partitioning / sharding consequence |
|---|---|---|
| 1× (one primary, tables up to a few hundred GB) | Indexes, pooling, a replica for reports | No partitioning yet, except for append-only tables with retention |
| 10× (TB-sized tables, retention pressure, VACUUM takes hours) | Time-partition the giants; pg_partman; BRIN on time; reports on replicas | Queries must carry the key; unique keys include it; ids carry time |
| 100× (one primary out of write throughput or storage) | Shard by tenant/user (Citus or app routing); per-shard replicas; IDs without sequences; a warehouse for global queries | Every request routes by key; cross-shard work becomes async; resharding is a planned operation |
Lab
Everything below is written to run on a laptop with Docker. These experiments were not executed while this page was written (no PostgreSQL server was available); the comments show the plan lines and messages to look for, taken from the PostgreSQL documentation and the code above. Your node types (parallel plans, index vs index-only scans), row counts, costs and timings will differ; the partitions that appear or disappear will not.
Setup: one PostgreSQL and a 10M-row partitioned events table.
docker run -d --name pgpart -e POSTGRES_PASSWORD=pg -p 5432:5432 postgres:17
docker exec -it pgpart psql -U postgresSET TimeZone = 'UTC';
CREATE TABLE events (
id bigint GENERATED ALWAYS AS IDENTITY,
user_id bigint NOT NULL,
kind text NOT NULL,
created_at timestamptz NOT NULL,
PRIMARY KEY (id, created_at)
) PARTITION BY RANGE (created_at);
DO $$
DECLARE m date := '2026-01-01';
BEGIN
WHILE m < '2027-01-01' LOOP
EXECUTE format('CREATE TABLE %I PARTITION OF events FOR VALUES FROM (%L) TO (%L)',
'events_' || to_char(m, 'YYYY_MM'), m, (m + interval '1 month')::date);
m := (m + interval '1 month')::date;
END LOOP;
END $$;
CREATE INDEX ON events (created_at);
-- 10M rows spread evenly over 2026 (one row every 3.1536 s); takes a minute or two
INSERT INTO events (user_id, kind, created_at)
SELECT (random() * 100000)::bigint,
(ARRAY['view', 'click', 'buy'])[1 + g % 3],
timestamptz '2026-01-01 00:00:00+00' + g * interval '3.1536 seconds'
FROM generate_series(0, 9999999) AS g;
VACUUM (ANALYZE) events; -- statistics + visibility map (index-only scans need it)
SELECT tableoid::regclass, count(*) FROM events GROUP BY 1 ORDER BY 1; -- 12 rows, ~850k eachExperiment 1: pruning at plan time.
EXPLAIN SELECT count(*) FROM events
WHERE created_at >= '2026-12-05' AND created_at < '2026-12-06';
-- Aggregate
-- -> Index (Only) Scan using events_2026_12_created_at_idx on events_2026_12 events
-- Index Cond: ((created_at >= ...) AND (created_at < ...))
-- what matters: only events_2026_12 appears; the other 11 are not in the plan at all
EXPLAIN SELECT count(*) FROM events WHERE user_id = 42;
-- every partition events_2026_01 ... events_2026_12 appears (often under Gather / Parallel Append)Experiment 2: pruning at executor start (generic plan, now()).
PREPARE day_count (timestamptz, timestamptz) AS
SELECT count(*) FROM events WHERE created_at >= $1 AND created_at < $2;
SET plan_cache_mode = force_generic_plan;
EXPLAIN (ANALYZE, COSTS OFF) EXECUTE day_count('2026-12-05', '2026-12-06');
-- Aggregate (actual ...)
-- -> Append (actual ...)
-- Subplans Removed: 11
-- -> Index (Only) Scan ... on events_2026_12 events_1
RESET plan_cache_mode;
EXPLAIN (COSTS OFF) SELECT count(*) FROM events WHERE created_at > now() - interval '7 days';
-- Append ... Subplans Removed: N (now() is stable: pruned at executor start, not at plan time)Experiment 3: what pruning saves in planning (and what partitionwise costs).
EXPLAIN (SUMMARY) SELECT * FROM events WHERE created_at >= '2026-12-05' AND created_at < '2026-12-06';
-- Planning Time: small
SET enable_partition_pruning = off;
EXPLAIN (SUMMARY) SELECT * FROM events WHERE created_at >= '2026-12-05' AND created_at < '2026-12-06';
-- 12 partitions in the plan; Planning Time higher; at execution each partition's index is probed
RESET enable_partition_pruning;
SET enable_partitionwise_aggregate = on;
EXPLAIN (COSTS OFF) SELECT created_at::date, count(*) FROM events GROUP BY 1;
-- Append -> 12 x (Partial/Finalize) aggregates per partition instead of one aggregate over AppendExperiment 4: the unique-key rule and a missing partition.
ALTER TABLE events ADD CONSTRAINT events_id_key UNIQUE (id);
-- ERROR: unique constraint on partitioned table must include all partitioning columns
INSERT INTO events (user_id, kind, created_at) VALUES (1, 'view', '2028-01-01');
-- ERROR: no partition of relation "events" found for row
-- DETAIL: Partition key of the failing row contains (created_at) = (2028-01-01 00:00:00+00).Experiment 5: rotation vs DELETE.
-- What a DELETE of one month costs (rolled back):
BEGIN;
EXPLAIN (ANALYZE, WAL, COSTS OFF) DELETE FROM events WHERE created_at < '2026-02-01';
-- Delete on events ... WAL: records=~850000 fpi=... bytes=tens of MB
ROLLBACK;
-- committed, the same DELETE would also leave ~850k dead tuples for VACUUM
-- Rotation: attach January 2027 with the CHECK trick, retire January 2026
CREATE TABLE events_2027_01 (LIKE events INCLUDING DEFAULTS);
ALTER TABLE events_2027_01 ADD CONSTRAINT b CHECK (created_at >= '2027-01-01' AND created_at < '2027-02-01');
SET lock_timeout = '5s';
BEGIN;
ALTER TABLE events ATTACH PARTITION events_2027_01 FOR VALUES FROM ('2027-01-01') TO ('2027-02-01');
-- second terminal now: SELECT mode, granted FROM pg_locks WHERE relation = 'events'::regclass;
-- ShareUpdateExclusiveLock | t (and SELECT/INSERT on events still run)
COMMIT;
ALTER TABLE events_2027_01 DROP CONSTRAINT b;
ALTER TABLE events DETACH PARTITION events_2026_01 CONCURRENTLY; -- autocommit, no BEGIN
DROP TABLE events_2026_01; -- instant, no WAL per rowExperiment 6: a 3-shard Docker Compose and application routing.
# Three independent PostgreSQL shards for the lab. Each runs init-shard.sql
# on first start. Start with: docker compose up -d
services:
shard0:
image: postgres:17
environment: &pg
POSTGRES_USER: app
POSTGRES_PASSWORD: app
POSTGRES_DB: app
ports: ["5433:5432"]
volumes: ["./init-shard.sql:/docker-entrypoint-initdb.d/init.sql:ro"]
shard1:
image: postgres:17
environment: *pg
ports: ["5434:5432"]
volumes: ["./init-shard.sql:/docker-entrypoint-initdb.d/init.sql:ro"]
shard2:
image: postgres:17
environment: *pg
ports: ["5435:5432"]
volumes: ["./init-shard.sql:/docker-entrypoint-initdb.d/init.sql:ro"]-- Same schema on every shard. The id is supplied by the application (UUID),
-- so two shards never hand out the same id.
CREATE TABLE events (
id uuid PRIMARY KEY,
user_id bigint NOT NULL,
kind text NOT NULL,
created_at timestamptz NOT NULL
);
CREATE INDEX events_user_created_idx ON events (user_id, created_at);cd docs/snippets/database/partitioning-sharding-postgresql/lab && docker compose up -d
cd ../go
SHARD_DSNS="postgres://app:app@localhost:5433/app,postgres://app:app@localhost:5434/app,postgres://app:app@localhost:5435/app" \
go run ./after/lab
# users per shard: [33 33 34]
# scatter-gather count: 300
# hash % n, 3 -> 4 shards: 7507 of 10000 users change shard
for p in 5433 5434 5435; do psql "postgres://app:app@localhost:$p/app" -Atc "select count(*) from events"; done
# 99, 99, 102 (3 events per user)
docker compose stop shard2
go run ./after/lab # log.Fatal at the first insert for a user owned by shard2: routing has no fallback,
# and a CountAll would return an error naming shard 2 instead of a totalThe last two lines are the point: one unavailable shard breaks every request for its users and every scatter-gather, and changing from 3 to 4 shards with hash % n would move three quarters of the users.
Common misconceptions
| Belief | Reality |
|---|---|
| “Partitioning makes every query faster.” | Only queries with the partition key in WHERE prune; others scan every partition and plan slower. |
| “Partitioning is sharding on one box.” | Same CPU, RAM, disk, WAL and failure domain; no extra write throughput. |
“I can keep PRIMARY KEY (id) on a time-partitioned table.” | PostgreSQL and MySQL require every unique key to include the partition key; there is no global index. |
“I can convert my existing table with ALTER TABLE ... PARTITION BY.” | Not possible; attach the old table as a partition of a new parent. |
| “Pruning needs an index on the key.” | Pruning uses partition bounds; indexes only matter inside the surviving partitions. |
| “Prepared statements disable pruning.” | Generic plans prune at executor start (Subplans Removed). |
“There is ATTACH PARTITION CONCURRENTLY.” | Only DETACH has CONCURRENTLY; ATTACH already takes SHARE UPDATE EXCLUSIVE on the parent, and a matching CHECK skips its scan. |
| “A DEFAULT partition is free insurance.” | It slows every new partition (scan) and forbids DETACH ... CONCURRENTLY. |
| “More partitions, more speed.” | Planning time and per-session memory grow with partitions that survive pruning; "a few thousand" is the documented comfort zone. |
| “Hash partitioning spreads load across machines.” | Hash partitions share one server; only sharding spreads load. |
| “Hashing the shard key prevents hot shards.” | One huge tenant is still one key on one shard. |
| “3 → 4 shards moves a quarter of the data.” | With hash % n about three quarters move (7,507 of 10,000 in the lab). |
| “Identity columns keep ids unique across shards.” | Each shard counts on its own; use UUIDv7/Snowflake or disjoint ranges. |
“postgres_fdw gives distributed transactions.” | It does not prepare remote transactions for 2PC. |
| “MySQL partitioned tables keep their foreign keys.” | InnoDB partitioned tables do not support foreign keys. |
Cheat sheet
| Topic | What to remember |
|---|---|
| Methods | RANGE (time), LIST (known values), HASH (MODULUS/REMAINDER), DEFAULT (RANGE/LIST only), sub-partitioning |
| Partition key | Most common WHERE column; must be in every unique key; data removed together lives together |
| Pruning | Plan time (constants), executor start (Subplans Removed), execution (never executed); enable_partition_pruning |
| Partitionwise | enable_partitionwise_join / _aggregate off by default; same key, same bounds |
| Indexes | Created on the parent → on every partition; no CONCURRENTLY on the parent: ON ONLY + per-partition + ALTER INDEX ... ATTACH PARTITION |
| Add a partition | CREATE TABLE (LIKE ...) + CHECK + ATTACH (parent SHARE UPDATE EXCLUSIVE) under lock_timeout |
| Remove a partition | DETACH ... CONCURRENTLY (no txn block, no DEFAULT, FINALIZE if interrupted) + DROP TABLE |
| Limits | "A few thousand" partitions (PostgreSQL), ~100 for inheritance, 8192 (MySQL), 15,000 (SQL Server) |
| Rotation | Premake ahead, alert on failure, pg_partman create_parent + run_maintenance / BGW |
| Errors | 23514 no partition for row; overlap 42P17; unique-key rule; 55P03 lock timeout; 25001 CONCURRENTLY in a txn |
| Shard key | High cardinality, even frequency, not monotonic, in every hot query, groups transactional rows |
| Cross-shard | Scatter-gather = slowest shard, no shared snapshot; co-locate or use reference tables |
| Resharding | Avoid hash % n; many virtual shards, consistent hashing, directory table; Citus rebalancer, Vitess resharding |
| IDs | No per-shard sequences: UUIDv7, Snowflake, or disjoint ranges |
| Products | Citus (coordinator, distributed/reference tables), postgres_fdw (no 2PC), Vitess (vindex, VTGate), MongoDB (chunks, mongos, balancer) |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — Your events table is RANGE-partitioned by created_at. Why does SELECT * FROM events WHERE id = 123 touch every partition? Important
Answer
Answer: Pruning works only from the partition key; id is not part of it, so no bound excludes any partition. Carry the time with the id (UUIDv7, Snowflake) and add a range on created_at, or keep a lookup table. See Partition pruning.
2 — Why can't you create PRIMARY KEY (id) on that table, and what does PRIMARY KEY (id, created_at) actually guarantee? Important
Answer
Answer: PostgreSQL has no global index; uniqueness is checked per partition, so the key must include the partition key. The composite key guarantees the pair is unique, not id alone. See Unique constraints.
3 — What is the difference between Subplans Removed: 11 and (never executed) in EXPLAIN ANALYZE? Good to know
Answer
Answer: Subplans Removed counts partitions pruned at executor initialization (they are not shown); (never executed) marks partitions pruned during execution, e.g. on every loop of a nested-loop join. See Partition pruning.
4 — Which lock does ATTACH PARTITION take on the parent, and how do you avoid the validation scan? Good to know
Answer
Answer: SHARE UPDATE EXCLUSIVE on the parent. Add a CHECK constraint on the incoming table that matches the bound before attaching, then drop it. See ATTACH and DETACH.
5 — Your rotation job runs DETACH PARTITION ... CONCURRENTLY inside DB::transaction(). What happens, and what else can make it fail? Good to know
Answer
Answer: It fails because CONCURRENTLY cannot run in a transaction block; it is also refused when the table has a DEFAULT partition. If interrupted, finish with DETACH PARTITION ... FINALIZE. See Error messages.
6 — You add 20 hash partitions on one server. How much write throughput did you gain? Must-know
Answer
Answer: None: partitions share the server's CPU, disk and WAL. Hash partitioning shrinks indexes and VACUUM units; only sharding adds capacity. See Partitioning vs sharding.
7 — Name three properties of a good shard key. Must-know
Answer
Answer: High cardinality, even frequency (no dominant value), not monotonically increasing (or hashed), present in nearly every hot query, and grouping rows that must be updated together. See Shard key choice.
8 — Why is a scatter-gather query slower and less consistent than the same query on one database? Must-know
Answer
Answer: It waits for the slowest shard, fails or degrades if one shard is down, and reads each shard at a different moment with no shared snapshot. See Scatter-gather.
9 — You route with fnv1a(user_id) % 3 (the lab router) and need a fourth shard. Roughly how much data moves, and what would have avoided it? Important
Answer
Answer: About three quarters of keys (7,507 of 10,000 in the lab). Many virtual shards, consistent hashing, a directory table, or Citus's rebalancer avoid remapping. See Resharding.
10 — Why does postgres_fdw sharding not give atomic writes across two servers? Important
Answer
Answer: postgres_fdw does not prepare remote transactions for two-phase commit, so a crash between the two remote commits leaves one applied. See Routing options.
11 — What does a Citus reference table solve? Good to know
Answer
Answer: Joins between a distributed table and small shared data (countries, plans): the reference table is replicated to every worker, so the join stays local on each shard. See Scatter-gather.
Glossary
| Term | Meaning |
|---|---|
| Partitioning | Splitting one logical table into several physical tables on the same server |
| Horizontal partitioning | Splitting rows (by range, list or hash) |
| Vertical partitioning | Splitting columns (or whole tables) into separate tables or databases |
| Declarative partitioning | PostgreSQL PARTITION BY / PARTITION OF, routed and pruned by the server |
| Partitioned table | The parent: no storage, routes rows to partitions |
| Partition | A child table holding the rows of one bound |
| Partition key | Columns/expressions in PARTITION BY that decide the partition |
| Partition bound | The FOR VALUES clause of a partition |
| RANGE | Partitioning by non-overlapping intervals; upper bound exclusive |
| LIST | Partitioning by explicit value lists |
| HASH | Partitioning by hash(key) mod MODULUS = REMAINDER |
| MODULUS / REMAINDER | The two numbers that define a hash partition |
| DEFAULT partition | Catch-all partition for rows matching no bound (RANGE/LIST) |
| Sub-partitioning | A partition that is itself partitioned |
| Tuple routing | Choosing the partition for each inserted or updated row |
| Row movement | An UPDATE of the key that moves a row to another partition |
| Partition pruning | Skipping partitions that cannot match, using bounds |
| Plan-time pruning | Pruning from constants while planning |
| Execution-time pruning | Pruning at executor start (parameters, stable functions) or during execution (subqueries, nested loops) |
| Subplans Removed | EXPLAIN line counting partitions pruned at executor start |
| (never executed) | EXPLAIN ANALYZE marker for a subplan pruned at run time on every loop |
| enable_partition_pruning | PostgreSQL GUC switching declarative pruning (default on) |
| Partitionwise join (partition-wise join) | Joining matching partitions pairwise; enable_partitionwise_join |
| Partitionwise aggregate | Aggregating per partition; enable_partitionwise_aggregate |
| constraint_exclusion | Plan-time, CHECK-based exclusion used by inheritance partitioning |
| Inheritance partitioning | Legacy scheme: INHERITS, insert trigger, CHECK constraints |
| Partitioned index | A logical index on the parent made of per-partition indexes |
| CREATE INDEX ON ONLY | Creates an invalid parent index without touching partitions |
| ALTER INDEX ... ATTACH PARTITION | Attaches a partition's index to the parent index |
| Global index | One index spanning all partitions; absent in PostgreSQL and MySQL, present in Oracle |
| Unique key rule | Unique/primary keys must include all partition key columns |
| ATTACH PARTITION | Adds an existing table as a partition (parent SHARE UPDATE EXCLUSIVE) |
| DETACH PARTITION | Removes a partition, leaving a standalone table |
| DETACH CONCURRENTLY | Two-transaction detach with a weaker parent lock; no txn block, no DEFAULT |
| FINALIZE | Completes an interrupted DETACH ... CONCURRENTLY |
| Pending detach | State of a partition whose concurrent detach was interrupted |
| CHECK-constraint trick | A CHECK matching the bound lets ATTACH skip the validation scan |
| ACCESS EXCLUSIVE | Strongest table lock; blocks all access |
| SHARE UPDATE EXCLUSIVE | Lock that allows reads and writes but excludes other DDL/VACUUM |
| lock_timeout | Maximum wait for a lock before 55P03 |
| max_locks_per_transaction | Size of the lock table per transaction; matters with many partitions |
| plan_cache_mode | Forces generic or custom plans for prepared statements |
| Planning time | Time spent building a plan; grows with surviving partitions |
| Time-based rotation | Creating future partitions and retiring old ones on a schedule |
| Retention | How long data is kept before its partition is dropped |
| Premake | Number of future partitions kept ready |
| pg_partman | Extension that automates partition creation and retention |
| create_parent | pg_partman function that registers a partition set |
| run_maintenance | pg_partman function that creates/retires partitions |
| pg_partman_bgw | pg_partman background worker that calls run_maintenance() |
| 23514 | SQLSTATE check_violation; also "no partition of relation ... found for row" |
| Sharding | Distributing rows of one logical table across database servers |
| Shard | One server (or server group) holding a subset of rows |
| Shard key | Column that decides which shard owns a row |
| Hot shard | A shard with disproportionate data or traffic |
| Skew | Uneven distribution of key values |
| Scatter-gather | Sending a query to all shards and merging results |
| Cross-shard join | A join whose rows live on different shards |
| Co-location (colocation) | Placing rows with the same key from different tables on the same node |
| Reference table | Citus table replicated to every node for local joins |
| Distributed table | Citus table split into shards by a distribution column |
| Distribution column | Citus's name for the shard key |
| Coordinator / worker | Citus nodes: query router and data holders |
| create_distributed_table | Citus function that shards a table |
| Rebalancer | Citus component that moves shards between workers (citus_rebalance_start) |
| citus.shard_count | Citus setting for the number of shards per new distributed table |
| Resharding | Changing the shard count or key-to-shard mapping |
| Directory (lookup) table | Table mapping keys or tenants to shards |
| Application-level routing | Shard selection in application code |
| Consistent hashing | Mapping keys to a ring so adding nodes moves few keys |
| Virtual shards | Many logical shards mapped onto fewer servers |
| Global unique ID | Id unique across all shards (UUIDv7, Snowflake) |
| Multi-tenant sharding | Sharding by tenant_id so each tenant lives on one shard |
| postgres_fdw | PostgreSQL foreign data wrapper for remote PostgreSQL tables |
| Foreign table | Local table definition whose rows live on a remote server |
| async_capable | postgres_fdw option to scan foreign tables concurrently |
| Two-phase commit (2PC) | Atomic commit protocol across servers; not used by postgres_fdw |
| MySQL partitioning | RANGE, LIST, HASH, KEY (and LINEAR) partitioning in InnoDB |
| KEY partitioning | MySQL hash partitioning with a server-supplied hash |
| LINEAR HASH | MySQL hash variant using powers of two for cheaper repartitioning |
| EXCHANGE PARTITION | MySQL/Oracle swap of a partition with a plain table |
| Vitess | MySQL sharding system with VTGate routing |
| Keyspace / keyspace ID | Vitess logical database / the routing value of a row |
| Vindex | Vitess mapping from a column to keyspace IDs (primary, lookup) |
| VTGate | Vitess query router |
| MongoDB chunk | Contiguous range of shard key values on one shard |
| mongos | MongoDB query router |
| Balancer | MongoDB process that moves chunks between shards |
| Hashed sharding | MongoDB sharding on a hash of the key (for monotonic keys) |
| Hash slot | Redis Cluster unit of distribution (16384 slots) |
| Range (CockroachDB) | Contiguous key-space chunk, split automatically |
| Partition function / scheme | SQL Server objects defining boundaries and filegroup mapping |
| Sharding vs partitioning | Many servers vs many tables on one server; only sharding adds capacity |
| postgres_fdw sharding | Foreign tables as partitions of a local parent, one per remote server |
| Hot shards | Shards that receive disproportionate data or traffic |
| Cross-shard joins | Joins needing rows from several shards; avoided by co-location |
| Partitioned indexes | Indexes defined on a partitioned parent, one per partition |
| Shard key choice | Picking the routing column: cardinality, frequency, monotonicity, query fit |
| MongoDB sharding | Collections split into chunks by shard key, routed by mongos |
| Inheritance-based partitioning | The legacy INHERITS + trigger + CHECK scheme |
| DETACH PARTITION CONCURRENTLY | The full form of the concurrent detach command (see above) |
References
- PostgreSQL documentation: Table Partitioning, ALTER TABLE (ATTACH / DETACH PARTITION), CREATE TABLE, Query planning configuration (
enable_partition_pruning,enable_partitionwise_join,enable_partitionwise_aggregate,constraint_exclusion), postgres_fdw - Citus documentation: Choosing Distribution Column, Concepts, Cluster Management
- pg_partman: README, pg_partman.md
- MySQL 8.4 Reference Manual (read via web.archive.org): Overview of Partitioning, KEY Partitioning, Restrictions and Limitations, Partitioning Keys, Primary Keys, and Unique Keys
- Vitess: Sharding, Vindexes
- MongoDB: Sharding, Choose a Shard Key
- Oracle Database 19c VLDB and Partitioning Guide: Partitioning Concepts
- Microsoft: Partitioned tables and indexes
- CockroachDB: Distribution Layer
- Redis: Cluster specification
- Laravel 13: Database: Getting Started (multiple connections, read/write), Eloquent
ModelAPI (on,setConnection) - Go:
database/sql,hash/fnv, pgx v5