Sub topic 8
Scaling consumers with concurrency
This chapter assumes you know how topics, partitions and consumer groups work, and that you can run the @KafkaListener example from the previous chapter. Here you will learn how to run several consumer threads in one application and where the limit on parallelism comes from.
The rule behind scaling
Within one consumer group, Kafka assigns each partition to exactly one consumer at a time. Two consequences follow:
- Ordering is preserved per partition, because only one consumer reads it.
- The number of partitions is the upper limit on parallelism. A group with three partitions can keep at most three consumers busy. A fourth consumer sits idle.
The orders topic from earlier chapters has three partitions, so three is the useful maximum for this group.
Setting concurrency
Spring creates one KafkaConsumer per unit of concurrency. Each one runs in its own thread inside a listener container. You can set the value for all listeners in application.yml:
spring:
kafka:
listener:
concurrency: 3You can also set it on a single listener. The annotation attribute takes precedence over the global value:
package com.example.orders;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;
@Component
public class ConcurrentOrderListener {
private static final Logger log = LoggerFactory.getLogger(ConcurrentOrderListener.class);
@KafkaListener(topics = "orders", groupId = "order-service", concurrency = "3")
public void onOrder(OrderEvent event) {
log.info("Thread {} received order {}",
Thread.currentThread().getName(), event.orderId());
}
}Run this with several orders that have different IDs. The log shows different thread names, such as ...-0-C-1, ...-1-C-1 and ...-2-C-1. Records with the same order ID always appear on the same thread, because the key maps them to one partition.
Do not keep both OrderListener and ConcurrentOrderListener active in the same group on the same topic. They would share the partitions between them, and the output would be confusing.
Choosing a number
Concurrency applies per application instance. If you run two instances, each with concurrency: 3, the group has six consumers for three partitions. Three of them stay idle.
| Partitions | Instances | Concurrency per instance | Active consumers |
|---|---|---|---|
| 3 | 1 | 3 | 3 |
| 3 | 3 | 1 | 3 |
| 3 | 2 | 3 | 3 (3 idle) |
| 6 | 2 | 3 | 6 |
Use concurrency to use the cores of one machine. Add instances to spread the load over several machines or to survive a machine failure. In both cases, keep the total number of consumers at or below the partition count.
If Spring starts more consumers than there are partitions, the extra ones receive no assignment. This is harmless but wastes threads and memory.
Common errors
- Raising concurrency without raising partitions. The extra threads do nothing. Increase the partition count in the
NewTopicbean instead. Kafka can add partitions to an existing topic but never remove them. Adding partitions also changes which partition a key maps to, so ordering for existing keys can break across the change. - Assuming the listener code is thread-safe. With
concurrencyabove 1, Spring calls the same listener bean from several threads at once. Any mutable field in the bean needs synchronization, or you should avoid shared state. - Slow processing causing rebalances. If one record takes longer than
max.poll.interval.ms(five minutes by default), Kafka considers the consumer dead and reassigns its partitions. Keep per-record work short, or tune that setting. - Expecting global ordering. Order is guaranteed only within a partition. Events for different orders may be processed in any relative order.
Exercise
A topic has 4 partitions. You deploy 3 instances of the application, each with concurrency: 2. How many consumers are active, how many are idle, and what would you change to use all of them?
Show answer
There are 6 consumers in the group but only 4 partitions, so 4 are active and 2 are idle. To use all six, increase the topic to at least 6 partitions. Otherwise, lower the total consumer count to 4, for example with concurrency: 1 on 4 instances or fewer threads per instance.