Scrivio Interview library
ScenarioIntermediate6 min read · updated 12 November 2026

A Spring Batch step that loads 50 million rows takes 9 hours with a commit interval of 10. How would you tune it, and what trade-offs does each change bring?

First measure where the 9 hours go, using the step's read, process and write timings, because a commit interval of 10 means 5 million transactions and the likely culprits are commit overhead and row-by-row writes. Then raise the commit interval to somewhere between 500 and 2,000, which cuts commits by 50 to 200 times but means more rework on a failure and more memory per chunk, write with JdbcBatchItemWriter or JDBC batching instead of single JPA saves, read with a cursor or keyset reader rather than offset paging, and, if the database can absorb it, partition by key range.

Why this question is asked

A batch job that takes 9 hours is not just slow; it may no longer fit its window, and a failure at hour 8 means a long restart. Tuning it well requires knowing which part is slow, because the fixes for reading, processing and writing are different, and each brings a cost. Interviewers ask this scenario to see whether we measure before changing anything and whether we know the trade-offs, not only the settings. In this answer, we will do the arithmetic, measure the step, and then go through the commit interval, batch writes, the reader, and partitioning, with what each one costs.

1Doing the Arithmetic First

Fifty million rows in 9 hours is about 32,400 seconds, so roughly 1,540 rows per second. With a commit interval of 10, that is 5 million chunks, and so 5 million commits, or about 154 commits per second. Each commit in a chunk-oriented step is not only the business commit: Spring Batch also updates the BATCH_STEP_EXECUTION row and saves the step's ExecutionContext in the job repository at every chunk. So each chunk does at least two extra writes and a commit that must be flushed to disk.

If one commit with its repository updates costs around 4 milliseconds, 5 million of them take more than 5 hours on their own. That suggests the commit interval alone explains much of the runtime. But we should confirm that rather than assume it.

2Measure Where the Time Goes

Spring Batch publishes Micrometer timers, including spring.batch.item.read, spring.batch.item.process and spring.batch.chunk.write, as well as step durations. With these in a dashboard, or even just in the logs from a test run on a few million rows, we can see the time per item for each phase. The StepExecution also shows the commit count and read and write counts. Database statistics tell the other half: time per statement, waits, and the number of statements executed.

A measured profile (example)
PhaseTime per itemShare of 9 hLikely cause
Read (offset paging)6 ms at the end, 0.3 ms at the start35%OFFSET grows with each page
Process0.05 msunder 1%fine
Write (JPA save per row)1.5 ms25%one INSERT round trip per row
Commit and repository update4 ms per chunk of 1040%5 million commits
Illustrative; the point is to find the dominant cost before tuning.

Notice that reading gets slower as the job goes on. That is a signature of offset-based paging, and it is why the measurement should look at the whole run, not just the first minutes.

3Raise the Commit Interval

Changing chunk(10, tm) to chunk(1000, tm) reduces the number of commits from 5 million to 50,000, a hundredfold reduction in commit and repository overhead. In the profile above, that removes most of the 40 percent spent on commits.

Java
.<Customer, Customer>chunk(1000, transactionManager) // was 10
// commits: 50,000,000 / 10 = 5,000,000
// commits: 50,000,000 / 1000 = 50,000

The trade-offs are real, though. A chunk of 1,000 items is held in memory together with its processed results, so with large items memory per chunk grows. A failure rolls back up to 1,000 items of work instead of 10, and in a fault-tolerant step a writer skip scans all 1,000 items one by one. Longer transactions also hold locks longer, which matters if other systems use the same tables. A range of a few hundred to a couple of thousand is usually a good balance; beyond that the gains are small and the risks grow.

4Write in Batches

If the writer calls a JPA repository's save() for each item, every row is a separate INSERT and a separate round trip to the database. JdbcBatchItemWriter sends the chunk's inserts as one JDBC batch, which is often ten times faster. If we must stay with JPA, we set hibernate.jdbc.batch_size, for example to 1000, and hibernate.order_inserts to true, so Hibernate groups the inserts.

