Scrivio Interview library
CodingIntermediate6 min read · updated 13 November 2026

A Spring Boot 3.5 service on Java 21 consumes a topic with a batch listener. Each record needs an independent HTTP call of about 200 ms, and order within a batch does not matter.

Show how you would process each batch concurrently on virtual threads, acknowledge only after all records succeed, and handle failures.

Use a batch listener that takes List<ConsumerRecord<K, V>> and an Acknowledgment with manual ack mode; inside it, open Executors.newVirtualThreadPerTaskExecutor() in try-with-resources, submit one task per record, wait for all of them (closing the executor waits too), and call ack.acknowledge() only when every task succeeded. On failure, throw BatchListenerFailedException with the index of the first failed record so the DefaultErrorHandler commits the records before it and retries from there. Limit calls to the downstream with a Semaphore, because virtual threads remove the thread limit but not the remote service's limit, and use per-call timeouts so each batch stays well inside max.poll.interval.ms.

Why this question is asked

Virtual threads make 'one thread per HTTP call' cheap again, which fits Kafka batches of independent records very well: 500 records at 200 ms each take 100 s one by one, but well under a second in parallel. Interviewers ask for this code to see whether we combine the new concurrency tools with the old Kafka rules: acknowledge only completed work, report failures precisely, and protect the downstream. In this answer, we will recap the pieces, write the listener, look at how failures are reported, add the concurrency limit and timeouts, and check the timing against max.poll.interval.ms.

1A Quick Recap of the Pieces

A batch listener in Spring Kafka receives all the records from one poll as a list, up to max.poll.records (500 by default). With manual acknowledgement (spring.kafka.listener.ack-mode=manual), the container commits the batch's offsets only after we call acknowledge() on the Acknowledgment it passes in.

A virtual thread is a lightweight thread managed by the JVM rather than the operating system. Blocking a virtual thread on I/O, such as waiting for an HTTP response, does not hold an OS thread, so we can create thousands of them cheaply. Executors.newVirtualThreadPerTaskExecutor() starts a new virtual thread for each submitted task, and since Java 19 ExecutorService is AutoCloseable: closing it waits for all submitted tasks to finish. Java 21 made virtual threads final, so Spring Boot 3.5 on Java 21 can use them directly.

2The Listener

Here is the core of the listener. It submits one task per record, waits for all of them, checks results in order, and acknowledges only if all succeeded.

Java
@Component
class EnrichmentListener {
private final Semaphore permits = new Semaphore(50); // at most 50 calls in flight
private final EnrichmentClient client; // HTTP client, 2 s timeout per call
EnrichmentListener(EnrichmentClient client) { this.client = client; }
@KafkaListener(id = "enrich", topics = "events", batch = "true")
void onBatch(List<ConsumerRecord<String, Event>> records, Acknowledgment ack) {
List<Future<Void>> results = new ArrayList<>(records.size());
try (ExecutorService vt = Executors.newVirtualThreadPerTaskExecutor()) {
for (ConsumerRecord<String, Event> rec : records) {
results.add(vt.submit(() -> {
permits.acquire();
try { client.enrich(rec.value()); } // about 200 ms
finally { permits.release(); }
return null;
}));
}
} // close() waits for every task
for (int i = 0; i < results.size(); i++) {
try {
results.get(i).get(); // already finished; rethrows a failure
} catch (ExecutionException e) {
throw new BatchListenerFailedException("enrich failed", e.getCause(), i);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new BatchListenerFailedException("interrupted", e, i);
}
}
ack.acknowledge(); // only when all 500 succeeded
}
}
// application.properties: spring.kafka.listener.ack-mode=manual
Step throughOne batch of 500 records
ContainerListenerVirtual threadsDownstream API
onBatch(500 records, ack)
submit 500 tasks
up to 50 calls at a time (Semaphore)
responses, about 200 ms each
executor closed: all tasks done
check results in index order
ack.acknowledge(), or BatchListenerFailedException(index)

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

Offsets are committed only after every record in the batch has succeeded.

Notice the order of operations. The try-with-resources block ends only when every task is finished, so by the time we check results, nothing is still running. We check results in list order, so the first failure we meet is the one with the lowest index, which is what the error handler needs. And acknowledge() is the last line, reached only if no exception was thrown.

3How Failures Are Reported

If record 137 fails, we throw BatchListenerFailedException with index 137. Spring Kafka's DefaultErrorHandler understands this exception: it commits the offsets of records 0 to 136, which are known to have succeeded, and seeks so that the next delivery starts at record 137. It retries according to its back-off, and after the retries are exhausted it passes the failed record to a recoverer, such as a DeadLetterPublishingRecoverer that sends it to a dead-letter topic, and moves on.

