Scrivio Interview library
DebuggingIntermediate7 min read · updated 12 November 2026

A nightly job runs DELETE FROM events WHERE created_at < now() - interval '90 days' on a 2 billion row PostgreSQL table. It runs for hours, replicas fall behind and the table never shrinks on disk. What is happening and what would you change?

One DELETE of hundreds of millions of rows locks every row it removes, writes a huge amount of WAL that replicas replay slowly, and leaves dead tuples that vacuum must clean up; that space is reused by later inserts but never returned to the operating system unless VACUUM FULL or pg_repack rewrites the table. I would delete in small batches by primary key range with pauses, or better, partition the table by time so old data is removed with an instant DROP or DETACH of a partition. I would also check autovacuum settings, long-running transactions that block cleanup, and foreign keys pointing at events whose referencing columns lack indexes.

Why this question is asked

Retention jobs are a classic source of night-time incidents. They start when the table has a few million rows, run in seconds, and nobody looks at them again. Two years later the same DELETE runs on 2 billion rows, lasts for hours, makes every replica fall behind, and the table keeps its size on disk anyway, so the team wonders what the job is even achieving. Interviewers ask this because the explanation needs a real understanding of PostgreSQL's MVCC storage, and the fix changes how we design time-based tables. In this answer, we will recap how a delete works in PostgreSQL, explain each symptom, then look at batching, partitioning, vacuum and foreign keys.

1A Quick Recap of What DELETE Does in PostgreSQL

PostgreSQL uses MVCC, multi-version concurrency control: rows are never changed in place. A DELETE does not remove the row from the page. It marks the row version as deleted by our transaction, so other transactions that started earlier can still see it. Only later, when no transaction can possibly need the old version any more, does VACUUM mark that space as free for new rows.

Every change is also written to the write-ahead log (WAL) before it reaches the table, so that the database can recover after a crash, and replicas receive this WAL stream and replay it to stay in sync. So deleting a row costs a row lock, a WAL record and later some vacuum work. With 180 million rows to delete each night, each of these costs becomes large.

2Why the Job Takes Hours and Replicas Fall Behind

The single DELETE has to find, lock and mark every row older than 90 days in one transaction. It writes WAL for each row, and in the first change of each page after a checkpoint, a full copy of the page, so the WAL volume can reach tens of gigabytes. The primary writes that WAL with many parallel processes, but a replica applies it with a single startup process, so the replica falls behind and reads on it return stale data. If the job fails after three hours, everything is rolled back and nothing has been deleted at all.

There is a second cost. While this transaction is open, its snapshot is old, and vacuum cannot remove any dead rows anywhere in the database that are newer than that snapshot. So the long DELETE also slows down cleanup of unrelated busy tables, which then bloat.

3Why the Table Never Shrinks

After the delete commits, the dead row versions remain in the pages until vacuum runs. Plain VACUUM, and autovacuum, which runs it automatically, marks the space as reusable and records it in the free space map. New inserts then fill those gaps. But vacuum only gives space back to the operating system when completely empty pages sit at the very end of the file, which with time-ordered data rarely happens at the right end. So the file stays the same size, and new rows reuse the holes.

SQL
SELECT pg_size_pretty(pg_total_relation_size('events')); -- 1400 GB before the job
DELETE FROM events WHERE created_at < now() - interval '90 days';
VACUUM events;
SELECT pg_size_pretty(pg_total_relation_size('events')); -- 1400 GB: space is free inside, not returned
-- Only a rewrite returns the space
VACUUM FULL events; -- ACCESS EXCLUSIVE lock for the whole rewrite: an outage
-- pg_repack -t events -- extension that rewrites online with brief locks

This is usually fine: if the table reaches a steady state where nightly deletes free roughly what the next day inserts, the disk size stays flat. If the table must actually shrink, VACUUM FULL rewrites it compactly but holds an ACCESS EXCLUSIVE lock throughout, and pg_repack achieves the same with only short locks at the start and end, at the cost of temporary extra disk space.

4Fix 1: Delete in Batches

The quickest improvement is to replace one huge transaction with many small ones. Each batch deletes, for example, 10,000 rows by primary key, commits, and pauses briefly, so WAL arrives at a rate replicas can follow, locks are short, vacuum can work between batches, and a failure only loses one batch.

SQL
-- Repeat until 0 rows are deleted; pause 100 ms or until replica lag is under 5 s
DELETE FROM events
WHERE id IN (
SELECT id FROM events
WHERE created_at < now() - interval '90 days'
ORDER BY id
LIMIT 10000
);
-- DELETE 10000 ... DELETE 10000 ... DELETE 0

This needs an index on created_at, otherwise each batch scans to find old rows. Batching does not reduce the total work, but it spreads it out and makes it safe. For 2 billion rows and a steady daily volume, though, there is a far better design.

