Apache Kafka: an introduction

Kafka stores events in partitioned, append-only logs that many applications can read independently and replay. This page explains the log, offsets, consumer groups, KRaft and the new share groups, and runs each idea as a Java program against a real broker started inside the program.

Share

Contents

What Kafka is and how it works

Apache Kafka is a distributed event log. Applications write records to it, Kafka stores them on disk in the order they arrived, and any number of other applications read them, at their own pace, for as long as the records are kept. A record is a small message with a key, a value, optional headers and a timestamp, such as "user ann viewed /cart".

The log is the central idea. A message queue hands each message to one receiver and then deletes it. Kafka never deletes a record because someone read it. Each reader only remembers how far it has got, as a number called the offset. That one design choice explains most of Kafka's behaviour: several systems can read the same data independently, a reader can rewind and process history again, and a slow reader does not slow down the writer.

Underneath, a topic is split into partitions. Each partition is an append-only file of records on a broker's disk, and each record gets the next offset in its partition: 0, 1, 2 and so on. Appending to the end of a file and reading it sequentially is what disks and the operating system's page cache do best, which is why a single broker can handle hundreds of megabytes per second. Partitions are also the unit of scaling. They are spread over the brokers of a cluster, and each one is copied to several brokers so that a failed machine loses nothing.

The building blocks of Kafka
PartWhat it isCovered in detail
RecordKey, value, headers and timestamp, stored as bytesSerialization
TopicA named stream of records, such as page-viewsTopics and partitions
PartitionAn ordered, append-only log; order is kept only inside one partitionTopics and partitions
OffsetThe position of a record in its partitionOffsets
BrokerA server that stores partitions and serves clientsThis page
ControllerA node that keeps the cluster's metadata with the KRaft protocolThis page
ProducerA client that appends records to topicsProducers
Consumer groupConsumers that share the partitions of a topic between themConsumers
Share groupConsumers that take records from a topic like a queue (production-ready since Kafka 4.2)This page

This page uses Apache Kafka 4.2 and its Java client, kafka-clients 4.2.2. Kafka 4.0 removed ZooKeeper: clusters now keep their metadata in Kafka itself, using KRaft. Each example is a complete program that starts its own single-node broker inside the same JVM first, with EmbeddedKafkaKraftBroker from spring-kafka-test; the startBroker method at the end of each program does this. Everything else uses the plain Kafka client APIs, exactly as against a real cluster, which has three or more brokers.

A first topic, producer and consumer

Page views keyed by user are a typical first stream: there are many of them, and each user's views should stay in order. The program creates a topic with three partitions, writes six views and reads them back:

Java
import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import org.apache.kafka.clients.admin.Admin;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;

public class FirstEvents {

    public static void main(String[] args) throws Exception {
        EmbeddedKafkaBroker broker = startBroker();
        String servers = broker.getBrokersAsString();
        try {
            // 1. a topic with 3 partitions, created through the Admin API
            try (Admin admin = Admin.create(Map.of("bootstrap.servers", servers))) {
                admin.createTopics(List.of(new NewTopic("page-views", 3, (short) 1)))
                        .all().get();
                System.out.println("topics: " + admin.listTopics().names().get());
            }

            // 2. a producer appends six events, keyed by user
            Map<String, Object> producerProps = Map.of(
                    "bootstrap.servers", servers,
                    "key.serializer", StringSerializer.class,
                    "value.serializer", StringSerializer.class);
            try (KafkaProducer<String, String> producer = new KafkaProducer<>(producerProps)) {
                String[][] views = {{"ann", "/home"}, {"ben", "/home"}, {"ann", "/cart"},
                    {"cat", "/search"}, {"ben", "/product/7"}, {"ann", "/checkout"}};
                for (String[] view : views) {
                    RecordMetadata meta = producer.send(
                            new ProducerRecord<>("page-views", view[0], view[1])).get();
                    System.out.printf("wrote %-4s %-11s -> partition %d, offset %d%n",
                            view[0], view[1], meta.partition(), meta.offset());
                }
            }

            // 3. a consumer in group "analytics" reads everything from the start
            Map<String, Object> consumerProps = Map.of(
                    "bootstrap.servers", servers,
                    "group.id", "analytics",
                    "auto.offset.reset", "earliest",
                    "key.deserializer", StringDeserializer.class,
                    "value.deserializer", StringDeserializer.class);
            List<ConsumerRecord<String, String>> read = new ArrayList<>();
            try (KafkaConsumer<String, String> consumer = new KafkaConsumer<>(consumerProps)) {
                consumer.subscribe(List.of("page-views"));
                while (read.size() < 6) {
                    consumer.poll(Duration.ofSeconds(1)).forEach(read::add);
                }
            }
            // records from different partitions arrive in no fixed order, so sort them
            read.sort(Comparator.comparingInt(ConsumerRecord<String, String>::partition)
                    .thenComparingLong(ConsumerRecord::offset));
            for (ConsumerRecord<String, String> r : read) {
                System.out.printf("read  partition %d, offset %d: key=%s value=%s%n",
                        r.partition(), r.offset(), r.key(), r.value());
            }
        } finally {
            broker.destroy();
        }
    }

