Video in progress
A Kafka consumer processes messages slowly. How do you raise parallelism: concurrency, partition count, or a thread pool inside the listener?
The main lever is the partition count and a matching concurrency: one partition is processed by one consumer thread at a time. Handing work to your own thread pool inside the listener looks fast, but it breaks offset commits and ordering and can lead to lost messages.
📖 Answer
First measure where the slowness is: the time to process one message (listener observation or your own timer) and the lag. Often the cause is a single slow query in the DB, and fixing it helps more than parallelism.
Options:
-
Partitions and concurrency. 12 partitions, 3 pods ×
concurrency = "4"= 12 threads. The safest way: ordering is preserved per key, and Spring Kafka commits offsets correctly on its own. The limit is the partition count. -
A batch listener. Taking messages 500 at a time and writing to the DB in one batch often gains more than parallelism:
@KafkaListener(topics = "events", batch = "true")
public void on(List<EventDto> events) {
repo.upsertAll(events);
}
- An executor inside the listener is dangerous:
// bad
@KafkaListener(topics = "events")
public void on(EventDto e) {
executor.submit(() -> handle(e)); // returns immediately
}
The listener returns right away, Spring commits the offset, and handle is still running. If the pod dies at that moment, the message is lost. Messages with the same key also get processed in parallel, so ordering breaks.
- Parallelism by key. If you really need more parallelism than the partition count, a library like Confluent Parallel Consumer processes different keys within one partition in parallel and manages offsets correctly.
Also tune max.poll.records and max.poll.interval.ms: if processing everything from one poll takes longer than the interval, the consumer is removed from the group and a rebalance starts, and a slow consumer gets even slower.
Sign up to mark studied questions and save your progress.