Scrivio Interview library
CodingIntermediate6 min read · updated 12 November 2026

Write the outline of a partitioned Spring Batch step that processes orders by id ranges across 8 worker threads, where each worker reads only its range.

Write a Partitioner whose partition(gridSize) method returns 8 ExecutionContexts, each holding a minId and maxId, build the manager step with new StepBuilder("manager", repo).partitioner("worker", partitioner).step(workerStep).gridSize(8).taskExecutor(executor), and make the worker's reader @StepScope so it injects @Value("#{stepExecutionContext['minId']}") and reads only its range. Use a bounded ThreadPoolTaskExecutor and size the connection pool for 8 workers, and remember that each partition is its own StepExecution, so a restart re-runs only the partitions that failed.

Why this question is asked

Partitioning is the standard way to make a large Spring Batch step faster without giving up restart, and writing its outline is a common coding question because it brings together several features that people rarely use together: partitioners, step-scoped beans with late binding, task executors and connection pools. Interviewers want to see that each worker really reads only its own range and that we have thought about the database. In this answer, we will recap how partitioning works, write the partitioner, the worker step with its range-bound reader, and the manager step, then size the threads and connections and see what a restart does.

1A Quick Recap of Partitioning

In a partitioned step, a manager step does no reading or writing itself. It asks a Partitioner to divide the work into partitions, each described by a small ExecutionContext, the key-value map Spring Batch stores per step execution. The manager then launches a worker step once per partition, here on 8 threads, and waits for all of them. Each worker execution reads its partition's values from its own step execution context, so the same worker step definition processes a different range each time.

Step throughA partitioned run with 8 workers
Manager stepPartitionerThread poolWorker step
partition(8)
8 contexts: minId and maxId
submit worker:partition0..7
run with context of partition 3
read ids 3,000,001..4,000,000
COMPLETED
all 8 done: manager COMPLETED

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

2Writing the Partitioner

The partitioner finds the smallest and largest order id and cuts the range into equal parts. With ids from 1 to 8,000,000 and a grid size of 8, each partition covers one million ids.

Java
public class OrderIdPartitioner implements Partitioner {
private final JdbcTemplate jdbc;
public OrderIdPartitioner(JdbcTemplate jdbc) { this.jdbc = jdbc; }
@Override
public Map<String, ExecutionContext> partition(int gridSize) {
long min = jdbc.queryForObject("SELECT MIN(id) FROM orders", Long.class); // 1
long max = jdbc.queryForObject("SELECT MAX(id) FROM orders", Long.class); // 8,000,000
long size = (max - min) / gridSize + 1; // 1,000,000
Map<String, ExecutionContext> result = new HashMap<>();
for (int i = 0; i < gridSize; i++) {
long from = min + i * size;
long to = Math.min(from + size - 1, max);
ExecutionContext ctx = new ExecutionContext();
ctx.putLong("minId", from);
ctx.putLong("maxId", to);
result.put("partition" + i, ctx); // partition0: 1..1,000,000
}
return result; // partition7: 7,000,001..8,000,000
}
}

The map keys become part of each worker step execution's name, such as worker:partition3, which is how the job repository tells partitions apart on restart. The ranges must cover every id exactly once, so we compute the last range's upper bound from max rather than from the size.

3The Worker Step and Its Range-Bound Reader

The worker reader must know its range, which only exists once the worker's step execution has started. So we mark the reader @StepScope, which makes Spring create a separate reader for each worker step execution, and we inject the values with a late-binding expression that reads the step execution context.

Java
@Bean
@StepScope
public JdbcPagingItemReader<Order> orderReader(
DataSource ds,
@Value("#{stepExecutionContext['minId']}") Long minId,
@Value("#{stepExecutionContext['maxId']}") Long maxId) {
return new JdbcPagingItemReaderBuilder<Order>()
.name("orderReader")
.dataSource(ds)
.selectClause("SELECT id, customer_id, total")
.fromClause("FROM orders")
.whereClause("WHERE id BETWEEN :minId AND :maxId") // only this range
.parameterValues(Map.of("minId", minId, "maxId", maxId))
.sortKeys(Map.of("id", Order.ASCENDING))
.pageSize(1000)
.rowMapper(new DataClassRowMapper<>(Order.class))
.build();
}
@Bean
public Step workerStep(JobRepository repo, PlatformTransactionManager tm,
JdbcPagingItemReader<Order> orderReader, ItemWriter<Order> orderWriter) {
return new StepBuilder("worker", repo)
.<Order, Order>chunk(1000, tm)
.reader(orderReader)
.writer(orderWriter)
.build();
}

Notice the naming clash: the Order record of our domain and Spring Batch's Order enum for sort direction. In real code one of them is imported with its full name. Each worker's reader has its own saved state, the last id read in its range, so the partitions restart independently.

4The Manager Step and the Thread Pool

