A robot with a vacuum hand that is pulling in various bits of data and outputing graphs and charts with its other hand. On the far left are the words "Data on Baeldung".

1. Overview

Apache Kafka share consumers, or Kafka queues, enable applications to consume messages from a topic concurrently without the need to split it into multiple partitions.

By default, Apache Kafka topics are split into partitions, and a single thread consumes messages from each partition. To consume messages from a topic concurrently, multiple partitions are necessary so that multiple consumer threads can consume messages from the different partitions. The Kafka Share Consumer support changes how consumers read messages from a topic. Multiple consumers can now consume from the same topic in parallel, without splitting it into multiple partitions.

In this article, we’ll learn how to use Kafka share consumers in a Spring Boot application.

2. Setup

Before we dive into the consumer-related application code, we need to define dependencies and configure the Kafka deployment.

2.1. Maven

Kafka version 4.1 brings preview support for the feature, and version 4.2 reaches general availability. Respectively, spring-boot-starter-kafka version 4.0 brings early access, and version 4.1 offers full production readiness. Additionally, spring-boot-starter-jackson is required for JSON formats since Jackson 3 is the preferred JSON library for Spring Boot versions 4.0.0 and onwards:

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-kafka</artifactId> <version>4.1.0</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jackson</artifactId> <version>4.1.0</version> </dependency>

2.2. Kafka

At a lower level, Kafka uses an internal topic, named “__share_group_state”, to keep the state of the share consumers. Since we use a single broker setup for our demo, we need to tweak the following settings:

share.coordinator.state.topic.replication.factor = 1 share.coordinator.state.topic.min.isr = 1

In detail, share.coordinator.state.topic.replication.factor setting defines the total number of broker nodes that hold a copy of the topic, and share.coordinator.state.topic.min.isr defines the minimum in-sync replicas. Since we’ll use Testcontainers for our test suites, let’s define the equivalent configuration for our KafkaContainer:

@Bean @ServiceConnection KafkaContainer kafkaContainer() { return new KafkaContainer("apache/kafka:4.3.1").withEnv("KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR", "1") .withEnv("KAFKA_SHARE_COORDINATOR_STATE_TOPIC_REPLICATION_FACTOR", "1") .withEnv("KAFKA_SHARE_COORDINATOR_STATE_TOPIC_MIN_ISR", "1"); }

3. Configuration

Conveniently, the Spring Boot Java configuration is similar to the non-share consumer configuration, with some key differences. To start, let’s create the ShareConsumerFactory:

@Bean public ShareConsumerFactory<String, Event> shareConsumerFactory() throws ExecutionException, InterruptedException {     configureShareGroupOffsetReset(); Map<String, Object> props = new HashMap<>(); props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers); props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class); props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, JacksonJsonDeserializer.class); props.put(JacksonJsonDeserializer.TRUSTED_PACKAGES, "com.baeldung.spring.kafka.shareconsumer.model"); props.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, 1); props.put(ConsumerConfig.SHARE_ACQUIRE_MODE_CONFIG, "record_limit"); return new DefaultShareConsumerFactory<>(props); }

Notably, we’ve set the ConsumerConfig.SHARE_ACQUIRE_MODE_CONFIG setting to “record_limit”, so that the ConsumerConfig.MAX_POLL_RECORDS_CONFIG, which is set to 1, takes effect. Interestingly, the ConsumerConfig.SHARE_ACQUIRE_MODE_CONFIG defaults to “batch_optimized”, leading to batch message delivery for better performance. This configuration ensures that when a consumer calls the poll() method to acquire new records, it gets a single record, leaving the other records available for other consumers.

In the configureShareGroupOffsetReset() method, we use Kafka’s Admin client to set the share.auto.offset.reset property of the shgroup share group to earliest, so the group reads the topic from the beginning instead of the latest offset and doesn’t skip records sent before its first fetch:

private void configureShareGroupOffsetReset() throws ExecutionException, InterruptedException { try (Admin admin = Admin.create(Map.of(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers))) { ConfigResource shareGroup = new ConfigResource(ConfigResource.Type.GROUP, SHARE_GROUP_ID); AlterConfigOp earliestOffsetReset = new AlterConfigOp( new ConfigEntry("share.auto.offset.reset", "earliest"), AlterConfigOp.OpType.SET); admin.incrementalAlterConfigs(Map.of(shareGroup, List.of(earliestOffsetReset))) .all() .get(); } }

The ShareKafkaListenerContainerFactory uses the previously created ShareConsumerFactory to provide the KafkaListenerContainerFactory bean:

@Value("${share.consumer.concurrency:1}") private int concurrency; @Bean public ShareKafkaListenerContainerFactory<String, Event> shareKafkaListenerContainerFactory( ShareConsumerFactory<String, Event> shareConsumerFactory) { ShareKafkaListenerContainerFactory<String, Event> factory = new ShareKafkaListenerContainerFactory<>(shareConsumerFactory); factory.getContainerProperties() .setShareAckMode(ContainerProperties.ShareAckMode.IMPLICIT); factory.setConcurrency(concurrency); return factory; }