5Fix 2: Partition by Time and Drop Old Partitions

If the events table is partitioned by month or by day, each partition is a separate physical table holding one period. Removing 90-day-old data is then removing a whole partition, which is a metadata operation: no row-by-row delete, almost no WAL, no dead tuples, and the files are deleted, so disk space really is returned at once.

SQL
CREATE TABLE events (
id bigint GENERATED ALWAYS AS IDENTITY,
created_at timestamptz NOT NULL,
payload jsonb,
PRIMARY KEY (id, created_at) -- the key must include the partition column
) PARTITION BY RANGE (created_at);
CREATE TABLE events_2026_11 PARTITION OF events
FOR VALUES FROM ('2026-11-01') TO ('2026-12-01');
-- Retention: instant, no WAL storm, space returned to the OS
ALTER TABLE events DETACH PARTITION events_2026_07 CONCURRENTLY; -- PostgreSQL 14+
DROP TABLE events_2026_07;
Removing 90-day-old events
ApproachWAL writtenDurationDisk returned
One DELETEtens of GBhours, all or nothingNo
Batched DELETEsame total, spread outhours, restartableNo
DROP old partitionalmost nonemillisecondsYes, immediately

DETACH PARTITION CONCURRENTLY avoids blocking queries on the parent table, and a separate DROP removes the files. Some teams keep the detached partition for a while, or archive it to object storage before dropping it. Tools such as pg_partman automate creating future partitions and dropping old ones.

6Vacuum, Long Transactions and Foreign Keys

Whatever we choose, I would check autovacuum for this table. With 2 billion rows, the default autovacuum_vacuum_scale_factor of 0.2 means vacuum waits until 400 million rows are dead, which is far too late; a per-table setting such as 0.01, or a fixed threshold, keeps cleanup regular. I would also look for long-running transactions in pg_stat_activity, such as an idle in transaction session from a misbehaving client or an analytics query running for hours, because they hold back cleanup for the whole database.

Finally, foreign keys: if another table, such as event_attachments, references events with ON DELETE CASCADE or a plain foreign key, every deleted event triggers a lookup in the child table. Without an index on event_attachments.event_id, each lookup is a sequential scan of that table, so deleting 180 million events means 180 million scans. PostgreSQL does not create indexes on referencing columns automatically, so this is a common hidden cause of slow deletes.

7Follow-up questions

How would you convert this table to partitions without downtime?

One approach avoids copying the old data. We create a new partitioned table, rename the current events table to events_legacy, add a CHECK constraint on events_legacy that matches its time range, created NOT VALID and then validated without blocking writes, and attach events_legacy as one big partition covering everything before the cut-over date; the validated CHECK lets PostgreSQL skip the scan on attach. The rename and attach happen in one short transaction. New data goes into proper monthly partitions from then on, and after 90 days the whole legacy partition is older than the retention period and can be dropped in one step. The primary key must include created_at, so the application and foreign keys need checking first.

8Conclusion

In this answer, we saw that a single huge DELETE in PostgreSQL locks rows, writes massive WAL for replicas to replay, holds back vacuum and leaves dead tuples whose space is reused but not returned to the operating system without VACUUM FULL or pg_repack. Batching by primary key makes the job safe, partitioning by time and dropping old partitions makes it nearly free, and tuned autovacuum, no long transactions and indexes on referencing foreign key columns keep it healthy.

What to say in the interviewAbout 80 seconds aloud

Open with

The single DELETE is the problem. In PostgreSQL a delete doesn't remove rows; it marks each row version dead, takes a row lock, and writes WAL for every row, so one statement deleting hundreds of millions of rows runs for hours, generates huge WAL that replicas replay with a single process so they fall behind, and its long transaction blocks vacuum across the database.

Then, if they want more

If it fails, it all rolls back. The table doesn't shrink because VACUUM only marks dead space as reusable for future inserts; it doesn't give it back to the OS except for empty pages at the end of the file. Only VACUUM FULL, which locks the table, or pg_repack, which works online, rewrite it.

As a quick fix I'd delete in batches of about 10,000 rows by primary key, each in its own transaction, pausing on replica lag, with an index on created_at. The real fix is partitioning by time, so retention becomes detaching and dropping an old partition: instant, almost no WAL, and space is returned immediately.

I'd also lower the table's autovacuum scale factor, look for long-running or idle-in-transaction sessions, and check foreign keys referencing events, because a missing index on the referencing column makes each deleted row scan the child table.

About this answer

Last updated
12 November 2026
Versions it names
PostgreSQL 14
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A nightly job runs DELETE FROM events WHERE created_at < now() - interval '90 days' on a...": https://scrivio-interview-library.netlify.app/databases/sql-fundamentals/614626f0d6/