00:00

Kafka Share Groups (Queues for Kafka)

Last updated:

Share groups, also known as Queues for Kafka (KIP-932), let many consumers work through the records of a topic cooperatively, like workers taking jobs from a queue. Unlike a classic consumer group, the number of consumers is not limited by the number of partitions, each record is acknowledged individually, and failed records are retried automatically up to a limit.

Share groups became production-ready in Apache Kafka 4.2, and Kafka 4.4 added dead-letter queue support. This tutorial explains how they differ from consumer groups, how record locks and delivery counts work, and how to use them with the Java KafkaShareConsumer and with Spring for Apache Kafka.

1. What Are Share Groups?

A share group is a new kind of group, next to the classic consumer group. Its members, called share consumers, subscribe to topics and fetch records, but the broker hands out individual records rather than whole partitions:

  • Several consumers can read from the same partition at the same time.
  • The group can have more consumers than partitions.
  • Each record is acknowledged individually, and the broker counts delivery attempts.

The data itself does not change: records still live in normal Kafka topics with normal retention, and the same topic can be read at the same time by consumer groups, other share groups and Kafka Streams.

2. Why Queue Semantics in Kafka?

Classic consumer groups assign each partition to exactly one consumer. That gives ordering per partition, but it also caps parallelism: a topic with 6 partitions can keep at most 6 consumers busy. For many workloads that cap is the wrong trade-off. Think of a topic of image-resizing jobs, emails to send or documents to scan: each record is independent, processing takes seconds, and the backlog would clear faster with 40 workers, not 6.

Before share groups, teams either over-partitioned topics, built their own work distribution on top of Kafka, or ran a separate message queue next to Kafka. Share groups provide queue-style consumption directly on Kafka topics.

3. Share Groups vs Consumer Groups

Consumer groupShare group
Unit of assignmentWhole partitions, one consumer eachPartitions shared by several consumers; records handed out individually
Maximum useful consumersNumber of partitionsNot limited by partitions
OrderingIn order within a partitionNo ordering guarantee
Progress trackingOne committed offset per partitionState per record (acquired, acknowledged, released, rejected)
Failed recordsApplication decides (retry, DLT, skip)Released records are redelivered automatically; delivery attempts are limited
Client APIKafkaConsumerKafkaShareConsumer
Best forOrdered event streams, state per key, stream processingIndependent work items: jobs, tasks, notifications

4. How Delivery Works: Locks and Delivery Counts

Share group record deliveryOne partition of the image-jobs topic holds offsets 100 to 109. Offsets 100 to 102 are acknowledged. Offsets 103 and 104 are acquired by consumer 1 with a 30-second lock, offsets 105 and 106 by consumer 2, and offset 107 by consumer 3, so three consumers read the same partition. Offsets 108 and 109 are available. If a lock expires or a consumer releases a record, it becomes available again and its delivery count increases; a record that reaches the delivery limit or is rejected is archived and is not delivered again. Partition 0 of topic "image-jobs" (one share group) 100–102acknowledged 103–104acquired by C1 105–106acquired by C2 107C3 108–109available Consumer 1 Consumer 2 Consumer 3 Lock expires or record releasedback to available, delivery count + 1 Rejected or delivery limit reachedarchived (optionally sent to a DLQ topic)
Records of one partition are spread across several consumers; each acquired record is locked for a limited time.
  1. A share consumer fetches; the broker acquires a batch of available records for it and locks them for share.record.lock.duration.ms (30 seconds by default). Other consumers in the same group cannot receive them meanwhile.
  2. The consumer processes the records and acknowledges each one. An accepted record is done for this group.
  3. If the consumer releases a record, or crashes and the lock expires, the record becomes available again and its delivery count goes up.
  4. When the count reaches share.delivery.count.limit (5 by default), or the consumer rejects the record, it is archived and not delivered again.

