← Back to SQL, page 19

sql-0365 · Medium mid

Deleting 50 million old rows in one statement caused replica lag and a full disk. How should it be done?

A single huge DELETE holds locks for a long time, writes a burst of log that replicas must replay, and leaves dead rows until vacuum. Delete in batches of a few thousand rows by key range with pauses, or, better, partition by time and drop old partitions. For a full purge, copy the rows to keep into a new table and swap.

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