Quick revision
The short answer
First we make sure every child foreign key column is indexed, otherwise each parent delete scans all five child tables. Then we delete in small batches, for example 1,000 to 10,000 rows per transaction ordered by primary key, deleting children explicitly before parents so no cascade hides a huge transaction, and we pause between batches so replicas catch up. A lock_timeout makes the job give up and retry instead of blocking the application, and for time-based data we move towards partitioning so future cleanup is a DROP or DETACH PARTITION.
What to remember
In this answer, we redid a 2 million row cleanup safely. We first checked that every child foreign key column was indexed, so deletes do not scan child tables. We deleted in small batches ordered by primary key, children explicitly before parents, with pauses and replica lag checks between batches. A lock_timeout made the job back off instead of blocking the application. And for time-based data, we moved towards partitioning so future cleanups become DROP or DETACH PARTITION instead of DELETE.
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.
First we make sure every child foreign key column is indexed, otherwise each parent delete scans all five child tables. Then we delete in small batches, for example 1,000 to 10,000 rows per transaction ordered by primary key, deleting children explicitly before parents so no cascade hides a huge transaction, and we pause between batches so replicas catch up. A lock_timeout makes the job give up and retry instead of blocking the application, and for time-based data we move towards partitioning so future cleanup is a DROP or DETACH PARTITION.
Why this question is asked
Data cleanups look like one-off scripts, so they rarely get the care that production code gets. Yet a single DELETE of 2 million rows across six tables is one of the heaviest operations we can run against a live database: it locks rows, generates a flood of WAL, and holds everything in one transaction until the end. Interviewers ask this scenario to see whether we can explain why the first attempt hurt production and how to redo it safely. In this answer, we will look at why the first run caused lag and lock errors, check indexes on the children, design the batch loop, handle cascades and lock timeouts, and change the design so the next cleanup is trivial.
1Why the First Run Hurt Production
A single DELETE FROM parent WHERE created_at < '2024-01-01' runs as one transaction. Every deleted parent row is locked until the end, and with ON DELETE CASCADE every child row too, perhaps 10 or 20 million rows across five tables. Every one of those deletions writes WAL. Replicas replay WAL in a single process, so a burst of millions of changes takes them many minutes to apply: that is the 20-minute replica lag. Meanwhile, application requests that touch any locked row wait, and when they hit their own timeouts they fail.
If any child foreign key column lacks an index, it is far worse: the cascade must scan that child table once per deleted parent row. Two million parent rows times a full scan of a child table is effectively endless.
2Check the Child Indexes
Before anything else, we verify that every foreign key pointing at the parent has an index on its referencing column. PostgreSQL does not create these automatically.
3Delete in Small Batches
The core change is to split the work into many short transactions. Each batch selects a limited set of parent ids in primary key order, deletes their children explicitly, then deletes the parents, and commits. Ordering by primary key makes progress predictable and lets the job resume from the last id after a failure. Between batches the job sleeps, and it checks replica lag before continuing.
- Select next 5,000 parent idsORDER BY id, after last id
- Delete children explicitlyfive tables, indexed FK columns
- Delete parents and commitshort transaction
- Lock wait over 2 s?YesRoll back, back off, retry laterNoContinue
- Replica lag over 5 s?YesPause until it recoversNoSleep 200 ms, next batch
5 steps in order. Play them, or step through them one at a time.
Notice the batch size. 1,000 to 10,000 parent rows is a common range; the right number is the one that keeps each transaction under a second or two and the WAL rate within what replicas can replay. We start small, watch lag and latency, and grow it. If a child has many rows per parent, such as audit entries, we may delete that child in its own smaller batches first. The job is also safe to stop and restart at any time, because each batch commits and the next one starts after the last deleted id.
4Make Cascades Explicit
ON DELETE CASCADE is convenient for single rows but dangerous for bulk work, because one parent delete may hide thousands of child deletes inside the same statement. By deleting children ourselves, in batches, we see and control the real size of each transaction. The cascade then has nothing left to do; it stays in place as a safety net for normal application deletes.
5Never Block the Application
A cleanup job must lose every fight with real traffic. lock_timeout, set per transaction with SET LOCAL, makes a statement fail if it waits longer than the limit for a lock, instead of queueing up and making application requests queue behind it. The job catches that error, rolls back the batch, waits a little and retries. We also keep statement_timeout as a ceiling, run the job in quiet hours, and announce it to the owning teams so unusual lock errors are recognised.
6Design So the Next Cleanup Is Trivial
Many cleanups remove data by time: closed accounts older than five years, events older than 90 days. If the tables are partitioned by that time, removing a period is DETACH PARTITION and DROP TABLE, a metadata operation that takes milliseconds and generates almost no WAL, instead of millions of deletes. Parent and child tables partitioned on the same time key can be dropped together. Partitioning is a bigger change, but for data with retention rules it turns a risky job into routine housekeeping.
7Follow-up questions
How do you know the right batch size?
By measuring rather than guessing. We start with something small, such as 1,000 parent rows, and look at how long each batch takes, how much replica lag grows, and whether application latency changes. If everything stays flat, we double it and measure again. The goal is short transactions, about a second, and lag that returns to near zero between batches.
Why not just run the big delete at night?
Because the problems are not only about traffic. One 2 million row transaction still produces a burst of WAL that replicas need many minutes to apply, still holds millions of locks until the end, and if it fails after an hour, everything rolls back and the time is lost. Batches give steady load, partial progress and a safe stop at any point.
8Conclusion
In this answer, we redid a 2 million row cleanup safely. We first checked that every child foreign key column was indexed, so deletes do not scan child tables. We deleted in small batches ordered by primary key, children explicitly before parents, with pauses and replica lag checks between batches. A lock_timeout made the job back off instead of blocking the application. And for time-based data, we moved towards partitioning so future cleanups become DROP or DETACH PARTITION instead of DELETE.
Open with
The first run failed because it was one huge transaction. Two million parent deletes with cascades into five child tables locked millions of rows until commit and produced a burst of WAL that replicas replay in a single process, hence 20 minutes of lag, and application requests waiting on those locks timed out.
Then, if they want more
To redo it, I would first check that every child foreign key column has an index, because PostgreSQL does not create them, and without one each parent delete scans the child table.
Then I would batch: select a few thousand parent ids in primary key order after the last processed id, delete the children explicitly in the same transaction, then the parents, and commit. Between batches I would sleep briefly and check replica lag, and wait if it goes above a few seconds.
Deleting children explicitly matters because a cascade hides an unknown number of child deletes inside one statement. I would set lock_timeout per transaction, around two seconds, so if the job meets an application lock it gives up, rolls back that batch and retries later, instead of making users wait. The job would be restartable from the last id.
And for the future, if the data is removed by age, I would partition the tables by time so the next cleanup is just detaching and dropping a partition.
About this answer
- Last updated
- 12 November 2026
- 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 "During a data cleanup, a batch job deletes 2 million rows from a parent table with five...": https://scrivio-interview-library.netlify.app/databases/indexing/1d698b0e72/