Scrivio Interview library
ScenarioIntermediate7 min read · updated 12 November 2026

A batch job processes 10 million records: each record needs a CPU-heavy transformation (about 1 ms) and a database write (about 5 ms of waiting). How would you structure the threads or executors, and how would you choose the sizes?

I would split the job into two stages connected by a bounded queue: a CPU stage with about as many platform threads as cores for the 1 ms transformation, and a write stage whose concurrency is set by the database connection pool and the database's capacity, not by thread counts. The biggest gain usually comes from batching the writes with JDBC batching or COPY, which cuts the per-record wait far more than extra threads can. Little's law (concurrency = throughput x latency) gives the first estimate of sizes, and then we measure, changing one size at a time.

Why this question is asked

Batch jobs are where thread pool sizing stops being theory. A job that takes 14 hours one way can take under an hour another way, on the same hardware, and the difference is almost never the number of threads alone. Interviewers ask this to see whether we can separate CPU work from waiting, find the real bottleneck, and reason with numbers instead of guessing a pool size of 200. In this answer, we will work out what the job costs, design the two stages, size each one with Little's law, see why batching beats more threads, add back-pressure, and plan how to measure.

1Working Out What the Job Costs

Each record needs 1 ms of CPU and 5 ms of waiting on the database. Done one record at a time on one thread, 10 million records take 10,000,000 x 6 ms = 60,000 seconds, about 16.7 hours. Most of that, 50,000 seconds, is waiting, which uses no CPU at all.

The CPU part has a hard floor set by the cores. 10,000 CPU-seconds on 8 cores is at least 1,250 seconds, about 21 minutes, however clever we are. The waiting part has no such floor, because many writes can wait at the same time, so the question becomes: how many writes must be in flight to keep up with the CPU stage?

Rough cost of the job on an 8-core machine
PlanTime for 10M recordsLimited by
One thread, record by record60,000 s (16.7 h)everything in sequence
8 threads doing both stepsabout 7,500 s (2.1 h)threads waiting on writes
8 CPU threads + 40 writes in flightabout 1,250 s (21 min)CPU, if the DB can take 8,000 writes/s
8 CPU threads + batched writesabout 1,250 s with few connectionsCPU
Numbers are first estimates from the stated costs; measurement decides.

2Separating CPU Work From Waiting

If one pool does both steps, its size is always wrong. Sized to 8 for the CPU, the threads spend 5 of every 6 ms waiting, so the CPU is idle most of the time. Sized to 100 for the waiting, up to 100 threads may compete for 8 cores during the CPU step, adding context switches and making every transformation slower.

So we split the work into two stages. Stage 1 reads records and transforms them on a pool of about 8 platform threads, one per core. Stage 2 takes transformed records from a bounded queue and writes them, with as much concurrency as the database can usefully take. Each stage now has one kind of work and one sizing rule.

Java
int cores = Runtime.getRuntime().availableProcessors(); // 8
ExecutorService cpuPool = Executors.newFixedThreadPool(cores);
BlockingQueue<Row> toWrite = new ArrayBlockingQueue<>(20_000); // bounded: back-pressure
// stage 1: transform
cpuPool.submit(() -> { for (Record r : reader) toWrite.put(transform(r)); return null; });
// stage 2: write in batches of 1,000 on a few connections
int writers = 4;
ExecutorService writePool = Executors.newFixedThreadPool(writers);
for (int i = 0; i < writers; i++) {
writePool.submit(() -> {
List<Row> batch = new ArrayList<>(1_000);
while (true) {
Row row = toWrite.poll(1, TimeUnit.SECONDS);
if (row != null) batch.add(row);
if (batch.size() == 1_000 || (row == null && !batch.isEmpty())) {
repository.insertBatch(batch); // one round trip for 1,000 rows
batch.clear();
}
if (row == null && readerDone.get()) return null;
}
});
}
Step throughTwo stages with a bounded queue between them
  1. Readerstreams records from the source in ranges
  2. CPU stageabout one platform thread per core, 1 ms each
  3. Bounded queue20,000 rows; a full queue pauses the CPU stage
  4. Write stagea few writers, batches of 1,000 rows
  5. Connection pool and databasethe real limit on write concurrency

5 layers, from the top down. Step through them one at a time.

Notice that put() on a full queue blocks the CPU stage. That is the back-pressure: if writes fall behind, transformation pauses instead of filling memory with millions of transformed rows. The single reader loop is simplified here; in a real job we would split the input into ranges and run one reader task per core.

3Sizing the Write Stage With Little's Law

