Scrivio Interview library
ScenarioIntermediate8 min read · updated 12 November 2026

A tasklet step runs DELETE FROM audit_log WHERE created_at < now() - interval '1 year' and fails after 50 minutes with a transaction timeout, leaving locks and replica lag. How would you redesign it?

The step fails because one DELETE of a year's worth of rows runs as a single transaction: it holds locks for 50 minutes, produces a flood of WAL that the replicas must replay, and leaves millions of dead rows behind. We redesign it to delete in small batches, each in its own short transaction, by returning CONTINUABLE from the tasklet with progress saved for restart and a pause between batches. The best long-term fix is to partition audit_log by month and drop old partitions, which takes milliseconds.

Why this question is asked

Retention jobs look harmless: delete old rows, once a night. They usually start small and work fine, then the table grows for three years and one night the job runs for 50 minutes, times out, rolls everything back and leaves the replicas minutes behind. Interviewers ask this scenario because it tests whether we understand what a large transaction costs a database, not just how to write a tasklet. In this answer, we will see why the single DELETE fails, rewrite the tasklet to delete in batches with CONTINUABLE, make it restartable and gentle on replicas, and then look at partitioning, which removes the problem entirely.

1Why One Big DELETE Hurts

The original tasklet runs one statement, DELETE FROM audit_log WHERE created_at < now() - interval '1 year', inside the transaction that the tasklet step opens around execute. Suppose that matches 40 million rows. PostgreSQL has to find every one of those rows, mark each as deleted and write a record of each change to the write-ahead log, the WAL, which is the journal that crash recovery and replication are built on.

All of this happens in one transaction, so nothing is final until the very end. The locks on every deleted row are held for the whole 50 minutes, so any other statement that wants to update one of those rows waits. The WAL for 40 million deletions is shipped to the replicas, which replay it and fall behind, so reads served from replicas become stale. When the transaction timeout fires, PostgreSQL rolls back, and all the work is wasted, yet the WAL has already been written and shipped.

Even when such a delete succeeds, the table does not shrink. Deleted rows become dead tuples that only VACUUM can reclaim, and a huge burst of them at once leaves the table bloated and slow to scan until autovacuum catches up.

2Deleting in Batches With CONTINUABLE

The fix is to make the work many small transactions instead of one big one. A tasklet step already gives us that loop: each call to execute runs in its own transaction, and returning RepeatStatus.CONTINUABLE asks the step to commit and call again. So each call deletes at most 10,000 rows and returns CONTINUABLE, and the call that finds nothing to delete returns FINISHED.

Two details matter. First, we walk through the table by primary key range rather than repeating the same 'oldest rows' query, so each batch starts where the last one stopped and uses the index. Second, we fix the cutoff once, when the step starts, so the target does not move while the job runs.

Java
public class AuditPurgeTasklet implements Tasklet {
private static final String DELETE_BATCH = """
WITH batch AS (
SELECT id FROM audit_log
WHERE id > ? AND created_at < ?
ORDER BY id
LIMIT 10000),
gone AS (
DELETE FROM audit_log a USING batch b WHERE a.id = b.id
RETURNING a.id)
SELECT count(*) AS n, coalesce(max(id), 0) AS last_id FROM gone""";
private final JdbcTemplate jdbc;
private final Clock clock;
@Override
public RepeatStatus execute(StepContribution contribution, ChunkContext chunk) throws InterruptedException {
ExecutionContext ctx = chunk.getStepContext().getStepExecution().getExecutionContext();
if (!ctx.containsKey("cutoff")) {
ctx.putLong("cutoff", clock.instant().minus(Duration.ofDays(365)).toEpochMilli()); // fixed once
}
Timestamp cutoff = new Timestamp(ctx.getLong("cutoff"));
long lastId = ctx.getLong("lastId", 0L);
Map<String, Object> r = jdbc.queryForMap(DELETE_BATCH, lastId, cutoff);
long deleted = ((Number) r.get("n")).longValue(); // 10000
contribution.incrementWriteCount(deleted);
if (deleted == 0) {
return RepeatStatus.FINISHED; // nothing older than the cutoff is left
}
ctx.putLong("lastId", ((Number) r.get("last_id")).longValue()); // saved with this commit
Thread.sleep(200); // let replicas and vacuum keep up
return RepeatStatus.CONTINUABLE;
}
}
// call 1: deleted 10000, lastId 10482 -> CONTINUABLE
// call 2: deleted 10000, lastId 20977 -> CONTINUABLE
// ...
// call 4001: deleted 0 -> FINISHED
Step throughOne pass of the batched purge
  1. Begin transactionopened by the tasklet step
  2. Read cutoff and lastIdfrom the step's ExecutionContext
  3. Delete up to 10,000 rowsid > lastId and created_at < cutoff
  4. Any rows deleted?
    Yessave lastId, sleep 200 ms, return CONTINUABLENoreturn FINISHED
  5. Commitrows, counters and ExecutionContext saved together

5 steps in order. Play them, or step through them one at a time.

Notice what each call costs now. A transaction touches 10,000 rows, holds their locks for well under a second and writes a small slice of WAL. Other statements wait at most that long, and if anything fails, we lose one batch of work, not 50 minutes.

The query relies on two indexes: the primary key on id and an index on created_at. If old and new rows are mixed across the id range, the batch query still finds them through the created_at condition; if ids grow with time, as they usually do for an audit table, the walk is a clean range scan.

3Making It Restartable