The broker limits how many records per partition can be locked at once (group.share.partition.max.record.locks), so a slow group cannot lock an unbounded amount of data. The per-record state of each share-partition is persisted by the share coordinator in an internal topic, which is why the Docker examples set replication settings for the share-coordinator state topic.

5. Acknowledging Records

Acknowledge typeMeaningUse when
ACCEPTProcessed successfullyThe work is done
RELEASEMake the record available for another attemptA temporary failure, such as a timeout from a downstream service
REJECTUnprocessable; do not deliver againInvalid data that will never succeed
RENEWExtend the lock because processing is still runningLong-running work that would exceed the lock duration

The client’s share.acknowledgement.mode decides how this happens. In implicit mode (the client default), calling poll() again or commitSync() accepts every record from the previous poll. In explicit mode, the application calls acknowledge(record, type) for each record and then commits; explicit mode is the right choice whenever some records may fail.

6. Example: A Java Share Consumer

The consumer below processes image-resizing jobs. Temporary failures are released for another attempt; bad jobs are rejected:

ImageJobWorker.java
package com.javabytechie.jobs;

import java.time.Duration;
import java.util.List;
import java.util.Properties;
import org.apache.kafka.clients.consumer.AcknowledgeType;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.KafkaShareConsumer;
import org.apache.kafka.common.serialization.StringDeserializer;

public class ImageJobWorker {

    public static void main(String[] args) {
        Properties props = new Properties();
        props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
        props.put(ConsumerConfig.GROUP_ID_CONFIG, "image-workers");          // the share group
        props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        props.put("share.acknowledgement.mode", "explicit");

        try (var consumer = new KafkaShareConsumer<String, String>(props)) {
            consumer.subscribe(List.of("image-jobs"));
            while (true) {
                for (ConsumerRecord<String, String> job : consumer.poll(Duration.ofMillis(500))) {
                    try {
                        resize(job.value());
                        consumer.acknowledge(job, AcknowledgeType.ACCEPT);
                    } catch (StorageUnavailableException e) {
                        consumer.acknowledge(job, AcknowledgeType.RELEASE);   // try again later
                    } catch (Exception e) {
                        consumer.acknowledge(job, AcknowledgeType.REJECT);    // never retry
                    }
                }
                consumer.commitSync();   // send the acknowledgements to the broker
            }
        }
    }

    private static void resize(String imagePath) { /* call the image service */ }

    static class StorageUnavailableException extends RuntimeException { }
}

Start the same program ten times and all ten instances receive work, even if image-jobs has only three partitions. If one instance is killed in the middle of a job, its locks expire after 30 seconds and the jobs are delivered to another instance.

7. Share Consumers in Spring Boot

Spring for Apache Kafka supports share consumers since version 4.0 (fully supported since 4.1 on Kafka 4.2). You define a ShareConsumerFactory and a ShareKafkaListenerContainerFactory, then point a normal @KafkaListener at it:

ShareConsumerConfig.java
@Configuration
public class ShareConsumerConfig {

    @Bean
    public ShareConsumerFactory<String, String> shareConsumerFactory() {
        Map<String, Object> props = Map.of(
                ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092",
                ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class,
                ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        return new DefaultShareConsumerFactory<>(props);
    }

    @Bean
    public ShareKafkaListenerContainerFactory<String, String> shareKafkaListenerContainerFactory(
            ShareConsumerFactory<String, String> shareConsumerFactory) {
        var factory = new ShareKafkaListenerContainerFactory<>(shareConsumerFactory);
        factory.setConcurrency(5);                     // five share consumers per instance
        factory.getContainerProperties().setShareAckMode(ContainerProperties.ShareAckMode.MANUAL);
        return factory;
    }
}
ImageJobListener.java
@Component
public class ImageJobListener {

