Home›Operate›Run it well 8: partitioning
Run it well

Split a huge table into parts

Some tables are really a series of days. Partitioning stores them that way, so deleting a month is a metadata change and queries for today skip everything else. Here is how it works in each engine, and when it makes things worse.

The problem

A table that only grows

Your events table gets 50 GB a month. You only need 90 days of it. Every night a cleanup job deletes yesterday's oldest day, and every night it runs a little longer, pushes the replicas behind, and leaves bloat for vacuum to chase. Meanwhile the dashboard query, which only ever looks at the last 24 hours, still has to walk an index over 600 million rows.

You already saw the batch delete in the last chapter. It works, but it is fighting the shape of the data. This table is really a series of days. What if the database stored it that way?

The idea

One table on the outside, many tables on the inside

Partitioning splits one logical table into parts by a key, usually time. The app still writes to and reads from events. Under the covers each month (or day) is its own table with its own indexes.

Two things get cheap. First, retention: dropping a month is dropping one table, a metadata change that takes milliseconds instead of deleting 50 GB of rows. Second, pruning: a query with WHERE created_at > now() - interval '1 day' only touches the newest partition, because the planner can rule out the rest from their boundaries.

So should every big table be partitioned?

No. Partitioning helps when queries and retention follow the partition key. A query that does not filter on the key now has to visit every partition, which can be slower than one big index. Unique keys get harder, as you will see below. And partitioning is not a replacement for an index: inside each partition you still need the right ones. Big alone is not a reason. Big and naturally sliced by time usually is.

PostgreSQL

Declarative partitioning

Since PostgreSQL 10, you declare the parent and attach the parts. Indexes created on the parent are created on every partition (PostgreSQL 11+). The primary key must include the partition key, because uniqueness is only enforced inside each partition.

CREATE TABLE events (
  id          bigint GENERATED ALWAYS AS IDENTITY,
  created_at  timestamptz NOT NULL,
  account_id  bigint NOT NULL,
  payload     jsonb,
  PRIMARY KEY (id, created_at)
) PARTITION BY RANGE (created_at);

CREATE TABLE events_2026_12 PARTITION OF events
  FOR VALUES FROM ('2026-12-01') TO ('2027-01-01');
CREATE INDEX ON events (account_id, created_at);       -- created on every partition

-- retention: detach without blocking queries (PostgreSQL 14+), then drop
ALTER TABLE events DETACH PARTITION events_2026_09 CONCURRENTLY;
DROP TABLE events_2026_09;

Most teams create future partitions with the pg_partman extension or a small scheduled job. Whichever you use, make sure next month exists before next month starts. A row with no matching partition fails to insert, unless you added a DEFAULT partition. And a default partition that fills with rows makes the next ATTACH slower, because the new range has to be checked against it.

To see pruning, run the query through EXPLAIN. The plan should list only the partitions your WHERE clause can match.

SELECT inhparent::regclass AS parent, count(*) AS partitions FROM pg_inherits GROUP BY 1 ORDER BY 2 DESC LIMIT 10;
MySQL

Range partitions, with two rules

MySQL partitions InnoDB tables natively. Two rules shape the design. Every unique key, including the primary key, must contain every column the partitioning uses. And partitioned InnoDB tables cannot have foreign keys, in either direction.

CREATE TABLE events (
  id          BIGINT NOT NULL AUTO_INCREMENT,
  created_at  DATETIME NOT NULL,
  account_id  BIGINT NOT NULL,
  payload     JSON,
  PRIMARY KEY (id, created_at),
  KEY (account_id, 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)
);

-- next month: split the catch-all before data lands in it
ALTER TABLE events REORGANIZE PARTITION pmax INTO (
  PARTITION p2027_01 VALUES LESS THAN ('2027-02-01'),
  PARTITION pmax     VALUES LESS THAN (MAXVALUE));

-- retention: milliseconds, not hours
ALTER TABLE events DROP PARTITION p2026_11;

Keep pmax empty. Reorganizing an empty partition is quick. Reorganizing one that already holds a month of rows copies all of them. EXPLAIN shows a partitions column, which is how you confirm pruning.

SELECT TABLE_NAME, PARTITION_NAME, TABLE_ROWS FROM information_schema.PARTITIONS WHERE PARTITION_NAME IS NOT NULL ORDER BY TABLE_NAME, PARTITION_ORDINAL_POSITION LIMIT 20;
MongoDB

No partitions, but the same two goals

MongoDB has no table partitioning. It reaches the same two goals in other ways. For retention, a TTL index deletes documents after an age, in the background. The TTL monitor runs about once a minute, so expiry is not exact, and a big backlog of expired documents still means a lot of deletes and replication traffic. For time-ordered data such as metrics and events, time series collections (MongoDB 5.0+) store documents in time buckets internally. When one server is not enough, sharding splits a collection across machines, which is partitioning across servers.

// expire events 90 days after created_at
db.events.createIndex({ created_at: 1 }, { expireAfterSeconds: 90 * 24 * 3600 })

// or a time series collection with the expiry built in
db.createCollection("metrics", {
  timeseries: { timeField: "ts", metaField: "host", granularity: "minutes" },
  expireAfterSeconds: 90 * 24 * 3600 })
Follow one query

The dashboard, before and after

The dashboard asks for the last 24 hours of events for one account. Before partitioning, the planner walks the (account_id, created_at) index of one 2-billion-row table. After, the plan touches one partition, a few hundred million rows smaller, with an index a fraction of the size that is far more likely to stay in memory. The nightly cleanup goes from a long batch job to one DROP on the first of the month.

Now the catch. A support tool that searches events by payload with no date range used to use one index. Now it has to scan the same index in 90 partitions. Partitioning made the common query cheaper and the rare one more expensive. That is the trade every time. Check the queries that do not use the partition key before you commit to the design.

What to watch

Partitions fail on the calendar

  • Future partitions exist before they are needed. Alert if next month's partition is missing a week before the month starts.
  • The catch-all stays empty: pmax in MySQL, the DEFAULT partition in PostgreSQL.
  • Retention actually runs. A drop job that silently fails turns into a full disk months later.
  • Pruning still happens. Look at the plan of your top queries after any change to how the app filters by time.
  • Partition count. Hundreds are fine. Many thousands make planning slower in PostgreSQL and open many files in MySQL.

Next in this story: keeping a second copy of all this data in sync, and repairing it when it breaks.

Next · chapter 9ReplicasBuild one, and fix it when it breaks← Chapter 7: Change huge tables
Part 4 of 4 · Operate · 21 pagesAll pages

How do I run it in production? What to check when it is slow or broken, where it runs and what it costs, how big it must be, pooling, backups, security, upgrades and other changes made safely.