Little's law says that the average number of items in a system equals throughput times the time each item spends there. For our writes: if the CPU stage produces 8 cores x 1,000 records per second = 8,000 records per second, and each single-row write takes 5 ms, we need 8,000 x 0.005 = 40 writes in flight to keep up.

But there is a catch: 40 writes in flight need 40 database connections, and the threads are not the scarce resource. The connection pool, say HikariCP with 20 connections, caps us at 20 concurrent writes, and the database itself may not sustain 8,000 single-row commits per second because each commit waits for a log flush. Adding writer threads beyond the pool size only makes them queue for a connection. So the database decides the write concurrency, and the right first step is to make each write cheaper.

4Batching the Writes: the Bigger Gain

Most of the 5 ms per record is not the work of inserting one row; it is the round trip to the database and the commit. Batching shares that cost across many rows. With JDBC batching (addBatch and executeBatch, and for PostgreSQL reWriteBatchedInserts=true on the driver), a batch of 1,000 rows might take about 50 ms, which is 0.05 ms per record instead of 5 ms. With PostgreSQL's COPY through the driver's CopyManager, bulk loads are faster still.

Now the arithmetic changes completely. To write 8,000 records per second at 0.05 ms each we need only 8,000 x 0.00005 = 0.4 writes in flight, so 2 to 4 writer threads are plenty, and the database does far less work per row. This is why batching is usually a bigger win than any thread count: it removes waiting instead of overlapping it. In Spring with JPA, batching needs hibernate.jdbc.batch_size and an ID strategy that does not force a round trip per insert (IDENTITY prevents insert batching in Hibernate), so for a job this size plain JDBC batching is often simpler.

5Measuring: One Size at a Time

Our numbers are estimates. The real job has other costs: reading input, garbage collection, indexes that slow inserts as the table grows. So we start with the estimate, 8 CPU threads, 4 writers, batches of 1,000, and run on a sample of maybe 500,000 records while recording throughput, queue depth, CPU use and database metrics.

Then we change one thing at a time. If the queue is always near full, writes are the bottleneck, so we try larger batches or another writer. If the queue is near empty and CPU is at 100 percent, the CPU stage is the bottleneck and we are close to the floor. Changing two sizes together makes it impossible to tell which change helped. We also make the job restartable, by committing in batches and recording the last processed key, so a failure at record 7 million does not mean starting again.

6Follow-up questions

Would virtual threads help here?

They could run the write stage, since writes mostly wait, but they do not remove the real limit, which is connections and database capacity. With batching we only need a handful of writers anyway. For the CPU stage they help nothing, because CPU-bound work needs cores, not cheap blocking.

Why not let the database transform the data with SQL instead?

If the transformation can be expressed in SQL, an INSERT ... SELECT inside the database avoids moving 10 million rows over the network at all, and is often the fastest option. When the logic needs Java libraries or external data, we keep it in the application and focus on batching.

What batch size would you start with?

Somewhere between 500 and 5,000 rows, then measure. Too small and round trips dominate; too large and each batch holds locks longer, uses more memory, and a failure means retrying more rows. The best size is where throughput stops improving.

7Conclusion

In this answer, we worked out that the job is 10,000 CPU-seconds and 50,000 seconds of waiting, so we split it into a CPU stage sized to the cores and a write stage whose concurrency is set by the connection pool and the database, joined by a bounded queue that provides back-pressure. Little's law gave the first estimate, 40 single-row writes in flight, and showed why that is hard to sustain; batching the writes with JDBC batching or COPY cut the per-record cost so much that a few writers are enough. Finally, we measure on a sample and change one size at a time.

What to say in the interviewAbout 80 seconds aloud

Open with

First I would separate the two kinds of work, because one pool can never be sized right for both. The transformation is CPU-bound, so I give it a pool of about one platform thread per core, which on 8 cores means roughly 8,000 records per second and a floor of about 21 minutes for the whole job.

Then, if they want more

The write is waiting, and its concurrency is limited by the database, the connection pool and what the database can commit, not by threads. Little's law says 8,000 per second times 5 milliseconds is about 40 writes in flight, which already exceeds a typical pool of 20.

So the bigger gain is batching: JDBC batching with reWriteBatchedInserts or COPY in PostgreSQL might write 1,000 rows in about 50 milliseconds, so a few writer threads keep up easily and the database does much less work. Between the stages I would put a bounded queue, so if writes fall behind, the CPU stage pauses instead of filling memory.

Then I would run on a sample, watch throughput, queue depth, CPU and database metrics, and change one size at a time, starting with batch size. I would also make the job restartable by committing per batch and recording progress.

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 batch job processes 10 million records: each record needs a CPU-heavy transformation...": https://scrivio-interview-library.netlify.app/java/threads/21ad557cb0/