    @KafkaListener(topics = "image-jobs", groupId = "image-workers",
                   containerFactory = "shareKafkaListenerContainerFactory")
    public void onJob(ConsumerRecord<String, String> job, ShareAcknowledgment ack) {
        try {
            resize(job.value());
            ack.acknowledge();          // ACCEPT
        } catch (StorageUnavailableException e) {
            ack.release();              // redeliver later
        } catch (Exception e) {
            ack.reject();               // give up on this record
        }
    }
}

Without manual acknowledgement, the Spring container accepts a record when the listener returns normally and, by default, rejects it when the listener throws. See the Spring documentation for lock renewal of long-running work.

8. Important Configuration

SettingLevelDefaultWhat it does
share.record.lock.duration.msGroup30000How long an acquired record stays locked to one consumer
share.delivery.count.limitGroup5Maximum delivery attempts before a record is archived
share.auto.offset.resetGrouplatestWhere a new share group starts: latest, earliest or by_duration:
share.isolation.levelGroupread_uncommittedSet read_committed to skip records of aborted transactions
share.session.timeout.msGroup45000How quickly a failed share consumer is removed from the group
share.acknowledgement.modeClientimplicitexplicit requires acknowledge() for each record

Group-level settings are changed dynamically, for example with kafka-configs.sh --entity-type groups --entity-name image-workers --alter --add-config share.auto.offset.reset=earliest.

Starting position: because the default is latest, a new share group ignores records that were already in the topic. Set share.auto.offset.reset=earliest before the first consumer starts if existing jobs must be processed.

9. Dead-Letter Queues for Share Groups

Kafka 4.4 adds dead-letter queue support for share groups. When the share.version feature is upgraded to 2 and a group sets errors.deadletterqueue.topic.name, records that are rejected or exceed the delivery limit become eligible for the DLQ topic instead of only being archived. By default the DLQ record carries metadata (group, topic, partition, offset, delivery count); set errors.deadletterqueue.copy.record.enable=true on the group to copy the original record data as well. DLQ topic names must start with the cluster’s errors.deadletterqueue.topic.name.prefix (dlq. by default).

10. Operating Share Groups

Share groups are managed with kafka-share-groups.sh:

Terminal
bin/kafka-share-groups.sh --bootstrap-server localhost:9092 --list
bin/kafka-share-groups.sh --bootstrap-server localhost:9092 --describe --group image-workers
# GROUP          TOPIC       PARTITION  START-OFFSET  LAG
# image-workers  image-jobs  0          4             0

The start offset is the earliest offset still being evaluated for delivery; some records after it may already be done. If share groups are not available on a cluster that was upgraded from an older version, check the share.version feature with kafka-features.sh describe and upgrade it with kafka-features.sh upgrade --feature share.version=1.

11. When Not to Use Share Groups

  • Order matters. Records of one partition, and therefore of one key, may be processed by different consumers in any order. Keep consumer groups for state changes per entity, such as account balances.
  • Stream processing and aggregations. Kafka Streams and windowed state rely on partition ownership.
  • Exactly-once pipelines. Delivery is at least once: a record whose lock expires during slow processing can be processed twice, so handlers must be idempotent.

12. Common Mistakes

  • Lock shorter than processing time. Jobs that take 45 seconds with a 30-second lock are redelivered while still running; raise the lock duration or renew it.
  • Implicit mode with failing records. In implicit mode, the next poll() accepts every record, including ones whose processing failed.
  • Forgetting the start position. A new group with the default latest skips the existing backlog.
  • Using share groups for ordered events. Out-of-order processing of “created” and “cancelled” events for the same order leads to wrong state.
  • Non-idempotent handlers. Redelivery after crashes or lock expiry is normal; deduplicate with a job ID where side effects are not repeatable.

13. Summary

Share groups bring queue semantics to Kafka: consumers share partitions, the group can grow beyond the partition count, records are acknowledged individually, and failures are retried up to a delivery limit, with optional dead-lettering since Kafka 4.4. Use them for independent work items, keep classic consumer groups for ordered streams, size the lock duration to your processing time, use explicit acknowledgement when records can fail, and make handlers idempotent.

15. References