Scrivio Interview library
ScenarioIntermediate6 min read · updated 12 November 2026

A nightly job updates 10 million rows in a single @Transactional method. It holds locks for an hour and blocks daytime traffic when it runs late. How would you redesign it?

I would replace the single transaction with chunks: walk the table with keyset pagination and commit each chunk of about 1,000 rows in its own short transaction, ideally with one set-based UPDATE per chunk instead of loading entities. The job records the last processed key so it can restart where it stopped, it is throttled and scheduled away from peak hours with an eye on replication lag, and for anything bigger than a simple loop Spring Batch provides the chunking, progress tracking and restart for us.

Why this question is asked

Nightly jobs are written once, work fine on small data, and then quietly grow until one day they run into the morning and block customers. Interviewers ask this scenario because the fix touches transactions, locking, SQL and operations together. In this answer, we will see why one big transaction hurts, redesign the job step by step, show the code for keyset chunks and restart, and then look at throttling and Spring Batch.

1Why One Transaction for 10 Million Rows Hurts

When one transaction updates a row, it holds a row lock until it commits. A single @Transactional method that updates 10 million rows therefore holds up to 10 million row locks for an hour. Any daytime request that tries to update one of those rows waits for the whole job. If the job runs late, customers wait.

There are other costs too. If the job fails at row 9,999,999, everything rolls back and the next run starts from zero. With JPA, the persistence context keeps every loaded entity, so memory grows until the job slows or dies. The database must keep old row versions for the length of the transaction, which bloats tables, and a replica must replay one huge change at commit, so replication lag spikes.

2Chunks With Keyset Iteration

The core change is one transaction per chunk. Each chunk is small enough to commit in well under a second, so any row is locked only briefly.

To find the next chunk we use keyset pagination: remember the last id we processed and ask for rows with a larger id. OFFSET pagination would get slower with every page, because the database still has to walk past all the skipped rows, and it can skip or repeat rows when the data changes during the run. Keyset uses the primary key index and costs the same for chunk 1 and chunk 10,000.

Java
public void run() {
long lastId = progress.lastIdFor("reprice"); // 0 on a fresh run
while (true) {
final long after = lastId; // effectively final for the lambda
Long next = tx.execute(s -> repriceChunk(after));
if (next == null) break; // no rows left
lastId = next;
throttle.pause(); // e.g. 50 ms between chunks
}
}
private Long repriceChunk(long afterId) {
List<Long> ids = jdbc.queryForList(
"select id from product where id > ? and needs_reprice order by id limit 1000",
Long.class, afterId);
if (ids.isEmpty()) return null;
long last = ids.get(ids.size() - 1);
jdbc.update("update product set price = round(base_price * ?, 2), needs_reprice = false "
+ "where id > ? and id <= ? and needs_reprice", factor, afterId, last);
progress.save("reprice", last); // same transaction as the update
return last;
}
// 10,000 chunks, each ~50 ms; any row locked for well under a second
Step throughOne run of the chunked job
  1. Read last committed idFrom the progress table
  2. Select next 1,000 ids after itKeyset, uses the primary key
  3. Any rows found?
    YesContinueNoJob is finished
  4. Update chunk and save progressOne short transaction
  5. Pause brieflyThen go back to the select

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

A crash at any point resumes from the last committed chunk.

Notice that the progress record is saved in the same transaction as the chunk. If the job crashes, either both the chunk and its progress committed, or neither did, so the restart never skips or repeats a chunk.

3Set-Based Updates Instead of Entities

Loading 1,000 entities, changing them in Java and letting Hibernate flush 1,000 UPDATE statements is many times slower than one UPDATE statement that changes the same rows in the database. When the new value can be computed in SQL, as with a price formula, a set-based statement per chunk is the right tool. When the logic must run in Java, we still keep the chunk, use JDBC batching (hibernate.jdbc.batch_size) and clear the persistence context after each chunk so memory stays flat.

4Make It Restartable and Safe to Re-run