The manager step ties it together. gridSize tells the partitioner how many partitions to create, and the task executor runs the worker executions in parallel. We use a bounded ThreadPoolTaskExecutor rather than an unbounded executor, so the number of concurrent workers is exactly what we planned.

Java
@Bean
public ThreadPoolTaskExecutor partitionExecutor() {
ThreadPoolTaskExecutor ex = new ThreadPoolTaskExecutor();
ex.setCorePoolSize(8);
ex.setMaxPoolSize(8); // never more than 8 workers at once
ex.setThreadNamePrefix("orders-part-");
ex.initialize();
return ex;
}
@Bean
public Step managerStep(JobRepository repo, OrderIdPartitioner partitioner,
Step workerStep, ThreadPoolTaskExecutor partitionExecutor) {
return new StepBuilder("manager", repo)
.partitioner("worker", partitioner)
.step(workerStep)
.gridSize(8)
.taskExecutor(partitionExecutor)
.build();
}
# connection pool sized for 8 workers plus the manager and repository work
spring.datasource.hikari.maximum-pool-size=12

The connection pool deserves a moment. Each worker holds a connection for the duration of its chunk transaction, and its paging reader and the job repository updates use that same connection when they share the data source. With 8 workers and the manager, a pool of 10 to 12 leaves a little headroom. If the pool is smaller than the number of workers, threads wait for connections and the extra workers add nothing. If we used cursor readers, each would hold an extra connection for the whole partition, so the pool would need about 8 more.

5What Happens on Restart

Suppose partition 5 fails at id 5,400,000 because of a deadlock, while the other seven complete. The manager step and the job end FAILED. When we restart the same job instance, Spring Batch does not call the partitioner again. It finds the existing worker step executions in the repository, sees that seven are COMPLETED and skips them, and restarts only worker:partition5 from its saved position, the last committed id. So the restart processes about 600,000 orders, not 8 million.

Partitions after a failure and restart
PartitionRangeFirst runRestart
partition0..41 .. 5,000,000COMPLETEDskipped
partition55,000,001 .. 6,000,000FAILED at 5,400,000resumes after 5,400,000
partition6..76,000,001 .. 8,000,000COMPLETEDskipped

6Follow-up questions

How do you choose ranges when ids are skewed?

Equal id ranges assume ids are spread evenly over the rows we process. If they are not, for example because old orders were archived and most rows are at the high end, some partitions have far more work. We can compute ranges from the data instead: in PostgreSQL, percentile_disc over the id column gives boundaries that put the same number of rows in each partition. Another simple approach is to create many more partitions than threads, such as 64 partitions on 8 threads, so the pool keeps pulling the next partition and uneven sizes average out.

Why not just use a multi-threaded step?

A multi-threaded step shares one reader across threads and cannot save a reliable position, so a restart starts over. Partitioning gives each worker its own reader and saved state, which is why it is preferred for large, restartable loads.

Can the workers run on other machines?

Yes. With remote partitioning, the manager sends each partition's StepExecution to workers over messaging, using spring-batch-integration, and the workers run the same worker step and update the shared job repository. The partitioner and worker step stay the same; only the way partitions are handed out changes.

7Conclusion

In this answer, we wrote a partitioned step for orders across 8 workers. The Partitioner returns 8 ExecutionContexts with minId and maxId, the manager step is built with partitioner("worker", partitioner).step(workerStep).gridSize(8).taskExecutor(executor), and the step-scoped worker reader injects its range from the step execution context so it reads only its ids. A bounded thread pool and a connection pool sized for the workers keep the load predictable, and because each partition has its own StepExecution, a restart re-runs only the failed partitions.

What to say in the interviewAbout 80 seconds aloud

Open with

I would start with a Partitioner. Its partition method gets the grid size, here 8, queries the minimum and maximum order id, and returns a map of 8 ExecutionContexts, each with a minId and a maxId, with keys like partition0 to partition7.

Then, if they want more

The worker step is a normal chunk step, but its reader is @StepScope, so a separate instance is created for each worker execution, and it injects its range with @Value of stepExecutionContext minId and maxId.

I would use a JdbcPagingItemReader with a where clause on id between those values and the id as the sort key, so each worker reads only its range and resumes precisely. The manager step is new StepBuilder manager, partitioner with the worker step name and the partitioner, step workerStep, gridSize 8 and a taskExecutor.

That executor is a bounded ThreadPoolTaskExecutor with exactly 8 threads, and I would size the Hikari pool to about 10 to 12 connections so all workers and the repository updates get a connection.

Each partition is its own StepExecution in the repository, so if partition 5 fails, a restart skips the seven completed partitions and resumes only partition 5 from its last commit. If the ids are skewed, I would compute boundaries with percentiles or use many more partitions than threads.

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 "Write the outline of a partitioned Spring Batch step that processes orders by id ranges...": https://scrivio-interview-library.netlify.app/spring-boot/spring-batch/6e2ed8619a/