Splitting an Elephant, Elegantly
If you delete a billion rows from a Postgres table, the table doesn’t get smaller. It gets bigger, at least for a while, and also slower.
It’s not an optimization issue, it’s instead how the database is supposed to work. And it was the first of several things I had wrong about a table that had been quietly growing for years, on the payment path of a service I work on, until it held more than two billion rows.
This post is about how I bounded it without taking anything down, and about the approach I took. Let’s dive deeper!
The session record
Picture a checkout page. Before you see it, something has to exist on the server: a row holding the state needed to render that page, process it, and start the payment. Call it a session record.
The row is written once, read a handful of times over the following minutes, and after the payment completes it’s likely operationally dead. So how long should it live?
Well, nobody asked. There was no retention policy, there was no cleanup job, and there never had been. Years later, the answer was two billion rows and counting.
To get things straight right away, cost wasn’t the motivation: our AWS billing is arranged in a way that made the storage cost genuinely irrelevant. I want to be precise about that, because it changes which solutions are allowed.
What actually concerned me:
- The data seemed to have no meaning beyond the payment window. A record whose payment finished months ago cannot affect any decision the service makes today. We kept it because nothing had ever deleted it.
- Recovery time scales with the table. This is the one that matters. Restoring a backup, rebuilding a logical replica,
pg_dumpfor a migration, autovacuum,REINDEX: all of them get slower as the table grows, and all are things you want to be fast on the day you actually need them. An unbounded table on a critical path quietly extended the worst-case recovery. - Every index covers the full table. We paid for index maintenance on all 2B rows forever, including the 99.9% that will never be read again.
The goal was to put an upper bound on the table, so that its size is no longer the bottleneck.
Why you can’t just delete it
The obvious move is a scheduled DELETE of old rows. Though at this scale it’s the wrong instrument:
DELETEdoes not free space, it marks tuples dead. Reclaiming requiresVACUUM, which on a table this size is a heavy background load.- It bloats indexes rather than shrinking them, so the index-maintenance cost stays.
- Deleting billions of historical rows is a long-running batch job that must be babysat.
An alternative is a DROP TABLE on a partition. Effectively instant, returns the space, leaves no bloat and nothing to vacuum. That points at RANGE partitioning with a retention window.
Except now you have to answer two questions, and the second one is where this story stops being about Postgres.
How long is long enough?
Before designing anything, there were two things I had to settle: what to partition by, and how long to keep the data. Neither is a number you get to guess. Guess too long, and you haven’t solved anything. Guess too short, and you break something in production for a customer, which in payments isn’t a thing you get to undo.
So I went to our analysts for two distributions of how the data is actually used, and worked back from there.
How long after creation is a record still being touched? Successful reads aren’t logged anywhere specifically, so we used a proxy from the table itself: the gap between updated_at and created_at, since every meaningful interaction bumps it. Across about 1.86 billion records:
| Still updated after… | Records |
|---|---|
| 7 days | 0.029% |
| 30 days | 0.020% |
| 90 days | 0.011% |
| 180 days | 0.0053% |
| 1 year | 0.00036% |
As the results showed, 99.92% of these records are never updated again after the day they’re created. The median, the 90th percentile and the 99th percentile of that gap are all zero days.
So the answer is just a day or days. Keep a week and you’re safe. Except that’s the wrong answer.
How long after a checkout do we see a repeat submission for the same reference? Repeat submissions are rare, a fraction of a percent. But when they come, roughly 95% arrive within three months of the original checkout, and most of those land in the first two. Almost none arrive the same day.
The two distributions didn’t agree. The record stops being read within days. But a merchant can come back and re-submit the same thing a month or two later. The window was never set by how long the data stays useful. It was set by how long someone might show up asking about it… again.
Three months, then. With monthly partitions, that cuts the table by about 92%.
Which raises the obvious follow-up: what happens to the 5% that arrive later than three months? Hold that thought, it comes back later.
Choosing a partition key
Before that, the other question: what do you partition by?
RANGE partitioning needs a key that carries time. Partitioning by a random identifier would have led to a potential issue I wanted to avoid: every row would land in the catch-all DEFAULT partition.
On a different table, about 14.5 million rows had collected in a DEFAULT partition, and cleaning it up locked the table for roughly a minute. Here’s why: to attach a new partition, Postgres has to scan the entire DEFAULT partition and prove that none of its rows belong in the new range. It holds an ACCESS EXCLUSIVE lock the whole time it does that. The bigger DEFAULT gets, the longer every query queues up behind it. Adyen wrote about hitting this as well.
I went with UUID v7, which embeds a millisecond timestamp in the high bits. And that’s why there had to be a second table.