The progress table gives us restart: a failed run starts from the last committed id. It is also worth making each chunk idempotent, safe to run twice, as the needs_reprice flag does here: a row already repriced is no longer selected. Then even a manual re-run or an overlapping run cannot double-apply the change. To prevent two instances running at once, a database lock such as a PostgreSQL advisory lock, or a scheduler lock library such as ShedLock, keeps the job single.

5Throttle, Schedule and Watch Replicas

Even short transactions add load. A pause between chunks, or a limit of so many rows per second, keeps the job from saturating the database. The job should also check replication lag between chunks and slow down when lag rises above a threshold, because a replica that falls minutes behind serves stale data to readers. Finally, we schedule it for the quiet hours and give it a stop time: if it is not done by 6 am, it pauses and continues the next night from its saved position, rather than running into peak traffic.

6Using Spring Batch

Spring Batch is a framework built for exactly this. A chunk-oriented step reads items, processes them and writes them in chunks, with one transaction per chunk, and stores progress in its job repository tables so a failed job restarts from the last committed chunk. It also gives skip and retry policies for bad rows, and partitioning to run ranges in parallel.

Java
@Bean
Step repriceStep(JobRepository jobs, PlatformTransactionManager tx,
JdbcPagingItemReader<Product> reader, ItemWriter<Product> writer) {
return new StepBuilder("reprice", jobs)
.<Product, Product>chunk(1_000, tx) // check your version: newer releases offer chunk(size) with the manager set separately
.reader(reader) // keyset paging by id
.processor(this::reprice)
.writer(writer) // batched updates
.build();
}

For a simple set-based update, the hand-written loop above is enough. When there are several steps, skip rules, parallel partitions or operators who need to see and restart jobs, Spring Batch saves us from rebuilding all of that.

7Follow-up questions

What chunk size should we use?

Start around 1,000 rows and measure. The goal is a transaction that commits in tens to a few hundred milliseconds. Larger chunks reduce overhead but hold locks longer; very small chunks spend most of their time on commits.

What if the business needs the whole update to appear at once?

Then write the new values into a separate column or staging table in chunks, and switch over in one short final step, such as flipping a version flag or renaming a table. The heavy work is chunked and only the visible switch is atomic.

Why not just run the job with a lower isolation level?

Isolation does not change how long write locks are held. Every isolation level keeps row locks until commit, so only shorter transactions solve the blocking.

8Conclusion

In this answer, we saw that a single transaction over 10 million rows holds locks for its whole duration, cannot restart, and bloats memory, tables and replication. The redesign processes keyset chunks of about 1,000 rows, each in its own short transaction with a set-based update and its progress saved in the same commit. It is idempotent, single-instance, throttled, scheduled with a stop time and watches replication lag, and Spring Batch provides the same structure when the job grows.

What to say in the interviewAbout 90 seconds aloud

Open with

The problem is that one transaction holds a lock on every updated row until it commits, so for an hour any daytime request touching those rows waits. It also cannot restart, a failure at the end rolls everything back, memory grows in the persistence context, and the replica gets one huge change at commit.

Then, if they want more

I would redesign it as chunks. Walk the table with keyset pagination, where id is greater than the last processed id, order by id, limit 1,000, and process each chunk in its own transaction with TransactionTemplate. Where the new value can be computed in SQL, I would use one set-based UPDATE per chunk rather than loading entities.

In the same transaction I save the last processed id to a progress table, so a crash resumes exactly where it stopped, and I make the update idempotent, for example with a flag, so a re-run cannot apply it twice. A scheduler lock keeps one instance running.

Then operations: a short pause between chunks, a check of replication lag that slows the job down when replicas fall behind, a schedule in quiet hours and a stop time so it never runs into peak traffic.

If the job has several steps or needs skip and retry rules, I would use Spring Batch, which gives chunk transactions and restart out of the box.

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.
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 nightly job updates 10 million rows in a single @Transactional method. It holds locks...": https://scrivio-interview-library.netlify.app/databases/transactions/d57e2c99ba/