There is a catch with parallel processing. Records 138 to 499 ran at the same time as 137 and may well have succeeded, but they come after the failed index, so they are delivered and called again on the retry. That is unavoidable with this design, so the downstream calls must be idempotent, for example by sending the record's key and offset or an event id as an idempotency key.

4Limiting Concurrency Against the Downstream

Virtual threads remove the limit on our side: without the Semaphore, 500 records would mean 500 simultaneous HTTP calls, and with several consumers in the group, thousands. The downstream service, its connection pool or its rate limit is now the bottleneck, and flooding it causes errors and timeouts for everyone. A Semaphore with, say, 50 permits caps calls in flight from this consumer; the right number comes from the downstream team's capacity divided by the number of consumers.

We use a Semaphore rather than a fixed thread pool because it limits the scarce resource, the remote calls, while keeping virtual threads cheap. A waiting virtual thread costs almost nothing.

5Keeping Each Batch Inside max.poll.interval.ms

The container calls poll() again only after onBatch() returns, so a batch must finish within max.poll.interval.ms, 5 minutes by default. When the downstream is healthy, the numbers are comfortable.

Text
records per batch 500
call latency 0.2 s
concurrency (permits) 50
waves 500 / 50 = 10
batch time, healthy 10 x 0.2 s = about 2 s
batch time, all calls time out at 2 s 10 x 2 s = about 20 s // still far below 300 s

Notice that the per-call timeout is what makes the worst case predictable. Without it, a downstream that hangs would hang the batch, and the consumer would be removed from the group after 5 minutes. One more detail for Java 21: a virtual thread that blocks inside a synchronized block pins its carrier thread, which can reduce concurrency with some older client libraries; Java 24 removed most of that pinning, and on Java 21 it is worth checking that the HTTP client does not block inside synchronized code.

6Follow-up questions

Why not use CompletableFuture.supplyAsync without virtual threads?

supplyAsync uses the common ForkJoinPool by default, which has about as many threads as CPU cores. Blocking HTTP calls would occupy those few threads and the batch would run only a handful of calls at a time. Virtual threads let each blocking call have its own thread without that limit, while the Semaphore sets the limit we actually want.

Could we acknowledge records individually instead of the whole batch?

With a batch listener, acknowledge() commits the whole batch. Spring Kafka also lets a batch listener acknowledge up to an index with ack.acknowledge(index) in manual ack mode, but throwing BatchListenerFailedException with the index already gives us partial commits on failure, which is simpler. Check your Spring Kafka version for the exact methods.

7Conclusion

In this answer, we wrote a Spring Kafka batch listener that processes each record on its own virtual thread inside a try-with-resources executor, waits for all tasks, and calls ack.acknowledge() only when every record succeeded. A failure becomes BatchListenerFailedException with the lowest failed index, so the DefaultErrorHandler commits the records before it and retries from there, which means the downstream calls must be idempotent. A Semaphore protects the downstream from unlimited parallelism, and per-call timeouts keep even a bad batch far inside max.poll.interval.ms.

What to say in the interviewAbout 90 seconds aloud

Open with

I would use a batch listener that takes a list of ConsumerRecord and an Acknowledgment, with the ack mode set to manual. Inside, I open Executors.newVirtualThreadPerTaskExecutor in a try-with-resources block and submit one task per record, keeping the futures in a list.

Then, if they want more

Closing the executor waits for every task, so after the block everything is finished. Then I go through the futures in index order and call get. If one failed, I throw BatchListenerFailedException with that index; the DefaultErrorHandler commits the records before it, retries from that record with its back-off, and eventually sends it to a dead-letter topic.

Records after the failed one were processed in parallel and will be called again on retry, so the downstream calls need to be idempotent, for example with an event id as an idempotency key. If all succeeded, I call ack.acknowledge, and that is the only place offsets get committed.

Because virtual threads remove our thread limit, I add a Semaphore, say 50 permits, so we do not hit the downstream with 500 simultaneous calls; the limit is the remote service's capacity, not our threads. And I put a timeout on each call, a couple of seconds, so even a bad batch takes about 20 seconds, far inside max.poll.interval.ms.

With the downstream healthy, 500 calls of 200 milliseconds at 50 in parallel take about two seconds.

About this answer

Last updated
13 November 2026
Versions it names
Java 21, Java 19, Java 24, Spring Boot 3.5
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
Apache Kafka documentation
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 "Show how you would process each batch concurrently on virtual threads, acknowledge only...": https://scrivio-interview-library.netlify.app/spring-boot/kafka-clients-in-depth/eef938e848/