The ExecutionContext is a small map that Spring Batch stores in the job repository, and a tasklet step saves it after every successful call. That is why we keep cutoff and lastId there. If the job is killed after batch 2,500, a restart of the same job instance reads the saved values, uses the same cutoff and continues from the saved id, instead of starting from scratch with a new cutoff.

Because each batch deletes rows and saves its progress in one transaction when the job repository and audit_log share a database and transaction manager, the two never disagree. If they are in different databases, the worst case is that the last batch is repeated, which is harmless here, since deleting rows that are already gone does nothing.

4Throttling to Protect Replicas and Vacuum

Batching limits the size of each transaction, but if we fire batches back to back, the total rate of WAL and dead tuples can still swamp the replicas. The simple throttle is a short pause between batches, 200 milliseconds in the example, which we tune by watching replica lag. A smarter throttle checks lag before each batch, for example by reading replay_lag from pg_stat_replication on the primary, and waits while it is above a limit such as 5 seconds.

Spreading the deletes also gives autovacuum the chance to clean dead rows as we go, so the space is reused by new audit rows instead of the table growing. We should also run the job at a quiet hour and set an explicit statement timeout for each batch, so a single slow batch fails fast rather than hanging.

5The Better Fix: Partition by Month and Drop Old Partitions

Deleting rows one by one is the slow way to remove data that is organised by time. PostgreSQL's declarative partitioning lets us split audit_log into one partition per month, each a separate table underneath. Retention then becomes 'drop the partitions older than a year', which removes a whole month of data as a metadata change, with no row-by-row WAL, no dead tuples and no bloat.

SQL
CREATE TABLE audit_log (
id bigint GENERATED ALWAYS AS IDENTITY,
created_at timestamptz NOT NULL,
payload jsonb,
PRIMARY KEY (id, created_at) -- the partition key must be part of the primary key
) PARTITION BY RANGE (created_at);
CREATE TABLE audit_log_2026_11 PARTITION OF audit_log
FOR VALUES FROM ('2026-11-01') TO ('2026-12-01');
-- monthly retention step:
ALTER TABLE audit_log DETACH PARTITION audit_log_2025_10 CONCURRENTLY; -- does not block readers
DROP TABLE audit_log_2025_10; -- milliseconds
Ways to purge a year of audit rows
ApproachLock timeWAL and bloatEffort
One DELETEwhole run (50 min)huge burst, heavy bloatnone, but it fails
Batched DELETE with CONTINUABLEunder a second per batchsame total, spread outsmall code change
Monthly partitions, DROP old onesbrief metadata lockalmost noneone-time migration

The cost is the migration: the existing table has to be moved into a partitioned one, usually by creating the new table, writing to it from a cutover date and copying older months in batches, and the primary key must include created_at. A tasklet step is still useful afterwards, creating next month's partition ahead of time and dropping expired ones. Note that DETACH PARTITION CONCURRENTLY cannot run inside a transaction block, so this tasklet must run those statements outside the step's transaction or through a separate connection with autocommit.

6Follow-up questions

Why not just raise the transaction timeout?

Because the timeout is a symptom. A longer timeout lets the transaction hold its locks even longer and produce the same flood of WAL, and the table keeps growing, so next year the job needs a longer timeout again. Small transactions fix the cause.

Would a chunk-oriented step be better than a tasklet here?

A chunk step reading ids and deleting them in chunks would also work, but it would load every id into the application and send deletes back, which is far more traffic than letting the database pick and delete each batch with one statement. For set-based database work, a CONTINUABLE tasklet is simpler and faster.

How do we know the replicas are keeping up?

On PostgreSQL we can read pg_stat_replication on the primary, which shows each replica's write, flush and replay lag, and alert when replay lag passes a limit. The purge job can read the same view and pause itself, which turns it into a polite background job rather than a nightly incident.

7Conclusion

In this answer, we saw that a single year-wide DELETE fails because it is one enormous transaction that holds locks, floods the WAL and bloats the table. We rewrote the tasklet to delete 10,000 rows per call by key range and return CONTINUABLE until a call deletes nothing, kept the cutoff and last id in the ExecutionContext so a restart resumes where it stopped, and paused between batches to protect replicas and vacuum. Finally, we saw that monthly partitions turn retention into dropping a partition, which is the best answer once the migration is done.

What to say in the interviewAbout 80 seconds aloud

Open with

The problem is that the whole purge is one transaction. Deleting a year of rows locks every one of them for the full 50 minutes, writes a huge amount of WAL that the replicas have to replay, which causes the lag, and leaves millions of dead tuples for vacuum, and when the timeout hits, it all rolls back.

Then, if they want more

I would turn it into many small transactions. The tasklet deletes up to 10,000 rows per call, walking the primary key range from the last id it deleted, and returns CONTINUABLE, so the step commits and calls it again; when a call deletes nothing, it returns FINISHED.

I fix the cutoff once and store it and the last id in the step's ExecutionContext, which is saved with each commit, so a restart resumes with the same target. Between batches I sleep a little, or better, check replica lag in pg_stat_replication and wait while it is high, so replicas and autovacuum keep up.

Longer term I would partition audit_log by month on created_at. Then retention is detaching and dropping the partitions older than a year, which takes milliseconds and produces no bloat. The migration is the cost, but it removes the problem for good.

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
Spring Batch reference
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 "A tasklet step runs DELETE FROM audit_log WHERE created_at < now() - interval '1 year'...": https://scrivio-interview-library.netlify.app/spring-boot/spring-batch/cc63f8338a/