Properties
# JPA path
spring.jpa.properties.hibernate.jdbc.batch_size=1000
spring.jpa.properties.hibernate.order_inserts=true
# PostgreSQL driver: rewrite a batch into multi-row INSERTs
spring.datasource.url=jdbc:postgresql://db/app?reWriteBatchedInserts=true

There is a catch with JPA: entities whose ids use IDENTITY generation cannot be batched for inserts by Hibernate, because it must run each insert to learn the generated id. A sequence with a sensible allocation size avoids that. The JDBC writer avoids the whole question, which is why it is the usual choice for bulk loads.

5Read Without Offset Paging

Offset paging means each page is fetched with LIMIT 1000 OFFSET n. The database still has to walk past the first n rows, so page 49,000 scans 49 million rows to return 1,000. That is why reading slowed down as the job went on. JpaPagingItemReader works this way. Two better readers exist. JdbcCursorItemReader opens one query and streams rows with a fetch size, so each row is read once. JdbcPagingItemReader uses a sort key and asks for rows after the last key it saw, which is keyset paging: each page uses the index and costs the same at the end as at the start.

SQL
SELECT id, name, email FROM customer
WHERE id > :lastId -- keyset: starts where the last page ended
ORDER BY id
LIMIT 1000; -- same cost on page 1 and page 49,000

6Partition by Key Range

Once a single thread is efficient, we can run several in parallel by partitioning: a manager step splits the id range into, say, 8 ranges, and 8 worker steps each process one range with their own reader and their own restart state. If the database is the bottleneck, though, partitioning only moves the queue into the database. So we check that it has spare CPU and I/O, size the connection pool for the extra workers, and watch replication lag and lock waits while testing. A realistic result after all changes is a run measured in tens of minutes rather than hours, but the actual number depends on the measurements.

7Follow-up questions

Is there a best commit interval?

No single value, but a useful rule is to aim for each chunk to take somewhere between a fraction of a second and a couple of seconds, so commit overhead is small and rework on failure is limited. For simple rows that is often 500 to 2,000 items. We measure throughput at a few sizes and stop increasing when the gain flattens.

Would a multi-threaded step be simpler than partitioning?

It is simpler to configure, but it shares one reader across threads, which must then be thread-safe, and its saved position is not reliable for restart because chunks finish out of order. Partitioning gives each worker its own range and its own saved state, so it is the safer way to parallelise a restartable load.

Should we drop indexes during the load?

For a full reload into an empty table, dropping secondary indexes and rebuilding them afterwards can be much faster. For a table that other systems query during the load, or for an incremental load, it is not an option. It is a decision for the database owner, not a default.

8Conclusion

In this answer, we worked out that a commit interval of 10 means 5 million commits, measured the step with Spring Batch's timers to find where the 9 hours went, and then tuned it. A larger commit interval cuts commit overhead at the cost of memory and rework, JDBC batch writes replace row-by-row saves, a cursor or keyset reader removes the slowdown of offset paging, and partitioning by key range adds parallelism if the database can absorb it.

What to say in the interviewAbout 80 seconds aloud

Open with

I would start by measuring, not changing settings. Fifty million rows with a commit interval of ten is five million chunks, and every chunk commits and also updates the step execution and execution context in the job repository, so commit overhead alone can take hours.

Then, if they want more

Spring Batch's Micrometer timers for read, process and chunk write, together with database statistics, show which phase dominates. Then I would raise the commit interval to something like 1,000, which cuts commits a hundredfold; the costs are more memory per chunk, more rework when a chunk fails, longer locks, and slower skip scans.

I would make sure the writer uses JdbcBatchItemWriter, or Hibernate batching with hibernate.jdbc.batch_size and a sequence instead of identity ids, rather than one save per row, and I would enable driver options like reWriteBatchedInserts on PostgreSQL.

If reading gets slower as the job goes on, that is offset paging, so I would switch to a JdbcCursorItemReader with a fetch size or a JdbcPagingItemReader, which uses a sort key and keyset paging.

Only after a single thread is efficient would I partition by id range, maybe into eight workers, after confirming the database has headroom and sizing the connection pool. At each step I would re-measure.

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 Spring Batch step that loads 50 million rows takes 9 hours with a commit interval of...": https://scrivio-interview-library.netlify.app/spring-boot/spring-batch/745802ec5a/