Scrivio Interview library
ScenarioAdvanced6 min read · updated 12 November 2026

A team regularly runs large bulk updates and deletes through @Modifying queries on shared tables, and other services report lock waits and stale caches. What guidance would you give?

Bulk statements lock every row they touch until they commit, so we split them into batches of a few thousand rows with short transactions, schedule heavy runs off-peak and throttle them. Because they bypass the persistence context, entity listeners, versions and second-level caches, each of those must be handled explicitly. And for shared tables, changes should be announced and coordinated, ideally with one owning service per table, while we monitor lock waits and replication lag during every run.

Background to this question

A bulk update that touches a million rows is one line of code, which makes it easy to forget that it is also one very large transaction. When the table is shared with other services, that transaction blocks their writes, fills replicas with lag, and leaves their caches holding data that changed underneath them. This scenario tests whether we can explain the mechanics and also give a team guidance they can follow. In this answer, we will see why a single large statement causes lock waits, how to batch it, what else the statement silently skips, how to schedule and throttle the work, and how ownership of shared tables changes the picture.

1Why One Big Statement Blocks Everyone

When PostgreSQL or MySQL InnoDB updates or deletes a row, the transaction takes a row lock on it and holds that lock until commit. Readers are not blocked, because both engines use MVCC, multi-version concurrency control, where readers see the last committed version. But any other transaction that wants to update or delete one of those rows must wait.

A statement like delete from events where created_at < :cutoff that removes two million rows runs as one transaction. For the minutes it takes, every one of those rows is locked, so another service trying to update a single event waits for minutes too, and its connection pool fills with stuck requests. In MySQL, the gap locks InnoDB takes on index ranges at its default REPEATABLE READ level can even block inserts into the affected range.

Step throughA long bulk delete blocking another service
Cleanup jobDatabaseOrders service
delete 2,000,000 old events (one transaction)
update event 812 status
waits for the row lock
commit after 6 minutes
update succeeds after 6 minutes, or times out

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

2Batching With Short Transactions

The fix is to do the same work in small pieces, each committed on its own. Locks are then held for a fraction of a second per batch, and other transactions slip in between batches.

Java
@Modifying
@Query(value = """
delete from events
where id in (select id from events where created_at < :cutoff
order by id limit 5000)
""", nativeQuery = true)
int deleteBatch(@Param("cutoff") Instant cutoff); // PostgreSQL has no DELETE ... LIMIT
// Not @Transactional: each call gets its own transaction from TransactionTemplate
public void purge(Instant cutoff) throws InterruptedException {
int deleted;
do {
deleted = tx.execute(s -> repo.deleteBatch(cutoff)); // 5000, 5000, ..., 812, 0
Thread.sleep(200); // throttle: let others in
} while (deleted > 0);
}

Notice that the loop itself is not one transaction. If it were, wrapping it in @Transactional would bring back the original problem, because every batch's locks would be held until the end. The pause between batches is the throttle; we tune batch size and pause by watching lock waits and replication lag. With an index on created_at, each batch finds its rows quickly.

3Handle What the Statement Skips

Bulk statements, JPQL or native, bypass everything Hibernate does per entity. The persistence context of the running transaction is not updated, so we use clearAutomatically. Entity listeners and auditing do not run, so we set audit columns in the statement. The @Version column is not incremented, so we add version = version + 1 to updates if other code relies on optimistic locking.

Caches are the part other services feel. Hibernate invalidates its own second-level cache region after a JPQL bulk update, and all regions after a native one, but only inside our process. Another service with its own Hibernate cache, a Redis cache of products, or a search index fed from entity events knows nothing. That is the stale cache report. We either publish an event after each batch, such as a list of changed ids on a topic other services consume, or agree that consumers cache this table with a short time to live.

4Schedule, Throttle and Monitor

Heavy runs belong in quiet hours, with a time window they must finish in, and a kill switch, such as a feature flag the loop checks before each batch. During the run we watch lock waits, for example pg_locks joined with pg_stat_activity, or the wait events in performance_schema on MySQL, and replication lag on the replicas, because each batch must also be replayed there.

A useful rule is to make the job back off automatically: if replica lag goes above, say, 10 seconds, or if lock waits on the table pass a threshold, the loop sleeps longer or stops. That turns the job from a risk into a polite background task.

Step throughA safe bulk job loop
  1. Kill switch off and inside the time window?
    YesContinueNoStop and report progress
  2. Run one batch in its own transactionfor example 5,000 rows
  3. Publish changed ids for cachesevent or cache eviction
  4. Replica lag or lock waits too high?
    YesSleep longerNoShort pause
  5. Rows left?
    YesNext batchNoDone

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

5Ownership of Shared Tables

The deeper issue is that several services write the same table. Then a change by one team, a new bulk job, an index or a column, affects others without warning. Our guidance would be that every table has one owning service; other services read through its API or events, or at least read-only. Where sharing cannot be removed yet, bulk operations on shared tables are announced in advance in the channel the consuming teams follow, with the time window and the expected volume.

6Follow-up questions

How large should a batch be?

Large enough that the overhead per transaction is small and small enough that each batch commits in well under a second. A few thousand rows is a common start. We then measure: if lock waits or replica lag rise, we shrink the batch or lengthen the pause; if neither moves, we can grow it.

Is partitioning a better answer for deleting old data?

Often, yes. If events are partitioned by month, removing old data becomes dropping or detaching a whole partition, which is almost instant and creates no row locks or dead rows to vacuum. It needs a schema change, so it is a longer-term fix than batching.

Why not run the bulk job on a replica?

Replicas are read-only, so writes must go to the primary. What we can move to replicas are the heavy reads that sometimes accompany bulk jobs, such as selecting candidate ids for a report, while the writes stay batched on the primary.

7Conclusion

In this answer, we saw that large bulk statements hold row locks on every touched row until commit, which causes the lock waits other services report. We split the work into short batches with a throttle, handled the persistence context, listeners, versions and caches explicitly because bulk statements skip them, scheduled heavy runs off-peak with monitoring of lock waits and replication lag, and pushed for one owning service per table with announced changes where sharing remains.

What to say in the interviewAbout 80 seconds aloud

Open with

My first point would be that a bulk statement is one transaction, and it holds a row lock on every row it touches until it commits. So deleting two million rows in one statement blocks every other service that wants to write any of those rows for the whole run, which is exactly the lock waits they report.

Then, if they want more

I would ask the team to run these jobs in batches of a few thousand rows, each in its own short transaction, with a short pause in between, and not to wrap the loop in @Transactional, because that brings the big transaction back.

Second, bulk statements bypass the persistence context, entity listeners, versions and second-level caches, so each needs explicit handling: clearAutomatically, audit columns and version increments in the statement, and an event or eviction after each batch, because other services' caches never hear about the change.

Third, schedule heavy jobs off-peak with a kill switch, and watch lock waits and replication lag during the run, ideally with the job backing off automatically. And finally, shared tables are the root problem, so I would push for one owning service per table, and until then, announce bulk runs to the teams that depend on the table.

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 team regularly runs large bulk updates and deletes through @Modifying queries on...": https://scrivio-interview-library.netlify.app/databases/jpa-queries/c20976600a/