The two billion rows already sitting there carry v4 ids with no time inside them, and you can’t retrofit that. Only rows created from now on can be partitioned by their id, so the partitioned table has to start out empty.
CREATE TABLE sessions_v2
(
guid UUID NOT NULL,
data JSONB,
-- ... the rest of the payload
PRIMARY KEY (guid)
)
PARTITION BY RANGE (guid);
SELECT partman.create_parent(
p_parent_table := 'public.sessions_v2',
p_control := 'guid',
p_interval := '1 month',
p_time_encoder := 'partman.uuid7_time_encoder',
p_time_decoder := 'partman.uuid7_time_decoder'
);
UPDATE partman.part_config
SET infinite_time_partitions = true,
retention = '3 months',
retention_keep_table = true
WHERE parent_table = 'public.sessions_v2';Two of those settings are worth pausing on. infinite_time_partitions matters because the table starts out empty, and without it pg_partman stops creating partitions in advance, which drops new rows straight into the DEFAULT partition we just went to all this trouble to avoid. And retention_keep_table = true makes the irreversible step reversible while you’re still learning: instead of dropping an expired partition, it detaches it. Get the window wrong and you reattach a table instead of explaining a data loss. I only switched it to false after watching it run for real.
Why nothing could be deleted
Now back to that thought we were holding. One existing constraint made me spend a bit more time on the design.
The service guarantees one checkout per (merchant reference, account), permanently. Merchants use their own identifiers to look the data up later, so this is effectively a merchant-supplied idempotency key: re-submit the same reference, and you must get the same checkout back, never a second one.
That constraint is what kept the payload alive. You cannot expire rows that a permanent uniqueness guarantee depends on, and it does not survive partitioning anyway: a unique index on a partitioned table must include the partition key.
In the current state of the system, idempotency keys have to live forever and the payload they protect does not, so we split them:

The ledger is narrow and keeping it forever is the irreducible cost of a permanent guarantee. The payload table then carries no unique constraint at all and can be partitioned and dropped freely.
CREATE TABLE session_keys
(
merchant_ref VARCHAR NOT NULL,
account_id INTEGER NOT NULL,
guid UUID NOT NULL,
PRIMARY KEY (merchant_ref, account_id)
);One consequence worth naming: once a payload is expired, the key remains but the session behind it is gone. An ancient merchant reference is still recognized as used; its details are not recoverable. That is exactly what the retention analysis above said we could afford.
Moving the rows
The old table was 2B+ rows on a hot path, so copying it wasn’t an option.
The new tables started empty and took over live traffic in stages, each behind its own feature flag: first writing to both tables at once, then reads preferring the new table and falling back to the old one, then reads served by the new table alone.
There was no backfill at all. Instead of moving the old rows, we waited. Old records aged past the point where anyone would read them, the read metrics confirmed the new table was serving effectively everything, and only then did the writes to the old table stop.
Dropping it happened in two moves. First a rename, which is instant and trivially reversible, so anything still pointing at the table announced itself immediately. Only then did the table actually get deleted.
The warehouse
The part with the most ways to lose data silently was the pipeline behind the data, not even the database itself. Analytics reads the warehouse, the warehouse is fed from this table, and a table rename or any disturbance in the data it accumulates would break that feed.
So after giving it some thought, I took it to the data engineering team with a concrete plan, and wrote the Airflow DAGs.
During the migration, both tables replicate into the warehouse in parallel: the old table into its existing destination, the new table into a new one. Two independent streams, and no cutover risk yet. There is nothing to backfill on the new side, because it starts empty, and the old table is still written exactly as before.

After the service stops writing to the old table, its destination stops changing and becomes a complete historical record: with nothing new arriving, there is nothing left to replicate. The new destination carries everything from the migration forward.
The last step merges the new stream back into the original destination, so the two halves become one continuous table under the name analysts already query. The temporary destination has done its job by then and gets dropped.
The merge is where the care goes, because the two halves overlap rather than meet end to end. For the whole dual-write window the same sessions sit in both destinations, so appending one to the other would count them twice. Every session carries a single stable identifier, though, so the merge deduplicates on it and the overlapping rows collapse into one copy instead of becoming duplicates. Only then did we compare the two sides, checking row counts and looking explicitly for duplicates and for gaps at the seam, and only after that did anything get dropped.

The naive direction would be to keep the new table as the source of truth and leave analysts to union the old one, which quietly breaks every query and automation. However, merging the other way means the rename never reaches anyone downstream, and this way the migration is invisible.
Results
No downtime. No incident. No alert fired, and no anomaly reported by anyone downstream. The query latencies and the endpoint’s success rate stayed inside their existing baselines the whole way through.
I want to be careful here, because there’s a claim I’m not going to make. I’m not going to tell you that not a single row was lost, because at this volume a handful of stragglers would never show up in aggregate metrics, and I’d rather tell you where my evidence stops than pretend it goes further than it does.
What I’ll say is that the design is what makes that acceptable. At every single stage, the irreversible step was hiding behind a reversible one. Detach before drop. Rename before drop. Fallback before read-only. A feature flag that fails back to the old behavior rather than into the dark.
As a bonus, lookups got faster, which showed up in a load test afterward.
Thanks for reading!
