Cleanup cron jobs: batched deletes, archiving and partitions
Why one DELETE of millions of rows hurts the database, deleting in batches with one transaction each, archiving before deleting, DROP PARTITION, observing the job, and a complete purge job in Spring.
On this page
With soft deletes (flipping status to INACTIVE instead of removing the row), the table grows forever, indexes grow, and queries and backups slow down. This post writes a cron job that backs up and then hard deletes rows that have been INACTIVE for more than X months without hurting the production database. Scheduling (cron expressions, @Scheduled, ShedLock, idempotency) is covered in part 1.
1. The problem
A nightly job runs DELETE FROM orders WHERE status = 'INACTIVE' AND updated_at < now() - interval '6 months' on a 40-million-row table. The statement runs for 50 minutes, replicas fall 35 minutes behind, customers see stale orders on the history page, and at minute 50 it fails on a full WAL disk and rolls everything back.
2. Key idea
Clear the warehouse with small trucks, logging each trip before the next, instead of blocking the gate all day for one giant load.
One big DELETE |
Consequence |
|---|---|
| A very long transaction | locks rows, blocking other transactions |
| WAL/binlog piles up | replicas lag; the disk may fill |
| Version garbage | PostgreSQL leaves millions of dead tuples; InnoDB's undo log bloats |
2.1 Batches or partitions, archive where?
| Approach | Use when | Don't use when |
|---|---|---|
| Batched deletes | any table, business data | huge log tables already partitioned |
DETACH/DROP PARTITION |
logs, events, history partitioned by time | INACTIVE isn't tied to creation time |
| An archive table in the same DB | you need atomicity with the delete, SQL-based restore | the main DB is short on space |
On PostgreSQL, dropping a month of data (~65,000 rows): DELETE 316 ms, producing WAL and dead tuples; DETACH PARTITION 2 ms.
2.2 What you must have
- An index on the filter:
(status, updated_at)or a partial indexWHERE status = 'INACTIVE'; without it each batch is a full scan. - Foreign keys: delete child tables first; beware
ON DELETE CASCADEpulling tens of thousands of child rows into one transaction. - A time limit: stop after X minutes and continue next run; condition-based deletes are correct wherever they resume.
3. In Java
PostgreSQL archives and deletes in one statement with a data-modifying CTE; Java loops until nothing is left.
String sql = """
WITH batch AS (
SELECT id FROM products
WHERE status = 'INACTIVE' AND updated_at < ?
ORDER BY id LIMIT ? FOR UPDATE SKIP LOCKED),
moved AS (
INSERT INTO products_archive SELECT p.* FROM products p JOIN batch b ON b.id = p.id)
DELETE FROM products p USING batch b WHERE p.id = b.id""";
Instant deadline = clock.instant().plus(props.maxDuration());
int deleted;
do {
deleted = tx.execute(s -> jdbc.update(sql, cutoff, props.batchSize())); // one batch, one transaction
total += deleted;
Thread.sleep(100); // let replicas breathe
} while (deleted > 0 && clock.instant().isBefore(deadline));
log.info("purged {} rows from products", total);MySQL: DELETE ... ORDER BY id LIMIT 1000 works directly.
Finding oversized transactions in flight
- MySQL:
information_schema.innodb_trxhastrx_rows_modifiedandtrx_rows_locked. - PostgreSQL:
pg_stat_activityfor transaction age;pg_stat_user_tables.n_dead_tupfor dead tuples awaitingVACUUM. - Replica lag:
pg_stat_replication.replay_lagorSHOW REPLICA STATUS(Seconds_Behind_Source). The job should read it and lengthen its pauses as lag grows.
4. Working with AI
Give the AI: the batching loop, migrations adding the index and archive table, tests on large data.
Check in AI-written code:
- No single
DELETEfor all old data. - Archive and delete share a transaction (or the file and row count are confirmed before deleting).
- An index matches the filter.
- There's a total time limit and a last-success metric.
5. Exercises
Exercise 1: A June 1 job
Task: write a job that runs at 00:00:00 on June 1 every year to delete INACTIVE records across the system's tables. Write the cron expression and config, and say what you'd propose to whoever asked for it.
Solution to Exercise 1
Spring cron: 0 0 0 1 6 * with zone = "Asia/Ho_Chi_Minh"; the next runs are 01/06/2026, 01/06/2027...
jobs:
purge-inactive:
cron: "0 0 0 1 6 *"
zone: "Asia/Ho_Chi_Minh"
retention: P6M
batch-size: 1000
max-duration: PT2H@SchedulerLock(lockAtMostFor = "PT3H")is longer thanmax-durationso the lock can't expire while the job runs.- Tables are listed children first; each runs the loop from section 3.
- Proposal:
@Scheduleddoesn't catch up, so if the app is mid-deploy on the night of May 31, you wait 12 months. Run nightly (0 0 2 * * *) with the same "INACTIVE for over 6 months" condition: small deletes, even load, and a missed night is covered the next. If the business truly needs June 1, ask why (which regulation?).
Exercise 2: A silent job
The DB size dashboard has grown steadily for 3 months; nobody saw cleanup job errors in the logs. It turns out the job hasn't run since a cron config change. Why did nobody notice, and what do you add?
Solution to Exercise 2
Error-based alerts never fire when a job doesn't run: no run means no error to log. Add a dead man's switch: the job writes job_last_success_timestamp on success; alert when now() - job_last_success_timestamp > 25h. Add a rows_deleted_total metric to spot a job that runs but deletes nothing (wrong condition, wrong index).
Summary
- Never delete millions of rows with one
DELETE. - Delete in batches, one short transaction each, with an index.
- Archive and delete in the same transaction.
- For time-partitioned tables,
DROP PARTITION. - Alert on the last success; prefer nightly data-driven jobs.
Read more: Cron expressions and @Scheduled.
Practice interview questions on this topic
- How would you delete 50 million old rows from a live production table?
- How do Counter, Gauge and Timer differ in Micrometer? How would you set metrics and alerts for a payment API?
All Data Modeling & Scaling questions →All Spring Boot questions →
Comments
Community rules