Full answer
Batched delete pattern:
text
DELETE FROM events WHERE id IN (
SELECT id FROM events WHERE created_at < '2025-01-01' ORDER BY id LIMIT 5000);Repeat until no rows are affected, committing each batch and sleeping briefly. Each batch is a short transaction, replicas keep up, and vacuum can reclaim space as the job progresses.
Better long-term options:
- Time partitioning, where retention becomes
DROP TABLE events_2024_12, an instant metadata change. - Keep-and-swap: when most rows go,
CREATE TABLE events_new AS SELECT ... WHERE created_at >= ..., add indexes, then rename in a short transaction.
Monitor replica lag and disk during the job, and run it off-peak.
Key points
- Huge deletes cause long locks and log bursts
- Batch by key with commits
- Partitions make retention instant
- Keep-and-swap when most rows go
- Watch replica lag during the job
Common mistakes
- One DELETE for millions of rows
- Batches by OFFSET, which slow down as they go
Follow-ups
- Why order the batch by primary key?
- How would you throttle the job automatically?
Tips
- Prefer partitions for recurring retention