Sub topic 8
Scaling consumers with concurrency
This chapter assumes you know the following from earlier chapters:
- A topic is split into partitions, and each partition is an ordered log.
- Consumers in one group share the partitions of a topic.
- You can write a basic
@KafkaListener.
Here you will learn how to run several consumers inside one application, and how far that scaling can go.
The limit that decides everything
Kafka assigns each partition to at most one consumer in a group at a time. That rule sets the maximum parallelism of a group:
- With 3 partitions, at most 3 consumers in the group do useful work.
- A fourth consumer joins the group but receives no partitions. It sits idle.
- With 1 partition, one consumer does all the work, however many instances you start.
The orders topic from the topic-declaration chapter has three partitions. So the parallelism ceiling for order-service is 3, regardless of how you configure Spring.
What the concurrency setting does
By default, a @KafkaListener runs in one container with one thread and one KafkaConsumer. The concurrency setting tells Spring to create N child containers instead. Each child container has these properties:
- It has its own
KafkaConsumerinstance. - It has its own polling thread.
- It joins the same consumer group as the others.
Kafka then assigns the partitions across these N consumers exactly as it would across N separate application instances. The KafkaConsumer class is not thread-safe, which is why Spring creates one consumer per thread. It does not share a consumer between threads.
Setting concurrency
You can set concurrency globally in application.yml. Spring Boot applies the value to its auto-configured listener container factory:
spring:
kafka:
listener:
concurrency: 3You can also set it on a single listener. The annotation attribute is a String, so it accepts property placeholders. It overrides the factory-level 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 OrderListener {
private static final Logger log = LoggerFactory.getLogger(OrderListener.class);
@KafkaListener(topics = "orders", groupId = "order-service", concurrency = "${orders.listener.concurrency:3}")
public void onOrder(OrderEvent event) {
log.info("Thread {} received order {}", Thread.currentThread().getName(), event.orderId());
}
}The ${orders.listener.concurrency:3} placeholder reads a property and falls back to 3. This lets you tune concurrency per environment without recompiling.
If you define your own ConcurrentKafkaListenerContainerFactory, you call setConcurrency(3) on it. A custom factory replaces Boot's auto-configured one. In that case Boot no longer applies the spring.kafka.listener.* properties or your DefaultErrorHandler bean to it. You must set the error handler on your factory yourself.
Seeing it work
To watch the threads, publish enough events to reach all three partitions. This runner sends 30 orders with different keys:
package com.example.orders;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class DemoDataConfig {
@Bean
public ApplicationRunner sendDemoOrders(OrderPublisher publisher) {
return args -> {
for (int i = 1; i <= 30; i++) {
publisher.publish(new OrderEvent("order-" + i, 1000L + i));
}
};
}
}With concurrency 3, the log shows three different consumer thread names. The exact names vary by Spring Kafka version, but they look similar to this:
Thread org.springframework.kafka.KafkaListenerEndpointContainer#0-0-C-1 received order order-4
Thread org.springframework.kafka.KafkaListenerEndpointContainer#0-1-C-1 received order order-7
Thread org.springframework.kafka.KafkaListenerEndpointContainer#0-2-C-1 received order order-1The number after #0- identifies the child container. Each child container normally handles one partition, so the same order ID always appears on the same thread name. Remember that the producer hashes the key to choose a partition, so you cannot predict which order lands on which partition.
Ordering guarantees
Kafka orders records only within a partition. Concurrency preserves this guarantee because one partition is always read by one thread, in offset order. Records for the same orderId share a key, so they share a partition, and a single thread processes them in sequence.
Across partitions there is no ordering. Order 7 on partition 1 may be processed before or after order 1 on partition 2. Code that depends on cross-key ordering cannot be scaled with concurrency.
Combining instances and concurrency
You can scale in two directions: more threads per instance, or more instances. What matters is the total number of consumers across all instances, compared with the partition count.
| Instances | Concurrency | Total consumers | Partitions | Active consumers | Idle consumers |
|---|---|---|---|---|---|
| 1 | 1 | 1 | 3 | 1 | 0 |
| 1 | 3 | 3 | 3 | 3 | 0 |
| 3 | 1 | 3 | 3 | 3 | 0 |
| 2 | 3 | 6 | 3 | 3 | 3 |
| 1 | 6 | 6 | 3 | 3 | 3 |
The last two rows are wasteful. Idle consumers hold a thread and a connection but receive nothing. They do have one use: they act as hot standbys. If an active consumer dies, Kafka reassigns its partition to an idle one.
Threads within one instance share a JVM, so they share CPU, memory and the same failure. Separate instances survive the loss of one machine. A common choice is a moderate concurrency (such as 3) with several instances, so that you get both parallelism and fault tolerance.
Rebalances
Whenever the set of consumers changes, Kafka reassigns partitions. This is called a rebalance. It happens when:
- An instance starts or stops.
- A consumer thread dies.
- A consumer takes too long between polls.
Raising concurrency from 1 to 3 triggers a rebalance at startup because three consumers join. During a rebalance, consumption pauses briefly for the affected partitions. After it, each consumer resumes from the last committed offset of its new partitions.
The third trigger is the one that surprises people. If processing one batch of records takes longer than max.poll.interval.ms (default 5 minutes), Kafka decides the consumer is stuck and removes it from the group. Its partitions move elsewhere, and its uncommitted records are processed again by another consumer. Slow processing with high concurrency can then cause repeated rebalances.
You can reduce this risk with these settings:
spring:
kafka:
consumer:
max-poll-records: 100
properties:
max.poll.interval.ms: 300000Lowering max-poll-records reduces the work done between polls. Raising max.poll.interval.ms gives slow processing more time. Tune the first one before the second.
Choosing a concurrency value
Follow these steps:
- Measure whether the listener is the bottleneck. Check consumer lag (how far the group's committed offsets are behind the end of each partition). Growing lag means consumers cannot keep up.
- Check whether the work is CPU-bound or I/O-bound. A listener that mostly waits on a database or HTTP call benefits from more threads. A CPU-bound listener gains little beyond the number of cores.
- Cap concurrency at the partition count divided by the number of instances, rounded up.
- If you need more parallelism than that, increase partitions. You can add partitions to an existing topic but never remove them.
Common mistakes
- Setting concurrency above the partition count. The extra threads are idle. Check the partition count with
kafka-topics.sh --describebefore raising the number. - Expecting concurrency to fix slow handlers on a single partition. One partition means one active consumer.
- Sharing mutable state in the listener bean. The same bean method is now called from several threads at once. Keep the listener stateless, or make shared state thread-safe.
- Forgetting that every thread opens its own connection. With 3 instances at concurrency 3, the broker sees 9 consumers.
Exercise
The orders topic has 4 partitions. You run 2 instances of order-service, each with concurrency 3. How many consumers are active, how many are idle, and what would you change to use all the consumers?
Show answer
There are 6 consumers in total (2 x 3). Only 4 are active because each partition is assigned to one consumer, so 2 are idle. To use all 6 consumers, increase the topic to at least 6 partitions. Alternatively, reduce the total consumers to 4, for example by setting concurrency to 2 on each instance, which uses 4 consumers with no idle ones.
Exercise
A teammate wants more throughput and suggests submitting each record to an ExecutorService inside the @KafkaListener method. Give two problems with this approach and the Kafka-native alternative.
Show answer
First, the offset is committed when the listener method returns, not when the background task finishes, so a failure or restart loses records that were never processed. Second, records for the same key can finish out of order, which breaks per-partition ordering. The Kafka-native alternative is to add partitions and raise the listener concurrency so that Kafka distributes the work across consumers.