Video in progress

You need to update or delete 30 million rows in a big table. How do you do it without taking prod down?

Instead of one huge query, I split it into small batches and run each in its own transaction. That keeps locks short, WAL and replica lag under control, and lets VACUUM work in between. I pause between batches and watch the job.

📖 Answer

What a single UPDATE orders SET ... WHERE ... does to 30 million rows:

  • a transaction open for hours, so VACUUM stops across the whole database;
  • 30 million rows get locked, and the application's writes to those rows wait;
  • tens of GB of WAL at once: replicas fall behind, and the disk may fill up;
  • if it fails at the end, everything rolls back and the work is wasted.

With batches, moving forward by key:

-- one batch per call; the application or a script calls it in a loop
WITH batch AS (
    SELECT id FROM orders
    WHERE id > :lastId AND status = 'LEGACY'
    ORDER BY id
    LIMIT 5000
)
UPDATE orders o SET status = 'ARCHIVED'
FROM batch
WHERE o.id = batch.id
RETURNING o.id;

The largest id returned becomes the next :lastId. Don't use OFFSET: every later batch gets slower.

What I add in practice:

  • I pick the batch size by measuring: one batch should take around 100-500 ms;
  • a short sleep between batches and a check of the replica lag; if the lag goes over the limit, I pause;
  • an idempotent condition (status = 'LEGACY') so the job can continue if it's restarted;
  • if the delete is big, I do it at night and then run VACUUM (ANALYZE).

If a large part of the table has to be deleted, another way is cheaper: copy what must stay into a new table and swap the names. If deleting by time is routine, that's a signal to move to partitioning.