Quick revision
The short answer
The goal is retention by DETACH PARTITION CONCURRENTLY and DROP TABLE, which takes seconds and leaves no bloat. We get there by creating a new partitioned audit_log, attaching the existing 4 TB table as one historical partition after adding a CHECK constraint that matches its range (so ATTACH skips the full scan), sending new writes to monthly partitions, and letting the old partition age out or be split later. Before the switch we check pruning, indexes, foreign keys, sequences and ORM mappings, and we rehearse on a production-sized copy.
What to remember
In this answer, we saw why a nightly DELETE on a 4 TB table causes hours of work, bloat and replica lag, and that the goal is retention by detaching and dropping monthly partitions. The low-downtime path is to attach the existing table as one historical partition, using a validated CHECK constraint so ATTACH does not scan, and to send new writes to monthly partitions; a batch copy with dual writes is the slower alternative. We closed with the checks that matter: pruning, indexes on the parent, foreign keys, sequences, ORM mappings and a rehearsal on production-sized data.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
The goal is retention by DETACH PARTITION CONCURRENTLY and DROP TABLE, which takes seconds and leaves no bloat. We get there by creating a new partitioned audit_log, attaching the existing 4 TB table as one historical partition after adding a CHECK constraint that matches its range (so ATTACH skips the full scan), sending new writes to monthly partitions, and letting the old partition age out or be split later. Before the switch we check pruning, indexes, foreign keys, sequences and ORM mappings, and we rehearse on a production-sized copy.
Why this question is asked
A nightly DELETE on a huge table is a classic slow-burning problem. Each run marks millions of rows dead, vacuum has to clean them up, the table and its indexes bloat, and the WAL generated by the delete makes replicas fall behind. Interviewers use this scenario to see whether we know the target design and, more importantly, how to get there on a live 4 TB table without a long outage. In this answer, we will see why DELETE hurts, what the partitioned target looks like, the attach-the-old-table plan step by step, an alternative batch-copy plan, and the checks that make the switch safe.
1Why the Nightly DELETE Hurts
In PostgreSQL a DELETE does not free space immediately. It marks each row version as dead, writes a WAL record for it, and leaves the space for vacuum to reclaim later. Deleting one month of a 13-month, 4 TB table means touching about 300 GB of rows. That produces a huge amount of WAL, which replicas must replay, so they lag. Vacuum must then scan the table and every index to clean up. Even after vacuum, the freed space is reused only by new rows in the same table, so the files do not shrink and indexes stay bloated.
Partitioning changes the unit of retention. If each month is its own partition, removing a month is a metadata operation: detach the partition and drop its files. No per-row WAL, no dead rows, no vacuum debt.
2The Target Design
The target is a parent table audit_log partitioned by RANGE on created_at, with one partition per month, indexes declared on the parent so every partition gets them, and a scheduled job that creates future months ahead of time and removes expired months.
DETACH PARTITION ... CONCURRENTLY, available since PostgreSQL 14, takes only a weak lock on the parent, so queries and inserts continue while it runs. It cannot run inside a transaction block and cannot be used when the table has a default partition, which is one more reason to create partitions ahead of time instead of relying on a default.
3Plan A: Attach the Existing Table as One Partition
The fastest way to switch is to avoid copying 4 TB at all. We create the new partitioned parent and make the existing table its first partition, covering everything up to the start of the next month. The danger is that ATTACH PARTITION normally scans the whole table to prove every row fits the range, holding a lock while it does. We avoid that scan by first adding a CHECK constraint that states the same range. We add it as NOT VALID, which is instant, and then VALIDATE CONSTRAINT, which scans the table but only with a lock that still allows reads and writes. When ATTACH sees a valid constraint that proves the range, it skips its own scan.
- Add CHECK constraint NOT VALIDinstant
- VALIDATE CONSTRAINTscans 4 TB, writes continue
- Short transactionrename, create parent, attach legacy, create next month
- New writes go to monthly partitionsnightly DELETE switched off
- Legacy partition expires or is splitdrop whole after 13 months, or copy months out
5 steps in order. Play them, or step through them one at a time.
Only step 3 needs an exclusive lock, and it lasts milliseconds.
Notice what we gained. The switch itself is a short transaction that needs a brief exclusive lock, so we run it in a quiet minute with a lock_timeout so it gives up rather than queueing behind a long query. From that moment, new rows go to monthly partitions, and the nightly DELETE can stop. There is a catch: the legacy partition still holds 13 months, so we cannot drop it by month. Either we wait until it is entirely older than the retention period, about 13 months, and drop it whole, or we gradually move its months into proper partitions with batched copies, one month at a time, while the legacy table shrinks.
4Plan B: Copy History in Batches
Sometimes Plan A does not fit, for example because the primary key must change to include created_at and rebuilding the unique index on the legacy table is itself too heavy, or because we want proper monthly partitions for history from day one. Then we build the new partitioned table next to the old one and fill it in batches: copy a few hundred thousand rows per batch, ordered by id, throttled so replicas keep up. Meanwhile the application dual-writes new rows to both tables, or a trigger on the old table copies them. Reads can go through a view that unions both tables during the migration, then point at the new table when the copy is complete and verified. This is slower and generates a lot of WAL, but each step is small and reversible.
5Checks Before the Switch
Pruning first. A partitioned table helps only queries that filter on created_at. If the audit screens search by user_id with no date range, every partition is scanned, so we add a default date range to those queries, or accept it knowingly. Indexes come next: we create them on the partitioned parent so every new month gets them automatically, and we make the primary key include created_at, because unique constraints on a partitioned table must contain the partition key.
Then the surrounding objects. Foreign keys that reference audit_log must now reference the composite key, or be dropped if they only existed out of habit. If id comes from a sequence owned by the old column, we make sure the new parent uses the same sequence so ids do not restart. On the Java side, a JPA entity mapped to audit_log keeps working because the name is the same, but if we change the key, the @Id mapping must become a composite key with @IdClass or @EmbeddedId, or stay a single @Id if we only need uniqueness by convention (check how your Hibernate version handles that). Finally, we rehearse the entire plan on a restored production-sized copy, measuring how long VALIDATE takes and how much lag it causes, because a 4 TB table behaves very differently from a test database.
6Follow-up questions
Why not just run the DELETE in smaller batches?
Batching reduces lock times and replica spikes, but it still creates the same total number of dead rows, the same total WAL and the same vacuum work every night. It treats the symptom. Partitioning removes the work entirely, because dropping a partition does not touch rows.
Can we keep a default partition as a safety net?
We can, but it blocks DETACH PARTITION CONCURRENTLY and makes creating new partitions slower, because PostgreSQL must check the default for matching rows. A better net is a job that creates partitions three months ahead and an alert if creation fails.
How do we limit replica lag during VALIDATE or batch copies?
VALIDATE reads but writes little, so it mostly costs I/O. Batch copies write a lot, so we throttle them: small batches, a pause between them, and a check of replica lag (pg_stat_replication replay_lag) that pauses the job when lag passes a threshold such as 30 seconds.
7Conclusion
In this answer, we saw why a nightly DELETE on a 4 TB table causes hours of work, bloat and replica lag, and that the goal is retention by detaching and dropping monthly partitions. The low-downtime path is to attach the existing table as one historical partition, using a validated CHECK constraint so ATTACH does not scan, and to send new writes to monthly partitions; a batch copy with dual writes is the slower alternative. We closed with the checks that matter: pruning, indexes on the parent, foreign keys, sequences, ORM mappings and a rehearsal on production-sized data.
Open with
The real fix is to stop deleting rows and start dropping partitions. With monthly partitions, retention becomes DETACH PARTITION CONCURRENTLY and DROP TABLE, which takes seconds, generates almost no WAL and leaves no bloat.
Then, if they want more
To get there on a live 4 TB table I would avoid copying it. First I add a CHECK constraint on the existing table saying created_at is below the first day of next month, as NOT VALID, and then VALIDATE it, which scans the table but lets writes continue.
Then, in one short transaction with a lock timeout, I rename the table, create a new partitioned audit_log, attach the old table as a partition from MINVALUE to that date, which skips the scan because the constraint proves it, and create the next monthly partition. New writes then go to monthly partitions and the nightly delete stops.
The legacy partition either ages out as a whole after 13 months, or I move its months into proper partitions in throttled batches. If the key or structure has to change, the alternative is building the new table beside it, copying in batches while dual-writing, and switching reads through a view.
Before the switch I check that queries filter on created_at, create indexes on the parent, fix foreign keys and sequence ownership, check the JPA mapping, and rehearse everything on a production-sized copy.
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.
- Official documentation
- PostgreSQL documentation, MySQL reference manual
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 4 TB PostgreSQL audit_log table keeps 13 months of data. A nightly DELETE of old rows...": https://scrivio-interview-library.netlify.app/databases/partitioning-and-sharding/f38fe2e5cc/