    // Starts a single-node KRaft broker inside this JVM, from spring-kafka-test
    static EmbeddedKafkaBroker startBroker() {
        // the broker logs at INFO and prints its storage setup, so both are silenced.
        // Logback's Logger is named in full: org.slf4j.Logger, imported, has no setLevel
        ((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
                .setLevel(Level.ERROR);
        PrintStream stdout = System.out;
        System.setOut(new PrintStream(OutputStream.nullOutputStream()));
        try {
            // one broker cannot hold the default 3 copies of the transaction log
            EmbeddedKafkaBroker broker = new EmbeddedKafkaKraftBroker(1, 1).brokerProperties(
                    Map.of("transaction.state.log.replication.factor", "1",
                            "transaction.state.log.min.isr", "1"));
            broker.afterPropertiesSet();
            return broker;
        } finally {
            System.setOut(stdout);
        }
    }
}
Output
topics: [page-views]
wrote ann  /home       -> partition 2, offset 0
wrote ben  /home       -> partition 1, offset 0
wrote ann  /cart       -> partition 2, offset 1
wrote cat  /search     -> partition 2, offset 2
wrote ben  /product/7  -> partition 1, offset 1
wrote ann  /checkout   -> partition 2, offset 3
read  partition 1, offset 0: key=ben value=/home
read  partition 1, offset 1: key=ben value=/product/7
read  partition 2, offset 0: key=ann value=/home
read  partition 2, offset 1: key=ann value=/cart
read  partition 2, offset 2: key=cat value=/search
read  partition 2, offset 3: key=ann value=/checkout
  • The topic was created through the Admin client, with 3 partitions and a replication factor of 1, the most a one-broker cluster can hold.
  • Every record for ann went to partition 2, and every record for ben to partition 1. The producer hashes the key to pick the partition, so one key always lands in one partition.
  • Offsets count per partition. Partition 2 has offsets 0 to 3, partition 1 has 0 and 1, and partition 0 received nothing: with only three keys, the hash happened to leave it empty.
  • Read back, ann's views are in the order she made them: /home, /cart, /checkout. Kafka guarantees this order inside a partition, and only there.
  • The consumer needed auto.offset.reset=earliest. A new group starts at the end of the log by default, and would have seen nothing.

Keys and values travel as bytes. StringSerializer and StringDeserializer convert them; JSON, Avro and Protobuf are the usual choices for real data.

Reading does not delete: the log and consumer groups

Payments are a good example of data that several systems need: billing books them and fraud detection scores them. Both read the same topic here, each in its own consumer group:

Java
import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;

public class LogNotQueue {

    static String servers;

    public static void main(String[] args) throws Exception {
        EmbeddedKafkaBroker broker = startBroker();
        servers = broker.getBrokersAsString();
        try {
            broker.addTopics("payments");
            try (KafkaProducer<String, String> producer = new KafkaProducer<>(Map.of(
                    "bootstrap.servers", servers,
                    "key.serializer", StringSerializer.class,
                    "value.serializer", StringSerializer.class))) {
                for (int i = 1; i <= 4; i++) {
                    producer.send(new ProducerRecord<>("payments", "pay-" + i, i * 10 + " EUR"));
                }
            } // close() waits until every record is sent

            System.out.println("group billing, 1st run : " + readAll("billing"));
            System.out.println("group fraud,   1st run : " + readAll("fraud"));
            System.out.println("group billing, 2nd run : " + readAll("billing"));

            // nothing was deleted by reading: a consumer can go back to the start
            try (KafkaConsumer<String, String> consumer = consumer("billing")) {
                consumer.subscribe(List.of("payments"));
                while (consumer.assignment().isEmpty()) {
                    consumer.poll(Duration.ofMillis(100));
                }
                consumer.seekToBeginning(consumer.assignment());
                List<String> again = new ArrayList<>();
                while (again.size() < 4) {
                    consumer.poll(Duration.ofSeconds(1)).forEach(r -> again.add(r.key()));
                }
                System.out.println("group billing, rewound : " + again);
            }
        } finally {
            broker.destroy();
        }
    }

    // polls until no record arrives for 2 seconds; closing commits the group's position
    static List<String> readAll(String group) {
        List<String> keys = new ArrayList<>();
        try (KafkaConsumer<String, String> consumer = consumer(group)) {
            consumer.subscribe(List.of("payments"));
            long quietSince = System.currentTimeMillis();
            // stop after 2 quiet seconds, counted from when the group assigned partitions
            while (System.currentTimeMillis() - quietSince < 2000) {
                for (ConsumerRecord<String, String> r : consumer.poll(Duration.ofMillis(200))) {
                    keys.add(r.key() + "@" + r.offset());
                    quietSince = System.currentTimeMillis();
                }
                if (consumer.assignment().isEmpty()) {
                    quietSince = System.currentTimeMillis();
                }
            }
        }
        return keys;
    }

    static KafkaConsumer<String, String> consumer(String group) {
        Map<String, Object> props = new HashMap<>();
        props.put("bootstrap.servers", servers);
        props.put("group.id", group);
        props.put("auto.offset.reset", "earliest");
        props.put("key.deserializer", StringDeserializer.class);
        props.put("value.deserializer", StringDeserializer.class);
        return new KafkaConsumer<>(props);
    }

    // Starts a single-node KRaft broker inside this JVM, from spring-kafka-test
    static EmbeddedKafkaBroker startBroker() {
        // the broker logs at INFO and prints its storage setup, so both are silenced.
        // Logback's Logger is named in full: org.slf4j.Logger, imported, has no setLevel
        ((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
                .setLevel(Level.ERROR);
        PrintStream stdout = System.out;
        System.setOut(new PrintStream(OutputStream.nullOutputStream()));
        try {
            // one broker cannot hold the default 3 copies of the transaction log
            EmbeddedKafkaBroker broker = new EmbeddedKafkaKraftBroker(1, 1).brokerProperties(
                    Map.of("transaction.state.log.replication.factor", "1",
                            "transaction.state.log.min.isr", "1"));
            broker.afterPropertiesSet();
            return broker;
        } finally {
            System.setOut(stdout);
        }
    }
}
Output
group billing, 1st run : [pay-1@0, pay-2@1, pay-3@2, pay-4@3]
group fraud,   1st run : [pay-1@0, pay-2@1, pay-3@2, pay-4@3]
group billing, 2nd run : []
group billing, rewound : [pay-1, pay-2, pay-3, pay-4]
  • The billing and fraud groups each received all four payments, offsets 0 to 3. A queue would have given each payment to only one of them.
  • The second billing run got nothing. When the first billing consumer closed, it committed its position, offset 4, to Kafka, and the next consumer in the group continued from there.
  • The records were still in the log. seekToBeginning moved the consumer back to offset 0, and it read all four again.

The committed positions live in an internal topic, __consumer_offsets, so they survive restarts of both consumers and brokers. Records are removed only by the topic's retention settings: by default after 7 days (log.retention.hours=168), or when a size limit is reached. A compacted topic keeps instead the latest record for each key. Because history stays available, a new service can start from offset 0 and build its own view of all past events, which is the idea behind event sourcing and change data capture.

Consumer groups split the partitions

A topic with more traffic than one consumer can handle is read by several consumers in the same group. Kafka assigns each partition to exactly one member of the group. The program adds consumers to a group one at a time, for a topic with four partitions, and prints the assignment after each change:

Java
import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;

public class GroupScaling {

    public static void main(String[] args) throws Exception {
        EmbeddedKafkaBroker broker = startBroker();
        try {
            broker.addTopics(new NewTopic("invoices", 4, (short) 1));
            List<KafkaConsumer<String, String>> group = new ArrayList<>();
            for (int size = 1; size <= 5; size++) {
                KafkaConsumer<String, String> consumer = new KafkaConsumer<>(Map.of(
                        "bootstrap.servers", broker.getBrokersAsString(),
                        "group.id", "invoicing",
                        "key.deserializer", StringDeserializer.class,
                        "value.deserializer", StringDeserializer.class));
                consumer.subscribe(List.of("invoices"));
                group.add(consumer);
                waitUntilBalanced(group);
                StringBuilder line = new StringBuilder(size + " consumer(s):");
                for (int i = 0; i < group.size(); i++) {
                    TreeSet<Integer> parts = new TreeSet<>();
                    group.get(i).assignment().forEach(tp -> parts.add(tp.partition()));
                    line.append("  c").append(i + 1).append("=").append(parts);
                }
                System.out.println(line);
            }
            group.forEach(KafkaConsumer::close);
        } finally {
            broker.destroy();
        }
    }

    // every member must keep polling to take part in a rebalance
    static void waitUntilBalanced(List<KafkaConsumer<String, String>> group) {
        while (true) {
            group.forEach(c -> c.poll(Duration.ofMillis(50)));
            List<TopicPartition> all = new ArrayList<>();
            group.forEach(c -> all.addAll(c.assignment()));
            boolean spread = group.size() > 4
                    || group.stream().noneMatch(c -> c.assignment().isEmpty());
            if (all.size() == 4 && new TreeSet<>(all.stream().map(TopicPartition::partition)
                    .toList()).size() == 4 && spread) {
                return;
            }
        }
    }

    // Starts a single-node KRaft broker inside this JVM, from spring-kafka-test
    static EmbeddedKafkaBroker startBroker() {
        // the broker logs at INFO and prints its storage setup, so both are silenced.
        // Logback's Logger is named in full: org.slf4j.Logger, imported, has no setLevel
        ((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
                .setLevel(Level.ERROR);
        PrintStream stdout = System.out;
        System.setOut(new PrintStream(OutputStream.nullOutputStream()));
        try {
            // one broker cannot hold the default 3 copies of the transaction log
            EmbeddedKafkaBroker broker = new EmbeddedKafkaKraftBroker(1, 1).brokerProperties(
                    Map.of("transaction.state.log.replication.factor", "1",
                            "transaction.state.log.min.isr", "1"));
            broker.afterPropertiesSet();
            return broker;
        } finally {
            System.setOut(stdout);
        }
    }
}
Output
1 consumer(s):  c1=[0, 1, 2, 3]
2 consumer(s):  c1=[0, 1]  c2=[2, 3]
3 consumer(s):  c1=[0, 1]  c2=[2]  c3=[3]
4 consumer(s):  c1=[0]  c2=[1]  c3=[2]  c4=[3]
5 consumer(s):  c1=[0]  c2=[1]  c3=[2]  c4=[3]  c5=[]
  • One consumer received all four partitions.
  • Each new member triggered a rebalance, after which the partitions were spread again: 2 and 2, then 2, 1 and 1, then one each.
  • The fifth consumer received nothing. A partition is never shared by two members of one group, so the partition count is the upper limit on parallelism within a group.

Because each partition has one reader, records in a partition are processed in order, one at a time. That is the trade the log makes: ordering and very cheap bookkeeping (one offset per partition) in exchange for a fixed maximum parallelism. Pick a partition count with room to grow, because adding partitions later moves keys to different partitions. The rebalance protocol itself, and how Kafka 4.0's new consumer protocol (KIP-848) reduces its pauses, is on the rebalancing page.

Brokers, controllers and KRaft

A Kafka cluster has two roles. Brokers store partitions and serve producers and consumers. Controllers hold the cluster metadata: which topics exist, which broker leads each partition and which replicas are in sync. Since Kafka 4.0 the controllers keep this metadata in a replicated log of their own, using the Raft consensus protocol (KRaft). The program asks the in-process cluster how it is set up:

Java
import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;
import org.apache.kafka.clients.admin.Admin;
import org.apache.kafka.clients.admin.Config;
import org.apache.kafka.clients.admin.DescribeClusterResult;
import org.apache.kafka.clients.admin.FeatureMetadata;
import org.apache.kafka.clients.admin.ListTopicsOptions;
import org.apache.kafka.clients.admin.QuorumInfo;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.config.ConfigResource;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;

public class ClusterInfo {

    public static void main(String[] args) throws Exception {
        EmbeddedKafkaBroker broker = startBroker();
        String servers = broker.getBrokersAsString();
        try (Admin admin = Admin.create(Map.of("bootstrap.servers", servers))) {
            DescribeClusterResult cluster = admin.describeCluster();
            System.out.println("brokers                   : "
                    + cluster.nodes().get().stream().map(n -> "id " + n.id()).toList());

            QuorumInfo quorum = admin.describeMetadataQuorum().quorumInfo().get();
            System.out.println("KRaft leader              : node " + quorum.leaderId());
            System.out.println("KRaft voters              : " + quorum.voters().stream()
                    .map(QuorumInfo.ReplicaState::replicaId).toList());

            Config config = admin.describeConfigs(List.of(
                    new ConfigResource(ConfigResource.Type.BROKER, "0"))).all().get()
                    .values().iterator().next();
            for (String name : List.of("process.roles", "num.partitions",
                    "default.replication.factor", "log.retention.hours")) {
                System.out.printf("%-26s: %s%n", name, config.get(name).value());
            }

            FeatureMetadata features = admin.describeFeatures().featureMetadata().get();
            System.out.println("finalized features        : "
                    + new TreeSet<>(features.finalizedFeatures().keySet()));

            System.out.println("topics before             : " + topics(admin));
            broker.addTopics("orders");
            try (KafkaConsumer<String, String> consumer = new KafkaConsumer<>(Map.of(
                    "bootstrap.servers", servers, "group.id", "audit",
                    "key.deserializer", StringDeserializer.class,
                    "value.deserializer", StringDeserializer.class))) {
                consumer.subscribe(List.of("orders"));
                consumer.poll(Duration.ofSeconds(3));
                consumer.commitSync();
            }
            System.out.println("topics after              : " + topics(admin));
        } finally {
            broker.destroy();
        }
    }

    static TreeSet<String> topics(Admin admin) throws Exception {
        return new TreeSet<>(admin.listTopics(new ListTopicsOptions().listInternal(true))
                .names().get());
    }

    // Starts a single-node KRaft broker inside this JVM, from spring-kafka-test
    static EmbeddedKafkaBroker startBroker() {
        // the broker logs at INFO and prints its storage setup, so both are silenced.
        // Logback's Logger is named in full: org.slf4j.Logger, imported, has no setLevel
        ((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
                .setLevel(Level.ERROR);
        PrintStream stdout = System.out;
        System.setOut(new PrintStream(OutputStream.nullOutputStream()));
        try {
            // one broker cannot hold the default 3 copies of the transaction log
            EmbeddedKafkaBroker broker = new EmbeddedKafkaKraftBroker(1, 1).brokerProperties(
                    Map.of("transaction.state.log.replication.factor", "1",
                            "transaction.state.log.min.isr", "1"));
            broker.afterPropertiesSet();
            return broker;
        } finally {
            System.setOut(stdout);
        }
    }
}
Output
brokers                   : [id 0]
KRaft leader              : node 0
KRaft voters              : [0]
process.roles             : broker,controller
num.partitions            : 1
default.replication.factor: 1
log.retention.hours       : 168
finalized features        : [eligible.leader.replicas.version, group.version, metadata.version, share.version, streams.version, transaction.version]
topics before             : []
topics after              : [__consumer_offsets, orders]
  • The cluster has one broker, node 0. The same node is also the only KRaft voter and the leader of the metadata quorum.
  • process.roles = broker,controller shows the combined mode, where one process plays both roles. It suits development. Production clusters usually run three or five dedicated controllers and separate brokers.
  • num.partitions and default.replication.factor are both 1, the broker defaults. They apply to topics created automatically; production topics should be created explicitly with a replication factor of 3.
  • log.retention.hours = 168 is the 7-day default retention.
  • The finalized features are versions the whole cluster has agreed on, such as share.version, which enables share groups. They let a cluster be upgraded one node at a time before new features are switched on.
  • The internal __consumer_offsets topic did not exist until a consumer group committed an offset.

Replication is the part one broker cannot show. In a real cluster each partition has a leader replica, which handles all writes, and follower replicas on other brokers, which copy it. The followers that are up to date form the in-sync replica set (ISR). With a replication factor of 3 and min.insync.replicas=2, a producer using acks=all gets its acknowledgement only after at least two copies exist, and the cluster survives the loss of one broker without losing acknowledged records. When a leader fails, the controller makes an in-sync follower the new leader. The topics and partitions page runs a three-broker cluster in one JVM to show this.

KRaft replaced ZooKeeper, which earlier Kafka versions needed as a separate system. Clusters still on ZooKeeper must migrate to KRaft on a 3.x release, 3.9 being the last, before upgrading to 4.x. Kafka 4.0 also raised the minimum Java version to 11 for clients and 17 for brokers.

Queue semantics with share groups

Some workloads are a queue of independent jobs, such as sending e-mails or resizing images, where order does not matter but parallelism does. With consumer groups, the number of workers is capped by the partition count. Share groups (KIP-932), production-ready since Kafka 4.2, remove that cap: all members of a share group can take records from the same partition, and each record is acknowledged one by one. This program runs two workers on a topic with a single partition. Job 3 fails on its first attempt:

Java
import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.kafka.clients.admin.Admin;
import org.apache.kafka.clients.admin.AlterConfigOp;
import org.apache.kafka.clients.admin.ConfigEntry;
import org.apache.kafka.clients.consumer.AcknowledgeType;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.KafkaShareConsumer;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.config.ConfigResource;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;

public class ShareGroupQueue {

    public static void main(String[] args) throws Exception {
        EmbeddedKafkaBroker broker = startBroker();
        String servers = broker.getBrokersAsString();
        try {
            broker.addTopics("jobs"); // ONE partition
            try (Admin admin = Admin.create(Map.of("bootstrap.servers", servers))) {
                // a share group starts at the latest offset unless told otherwise
                ConfigResource group = new ConfigResource(ConfigResource.Type.GROUP, "workers");
                admin.incrementalAlterConfigs(Map.of(group, List.of(new AlterConfigOp(
                        new ConfigEntry("share.auto.offset.reset", "earliest"),
                        AlterConfigOp.OpType.SET)))).all().get();
            }
            try (KafkaProducer<String, String> producer = new KafkaProducer<>(Map.of(
                    "bootstrap.servers", servers,
                    "key.serializer", StringSerializer.class,
                    "value.serializer", StringSerializer.class))) {
                for (int i = 0; i < 6; i++) {
                    producer.send(new ProducerRecord<>("jobs", "job-" + i));
                }
            }

            Map<String, Object> props = new HashMap<>();
            props.put("bootstrap.servers", servers);
            props.put("group.id", "workers");
            props.put("share.acknowledgement.mode", "explicit");
            props.put("share.acquire.mode", "record_limit"); // hand out at most ...
            props.put("max.poll.records", 2);                 // ... 2 records per poll
            props.put("key.deserializer", StringDeserializer.class);
            props.put("value.deserializer", StringDeserializer.class);
            try (var w1 = new KafkaShareConsumer<String, String>(props);
                 var w2 = new KafkaShareConsumer<String, String>(props)) {
                w1.subscribe(List.of("jobs"));
                w2.subscribe(List.of("jobs"));
                int done = 0;
                for (int round = 0; done < 6 && round < 50; round++) {
                    done += work("w1", w1);
                    done += work("w2", w2);
                }
                System.out.println("jobs completed: " + done);
            }
        } finally {
            broker.destroy();
        }
    }

    // processes one poll; job-3 fails the first time it is seen and is released
    static int work(String name, KafkaShareConsumer<String, String> worker) {
        int accepted = 0;
        List<String> seen = new ArrayList<>();
        for (ConsumerRecord<String, String> r : worker.poll(Duration.ofMillis(500))) {
            int attempt = r.deliveryCount().orElse((short) 0);
            seen.add(r.value() + "@" + r.offset() + " try " + attempt);
            if (r.value().equals("job-3") && attempt == 1) {
                worker.acknowledge(r, AcknowledgeType.RELEASE); // give it back to the group
            } else {
                worker.acknowledge(r, AcknowledgeType.ACCEPT);
                accepted++;
            }
        }
        worker.commitSync();
        if (!seen.isEmpty()) {
            System.out.println(name + " got " + seen);
        }
        return accepted;
    }

    // Starts a single-node KRaft broker inside this JVM, from spring-kafka-test
    static EmbeddedKafkaBroker startBroker() {
        // the broker logs at INFO and prints its storage setup, so both are silenced.
        // Logback's Logger is named in full: org.slf4j.Logger, imported, has no setLevel
        ((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
                .setLevel(Level.ERROR);
        PrintStream stdout = System.out;
        System.setOut(new PrintStream(OutputStream.nullOutputStream()));
        try {
            // one broker cannot hold the default 3 copies of the share-group state log
            EmbeddedKafkaBroker broker = new EmbeddedKafkaKraftBroker(1, 1).brokerProperties(
                    Map.of("share.coordinator.state.topic.replication.factor", "1",
                            "share.coordinator.state.topic.min.isr", "1"));
            broker.afterPropertiesSet();
            return broker;
        } finally {
            System.setOut(stdout);
        }
    }
}
Output
w1 got [job-0@0 try 1, job-1@1 try 1]
w2 got [job-2@2 try 1, job-3@3 try 1]
w1 got [job-3@3 try 2, job-4@4 try 1]
w2 got [job-5@5 try 1]
jobs completed: 6
  • Both workers received records from the one partition, two at a time because of max.poll.records=2 with share.acquire.mode=record_limit. A consumer group would have given the whole partition to one of them. Which worker gets the first batch varies from run to run.
  • deliveryCount() was 1 for every first delivery.
  • Job 3 was released with AcknowledgeType.RELEASE and delivered again with a delivery count of 2. The broker counts attempts per record; after group.share.delivery.count.limit attempts, 5 by default, it gives up on the record and archives it.
  • All six jobs were finally accepted with AcknowledgeType.ACCEPT. REJECT marks a record as unprocessable, and RENEW, new in 4.2, extends the time a worker may hold a record.

The topic is still an ordinary log. A share group tracks which records are in flight and which are done, instead of a single offset, and there is no ordering guarantee between records. The group needed share.auto.offset.reset=earliest, a group-level setting changed through the Admin client, because a new share group starts at the end of the log. The broker's share-group state topic also needs three replicas by default, so startBroker lowers that to one here.

Kafka compared with traditional message queues

Kafka is often compared with brokers such as RabbitMQ or ActiveMQ, which implement queues and topics in the JMS or AMQP style. The designs serve different needs:

A Kafka topic compared with a classic message queue
AspectKafka topicClassic message queue
After a message is readKept until retention removes itDeleted once acknowledged
Several independent readersAny number of consumer groups, each with its own offsetOne queue per reader, or a fan-out exchange
Replay of old messagesSeek to any offset or timestampNot possible once consumed
OrderingPer partition, by keyPer queue, often lost with competing consumers
Bookkeeping per readerOne offset per partition (or per-record state in a share group)An acknowledgement per message
RoutingBy topic and key onlyRich routing rules, priorities, per-message TTL
Typical throughputVery high, from sequential disk I/O and batchingLower, but with lower per-message latency at small scale

Kafka fits event streams that several systems consume, high-volume data such as logs, metrics and clickstreams, change data capture from databases, and stream processing with Kafka Streams. A classic broker can be simpler for request-reply messaging, complex routing or per-message priorities.

Choosing the right Kafka feature

Common needs and the Kafka feature that fits
NeedFeature
Several services react to the same eventsOne topic, one consumer group per service
Events for one entity processed in orderUse the entity id as the record key
More throughput from one serviceMore consumers in its group, up to the partition count
A pool of workers on independent jobsA share group (Kafka 4.2 or later)
Rebuild a view or fix a bug by reprocessingReset the group's offsets, or seek to a timestamp
Keep only the latest value per keyA compacted topic
Survive a broker failure without data lossReplication factor 3, min.insync.replicas=2, acks=all

The next pages go into each part: producers, consumers, topics and partitions, offsets, configuration and serialization. For Spring applications, see sending with KafkaTemplate and consuming with @KafkaListener.