Video in progress

What does the concurrency parameter of @KafkaListener do, and how do you choose it?

concurrency sets how many consumer threads (each a separate KafkaConsumer) run inside one application. The total number of consumers = pods × concurrency, and it shouldn't exceed the partition count.

📖 Answer

@KafkaListener(topics = "orders", groupId = "fulfillment", concurrency = "4")
public void handle(OrderEvent e) { ... }

Here ConcurrentMessageListenerContainer creates 4 inner containers. Each one joins the group as a separate member and gets its own partitions.

The math: a topic with 12 partitions, 3 pods, concurrency=4 gives 12 consumers, one partition each. If the pods grow to 5, you get 20 consumers and 8 of them sit idle.

A few subtle points:

  • there's one listener bean for all threads, so any state in it (fields) has to be thread-safe;
  • every thread takes a DB connection, so the Hikari pool shouldn't be smaller than concurrency;
  • if concurrency is larger than the partition count, the extra consumer threads sit idle. Spring only warns and reduces the count when partitions are assigned explicitly (TopicPartitionOffset).

The order inside a partition isn't broken, because one thread still reads each partition.