Interestingly, the configuration is almost identical to the configuration we’d apply for a non-share consumer group except for the classes we have used. Specifically, DefaultShareConsumerFactory replaces DefaultConsumerFactory and ShareKafkaListenerContainerFactory replaces ConcurrentKafkaListenerContainerFactory. Moreover, invoking setConcurrency(n) starts n threads, and each joins the share group as a separate member. Unlike a classic consumer group, where threads beyond the partition count sit idle, all of them can receive records from the same partition.

4. Consumer

With all the components in place, it’s finally time to implement the event consumer:

@KafkaListener( topics = "stopic", groupId = "shgroup", containerFactory = "shareKafkaListenerContainerFactory" ) public void consume(ConsumerRecord<String, Event> record) { log.info("Thread: {} - Doing some heavy work for key {} ...", Thread.currentThread() .threadId(), record.key()); try { // 5 second wait that simulates a long-running process Thread.sleep(5000L); } catch (InterruptedException e) { throw new RuntimeException(e); } log.info("Thread: {} - Finished heavy work for key {} ...", Thread.currentThread() .threadId(), record.key()); }

When record consumption is slow and random record processing order is acceptable, the share consumers feature is a good approach. For this reason, the consume() method explicitly waits for five seconds by using Thread.sleep() to simulate a slow processing scenario. Every listener that subscribes to the “stopic” topic with the same groupId becomes a member of that share group, and the members share the topic’s records between them.

5. Verification

Let’s create an integration test that verifies concurrent message consumption. For this test case, we’ll need two EventShareConsumer Spring beans:

@Configuration public class DualConsumersConfiguration { @Bean("eventShareConsumer1") public EventShareConsumer eventShareConsumer1() { return new EventShareConsumer(); } @Bean("eventShareConsumer2") public EventShareConsumer eventShareConsumer2() { return new EventShareConsumer(); } }

To verify that both consumer instances consume an event, let’s write a test case in which we send two messages, and we verify that both consumers receive a message:

@Autowired private KafkaTemplate<String, Event> kafkaTemplate; @MockitoSpyBean("eventShareConsumer1") private EventShareConsumer eventShareConsumer1; @MockitoSpyBean("eventShareConsumer2") private EventShareConsumer eventShareConsumer2; @Test void givenMultipleEvents_whenSent_thenAllConsumersConsume() { kafkaTemplate.send(TOPIC, "1", new Event(1L, "first")); kafkaTemplate.send(TOPIC, "2", new Event(2L, "second")); await().atMost(Duration.ofSeconds(7L)) .pollInterval(Duration.ofSeconds(1L)) .untilAsserted(() -> verify(eventShareConsumer1, times(1)) .consume(argThat((ConsumerRecord<String, Event> record) -> List.of(1L, 2L) .contains(record.value() .id())))); await().atMost(Duration.ofSeconds(7L)) .pollInterval(Duration.ofSeconds(1L)) .untilAsserted(() -> verify(eventShareConsumer2, times(1)) .consume(argThat((ConsumerRecord<String, Event> record) -> List.of(1L, 2L) .contains(record.value() .id())))); }

Our test case verifies that eventShareConsumer1 and eventShareConsumer2 instances consume one message each within a given timeframe. Simply put, while one consumer processes the first generated event for 5 seconds, the other consumes the second event, proving that our setup takes full advantage of the share consumers feature. Additionally, we use two beans with the same groupId rather than more threads, so each spy tells us which member handled which record. To the broker, two one-thread beans and one two-thread bean look the same.

6. Acknowledgement Modes and Error Handling

Because the broker manages the message state, acknowledgement happens at the record level. In other words, we can only acknowledge single records implicitly, explicitly, or manually. To demonstrate the implicit and explicit modes, we use the ThrowingEventShareConsumer, which throws an exception for every record it receives:

@KafkaListener(topics = "stopic", groupId = "shgroup", containerFactory = "shareKafkaListenerContainerFactory") public void consume(ConsumerRecord<String, Event> record) { // Simulating erroneous event consumption throw new RuntimeException("Something went wrong!"); }

6.1. Implicit Mode

In Spring Kafka 4.1, the default acknowledgement mode is explicit. That’s why the factory we defined in Section 3 sets the implicit mode itself:

shareKafkaListenerContainerFactory.getContainerProperties() .setShareAckMode(ContainerProperties.ShareAckMode.IMPLICIT);

Let’s write a test case to verify that the consumer doesn’t consume a message twice if the first consume() attempt fails:

@Test void givenSingleEvent_whenSent_thenItIsNotRetried() { kafkaTemplate.send(TOPIC, "1", new Event(1L, "first")); await().during(Duration.ofSeconds(5)) .atMost(Duration.ofSeconds(15)) .pollInterval(Duration.ofSeconds(1)) .untilAsserted(() -> verify(throwingEventShareConsumer, times(1)) .consume(argThat((ConsumerRecord<String, Event> record) -> record.value() .id() == 1L))); }

6.2. Explicit Mode

On the other hand, explicit mode enables us to define what happens in case of an exception by setting a ShareConsumerRecordRecoverer:

shareKafkaListenerContainerFactory.getContainerProperties() .setShareAckMode(ContainerProperties.ShareAckMode.EXPLICIT); shareKafkaListenerContainerFactory.setShareConsumerRecordRecoverer(ShareConsumerRecordRecoverer.REJECTING);

At first glance, explicit mode with the rejecting recoverer behaves like implicit mode, since the failed record isn’t redelivered in either case. However, the outcome differs. In implicit mode, the broker accepts the record as if it had been processed successfully, and the failure goes unnoticed. With rejecting, Spring Kafka logs the failure and rejects the record, so the broker archives it as a failed record. In fact, the same givenSingleEvent_whenSent_thenItIsNotRetried() integration test from the implicit mode also passes with the rejecting recoverer, since the failed record arrives for processing exactly once.

On the contrary, ShareConsumerRecordRecoverer.RELEASING instructs the broker to resend the record for processing:

shareKafkaListenerContainerFactory.getContainerProperties() .setShareAckMode(ContainerProperties.ShareAckMode.EXPLICIT); shareKafkaListenerContainerFactory.setShareConsumerRecordRecoverer(ShareConsumerRecordRecoverer.RELEASING);

For the explicit mode and ShareConsumerRecordRecoverer.RELEASING combination, the test case asserts that a record is consumed at least twice:

@Test void givenSingleEvent_whenSent_thenItIsRetried() { kafkaTemplate.send(TOPIC, UUID.randomUUID() .toString(), new Event(1L, "first")); await().atMost(Duration.ofSeconds(10)) .pollInterval(Duration.ofMillis(1000)) .untilAsserted(() -> verify(throwingEventShareConsumer, atLeast(2)) .consume(argThat((ConsumerRecord<String, Event> record) -> List.of(1L) .contains(record.value() .id())))); }

Note that a released record isn’t retried forever. The broker counts delivery attempts for each record, and once it reaches group.share.delivery.count.limit, it archives the record instead of delivering it again.

6.3. Manual Mode

Lastly, in manual mode, the listener handles a record individually, by accepting, rejecting, or releasing it:

@KafkaListener(topics = "stopic", groupId = "shgroup", containerFactory = "shareKafkaListenerContainerFactory") public void consume(ConsumerRecord<String, Event> record, ShareAcknowledgment acknowledgment) { try { doConsume(record); acknowledgment.acknowledge(); } catch (TransientException e) { acknowledgment.release(); } catch (RuntimeException e) { acknowledgment.reject(); } }

As with the other modes, we need to set the ShareAckMode.MANUAL acknowledgement mode on the ShareKafkaListenerContainerFactory:

shareKafkaListenerContainerFactory.getContainerProperties() .setShareAckMode(ContainerProperties.ShareAckMode.MANUAL);

In this implementation, when the consumer throws a TransientException, the broker resends the record to a consumer:

@Test void givenSingleEvent_whenTransientException_thenItIsRetried() { kafkaTemplate.send(TOPIC, "3", new Event(3L, "first")); await().atMost(Duration.ofSeconds(10)) .pollInterval(Duration.ofMillis(1000)) .untilAsserted(() -> verify(manualAckEventShareConsumer, atLeast(2)).consume(argThat( (ConsumerRecord<String, Event> record) -> List.of(3L) .contains(record.value() .id())), any(ShareAcknowledgment.class))); }

Next, let’s verify that a record that causes a non-transient failure arrives exactly once:

@Test void givenSingleEvent_whenNonTransientException_thenItIsNotRetried() { kafkaTemplate.send(TOPIC, "1", new Event(1L, "first")); await().during(Duration.ofSeconds(5)) .atMost(Duration.ofSeconds(15)) .pollInterval(Duration.ofSeconds(1)) .untilAsserted(() -> verify(manualAckEventShareConsumer, times(1)) .consume(argThat((ConsumerRecord<String, Event> record) -> record.value() .id() == 1L), any(ShareAcknowledgment.class))); }

Because the implementor handles errors independently, manual acknowledgement mode offers the greatest flexibility and covers the most complex needs an application might have.

7. Conclusion

In this article, we described how to use the share consumer in a Spring Boot application. Interestingly, this new feature allows us to utilize Apache Kafka without the need to calculate partitions beforehand based on the expected message rate. Additionally, we expanded on error handling and retry strategies.

As always, the complete source code for all the examples is available over on GitHub.

The post Share Consumer Support in Spring Boot for Apache Kafka first appeared on Baeldung.