Kafka topics and partitions: from keys to files

A topic is a set of partitions, and each partition is a log of segment files copied to several brokers. This page explains that structure, then runs it: keys moving when partitions are added, segment files and retention, compaction with tombstones, and a leader failing in a three-broker cluster.

Share

Contents

Topics, partitions and the files behind them

A topic is a name for a stream of records, such as orders. Kafka does not store a topic as one thing. It splits it into partitions, numbered from 0, and each partition is an independent, ordered, append-only log. Every record in a partition has an offset, its position in that log, and a consumer reads a partition in offset order.

Partitions do three jobs at once:

  • Ordering: Kafka keeps order only within a partition. The producer sends all records with the same key to the same partition, so each key's records stay in order.
  • Parallelism: one consumer in a group reads each partition, so the partition count is the most consumers a group can keep busy.
  • Distribution: partitions are spread over the brokers, and each is copied to several of them (the replication factor), so load and failures are shared.

On disk, a partition is a directory such as orders-0 in the broker's log.dirs. The log in it is cut into segments: files named after the first offset they hold, each with a .log file for the records and two small indexes, .index (offset to file position) and .timeindex (timestamp to offset). Only the newest segment, the active one, receives writes. Retention and compaction work on whole closed segments, which is why segment settings matter more than they seem.

Topic settings that shape the log
SettingDefaultWhat it controls
partitionsBroker's num.partitions (1)Parallelism and key distribution; can only grow
replication.factorBroker's default.replication.factor (1)Copies of each partition; 3 in production
cleanup.policydeleteRemove old segments (delete), keep the latest record per key (compact), or both
retention.ms, retention.bytes7 days, no size limitWhen old segments are deleted
segment.bytes, segment.ms1 GB, 7 daysWhen the active segment is closed and a new one started
min.insync.replicas1How many copies an acks=all write needs

The examples use the plain Admin, producer and consumer APIs of kafka-clients 4.2.2. Each program first starts its own Kafka 4.2 cluster inside the JVM with EmbeddedKafkaKraftBroker from spring-kafka-test: one broker for most examples, three for the replication example. A real cluster has three or more brokers on separate machines.

Creating a topic and adding partitions

An orders topic keyed by customer shows what the partition count decides. The program creates it with three partitions, notes where six customers' orders land, grows it to five partitions and checks again:

Java
import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import org.apache.kafka.clients.admin.Admin;
import org.apache.kafka.clients.admin.CreateTopicsResult;
import org.apache.kafka.clients.admin.NewPartitions;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.clients.admin.TopicDescription;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
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 CreateAndGrow {

    static final List<String> CUSTOMERS = List.of("c-101", "c-102", "c-103", "c-104",
            "c-105", "c-106");

    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))) {
            CreateTopicsResult created = admin.createTopics(List.of(
                    new NewTopic("orders", 3, (short) 1)));
            created.all().get();
            System.out.println("created orders: " + created.numPartitions("orders").get()
                    + " partitions, replication factor "
                    + created.replicationFactor("orders").get());
            try {
                admin.createTopics(List.of(new NewTopic("orders", 3, (short) 1))).all().get();
            } catch (ExecutionException e) {
                System.out.println("create again: " + e.getCause().getClass().getSimpleName());
            }

            System.out.println("with 3 partitions: " + placement(servers));

            admin.createPartitions(Map.of("orders", NewPartitions.increaseTo(5))).all().get();
            TopicDescription d = admin.describeTopics(List.of("orders")).allTopicNames().get()
                    .get("orders");
            System.out.println("partitions now: " + d.partitions().size());
            System.out.println("with 5 partitions: " + placement(servers));

            try {
                admin.createPartitions(Map.of("orders", NewPartitions.increaseTo(2)))
                        .all().get();
            } catch (ExecutionException e) {
                System.out.println("shrink to 2: " + e.getCause().getClass().getSimpleName()
                        + ": " + e.getCause().getMessage());
            }
        } finally {
            broker.destroy();
        }
    }

    // a new producer each time, so that it sees the current partition count
    static String placement(String servers) throws Exception {
        StringBuilder sb = new StringBuilder();
        try (KafkaProducer<String, String> producer = new KafkaProducer<>(Map.of(
                "bootstrap.servers", servers,
                "key.serializer", StringSerializer.class,
                "value.serializer", StringSerializer.class))) {
            for (String customer : CUSTOMERS) {
                int p = producer.send(new ProducerRecord<>("orders", customer, "order")).get()
                        .partition();
                sb.append(customer).append("->").append(p).append(' ');
            }
        }
        return sb.toString().trim();
    }

    // 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 turned off.
        // 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.OFF);
        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
created orders: 3 partitions, replication factor 1
create again: TopicExistsException
with 3 partitions: c-101->1 c-102->0 c-103->1 c-104->2 c-105->2 c-106->2
partitions now: 5
with 5 partitions: c-101->2 c-102->1 c-103->2 c-104->1 c-105->3 c-106->3
shrink to 2: InvalidPartitionsException: The topic orders currently has 5 partition(s); 2 would not be an increase.
  • createTopics returned the partition count and replication factor the broker actually used: 3 and 1.
  • Creating the same topic again failed with TopicExistsException. Tools that create topics at start-up should treat that error as success.
  • With three partitions, c-101 and c-103 went to partition 1, c-102 to 0, and three customers shared partition 2. With few keys, an uneven spread is normal.
  • After createPartitions raised the count to five, every one of the six customers mapped to a different partition than before. The default partitioner computes the hash of the key modulo the partition count, so a new count moves most keys.
  • Reducing the count to two was refused with InvalidPartitionsException. A partition count can only grow; to shrink, create a new topic and copy the data.

The moved keys are a real trap. During the change, a customer's older orders sit in one partition and newer ones in another, and two consumers may process them at the same time, out of order. Choose a partition count that leaves room to grow, or, if order per key matters, create a new topic with more partitions and move consumers over once the old one is drained. Topic names may use letters, digits, ., _ and -; avoid mixing . and _, because they collide in metric names.

Segments on disk and retention

The segment files are easiest to understand by looking at them. The program writes 250 records of 10 KB to a topic with the smallest segment size Kafka allows, 1 MB, then lists the partition directory three times: after writing, after deleteRecords, and after shortening the retention time. The broker is set to check retention every second instead of every five minutes:

Java
import ch.qos.logback.classic.Level;
import java.io.File;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Arrays;
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.admin.NewTopic;
import org.apache.kafka.clients.admin.OffsetSpec;
import org.apache.kafka.clients.admin.RecordsToDelete;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.config.ConfigResource;
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 SegmentsAndRetention {

    static final TopicPartition LOGS_0 = new TopicPartition("logs", 0);

    public static void main(String[] args) throws Exception {
        EmbeddedKafkaBroker broker = startBroker();
        try (Admin admin = Admin.create(Map.of("bootstrap.servers",
                broker.getBrokersAsString()))) {
            // the smallest segment size Kafka allows: 1 MB
            admin.createTopics(List.of(new NewTopic("logs", 1, (short) 1)
                    .configs(Map.of("segment.bytes", "1048576")))).all().get();
            try (KafkaProducer<String, String> producer = new KafkaProducer<>(Map.of(
                    "bootstrap.servers", broker.getBrokersAsString(),
                    "linger.ms", 0,
                    "key.serializer", StringSerializer.class,
                    "value.serializer", StringSerializer.class))) {
                String value = "x".repeat(10000);
                for (int i = 0; i < 250; i++) { // 250 records of 10 KB, one batch each
                    producer.send(new ProducerRecord<>("logs", value)).get();
                }
            }
            String logDir = admin.describeLogDirs(List.of(0)).allDescriptions().get()
                    .get(0).keySet().iterator().next();
            File partitionDir = new File(logDir, "logs-0");

            show(admin, partitionDir, "after writing 250 records of 10 KB");

            admin.deleteRecords(Map.of(LOGS_0, RecordsToDelete.beforeOffset(50))).all().get();
            show(admin, partitionDir, "after deleteRecords(beforeOffset 50)");

            ConfigResource topic = new ConfigResource(ConfigResource.Type.TOPIC, "logs");
            admin.incrementalAlterConfigs(Map.of(topic, List.of(new AlterConfigOp(
                    new ConfigEntry("retention.ms", "1000"), AlterConfigOp.OpType.SET))))
                    .all().get();
            long start = earliest(admin);
            while (earliest(admin) == start) {
                Thread.sleep(200); // the broker checks retention every second (see below)
            }
            show(admin, partitionDir, "after retention.ms=1000 and a retention check");
        } finally {
            broker.destroy();
        }
    }

    static long earliest(Admin admin) throws Exception {
        return admin.listOffsets(Map.of(LOGS_0, OffsetSpec.earliest())).all().get()
                .get(LOGS_0).offset();
    }

    static void show(Admin admin, File dir, String step) throws Exception {
        long latest = admin.listOffsets(Map.of(LOGS_0, OffsetSpec.latest())).all().get()
                .get(LOGS_0).offset();
        long first = earliest(admin);
        System.out.println(step + ": " + (first == latest ? "no records, next offset " + latest
                : "offsets " + first + " to " + (latest - 1)));
        String[] names = dir.list((d, name) -> name.matches("\\d+\\.(log|index|timeindex)"
                + "(\\.deleted)?"));
        Arrays.sort(names);
        for (String name : names) {
            System.out.printf("   %-38s %,10d bytes%n", name, new File(dir, name).length());
        }
    }

    // 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 turned off.
        // 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.OFF);
        PrintStream stdout = System.out;
        System.setOut(new PrintStream(OutputStream.nullOutputStream()));
        try {
            // check retention every second instead of every 5 minutes
            EmbeddedKafkaBroker broker = new EmbeddedKafkaKraftBroker(1, 1).brokerProperties(
                    Map.of("log.retention.check.interval.ms", "1000"));
            broker.afterPropertiesSet();
            return broker;
        } finally {
            System.setOut(stdout);
        }
    }
}
Output
after writing 250 records of 10 KB: offsets 0 to 249
   00000000000000000000.index                    824 bytes
   00000000000000000000.log                1,047,488 bytes
   00000000000000000000.timeindex              1,236 bytes
   00000000000000000104.index                    824 bytes
   00000000000000000104.log                1,047,488 bytes
   00000000000000000104.timeindex              1,236 bytes
   00000000000000000208.index             10,485,760 bytes
   00000000000000000208.log                  423,024 bytes
   00000000000000000208.timeindex         10,485,756 bytes
after deleteRecords(beforeOffset 50): offsets 50 to 249
   00000000000000000000.index                    824 bytes
   00000000000000000000.log                1,047,488 bytes
   00000000000000000000.timeindex              1,236 bytes
   00000000000000000104.index                    824 bytes
   00000000000000000104.log                1,047,488 bytes
   00000000000000000104.timeindex              1,236 bytes
   00000000000000000208.index             10,485,760 bytes
   00000000000000000208.log                  423,024 bytes
   00000000000000000208.timeindex         10,485,756 bytes
after retention.ms=1000 and a retention check: no records, next offset 250
   00000000000000000000.index.deleted            824 bytes
   00000000000000000000.log.deleted        1,047,488 bytes
   00000000000000000000.timeindex.deleted      1,236 bytes
   00000000000000000104.index.deleted            824 bytes
   00000000000000000104.log.deleted        1,047,488 bytes
   00000000000000000104.timeindex.deleted      1,236 bytes
   00000000000000000208.index.deleted            328 bytes
   00000000000000000208.log.deleted          423,024 bytes
   00000000000000000208.timeindex.deleted        492 bytes
   00000000000000000250.log                        0 bytes
  • The 250 records filled three segments, named after their first offsets: 0, 104 and 208. Each closed segment holds 104 records, about 1 MB. Offsets 208 to 249 are in the active segment.
  • The closed segments' indexes are small (824 and 1,236 bytes), but the active segment's are 10 MB each. Kafka preallocates the index files of the active segment to segment.index.bytes and trims them when the segment closes.
  • deleteRecords(beforeOffset 50) moved the log start offset to 50, and a consumer starting from the beginning now begins there. No file changed: offsets 0 to 49 share a segment with records that must stay, so nothing could be deleted yet.
  • With retention.ms=1000, every record was older than the limit. The broker closed the active segment and marked all three segments for deletion by renaming them to .deleted; the files are removed a minute later (file.delete.delay.ms). A new empty segment starts at offset 250, so offsets keep counting up.

Retention deletes whole segments, using the newest timestamp in each. With the default 1 GB segments, a quiet topic can keep data well past retention.ms, because its active segment is not closed until it fills or segment.ms (7 days) passes. retention.bytes applies per partition, not per topic. With tiered storage enabled, closed segments are copied to object storage, and the broker keeps only the most recent ones locally.

Log compaction: the latest value per key

A topic of current prices only needs the latest price of each product. With cleanup.policy=compact, a background cleaner removes records whose key has a newer record. The topic here rolls segments every 100 ms and is cleaned eagerly, and a null value, a tombstone, deletes the key plum:

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 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.common.TopicPartition;
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 Compaction {

    static String servers;

    public static void main(String[] args) throws Exception {
        EmbeddedKafkaBroker broker = startBroker();
        servers = broker.getBrokersAsString();
        try (Admin admin = Admin.create(Map.of("bootstrap.servers", servers))) {
            admin.createTopics(List.of(new NewTopic("prices", 1, (short) 1).configs(Map.of(
                    "cleanup.policy", "compact",
                    "segment.ms", "100",               // roll segments quickly ...
                    "min.cleanable.dirty.ratio", "0.01", // ... and clean them eagerly
                    "delete.retention.ms", "100")))).all().get();
            try (KafkaProducer<String, String> producer = new KafkaProducer<>(Map.of(
                    "bootstrap.servers", servers,
                    "key.serializer", StringSerializer.class,
                    "value.serializer", StringSerializer.class))) {
                String[][] updates = {{"apple", "1.10"}, {"pear", "0.90"}, {"apple", "1.20"},
                    {"plum", "2.00"}, {"pear", "0.95"}, {"apple", "1.25"}, {"plum", null}};
                for (String[] u : updates) { // a null value is a tombstone: delete the key
                    producer.send(new ProducerRecord<>("prices", u[0], u[1])).get();
                }
                System.out.println("before cleaning: " + readAll());
                Thread.sleep(500);
                // the active segment is never cleaned, so add a record to roll it
                producer.send(new ProducerRecord<>("prices", "kiwi", "0.50")).get();
                Thread.sleep(500);
                producer.send(new ProducerRecord<>("prices", "kiwi", "0.55")).get();
            }
            List<String> after = readAll();
            while (after.size() > 4) { // wait for the log cleaner thread
                Thread.sleep(500);
                after = readAll();
            }
            System.out.println("after cleaning : " + after);
        } finally {
            broker.destroy();
        }
    }

    static List<String> readAll() {
        List<String> seen = new ArrayList<>();
        try (KafkaConsumer<String, String> consumer = new KafkaConsumer<>(Map.of(
                "bootstrap.servers", servers,
                "key.deserializer", StringDeserializer.class,
                "value.deserializer", StringDeserializer.class))) {
            TopicPartition p = new TopicPartition("prices", 0);
            consumer.assign(List.of(p));
            consumer.seekToBeginning(List.of(p));
            long end = consumer.endOffsets(List.of(p)).get(p);
            while (consumer.position(p) < end) {
                for (ConsumerRecord<String, String> r : consumer.poll(Duration.ofSeconds(1))) {
                    seen.add(r.offset() + ":" + r.key() + "=" + r.value());
                }
            }
        }
        return seen;
    }

    // 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 turned off.
        // 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.OFF);
        PrintStream stdout = System.out;
        System.setOut(new PrintStream(OutputStream.nullOutputStream()));
        try {
            // the log cleaner looks for work every second instead of every 15
            EmbeddedKafkaBroker broker = new EmbeddedKafkaKraftBroker(1, 1).brokerProperties(
                    Map.of("log.cleaner.backoff.ms", "1000"));
            broker.afterPropertiesSet();
            return broker;
        } finally {
            System.setOut(stdout);
        }
    }
}
Output
before cleaning: [0:apple=1.10, 1:pear=0.90, 2:apple=1.20, 3:plum=2.00, 4:pear=0.95, 5:apple=1.25, 6:plum=null]
after cleaning : [4:pear=0.95, 5:apple=1.25, 7:kiwi=0.50, 8:kiwi=0.55]
  • Before cleaning, all seven updates were in the log, including two old apple prices and the tombstone at offset 6.
  • After cleaning, apple kept only its latest price (offset 5) and pear its latest (offset 4). The old records were removed, but the survivors kept their original offsets: compaction leaves gaps, it never renumbers.
  • plum disappeared completely: first its value was removed because the tombstone was newer, then the tombstone itself after delete.retention.ms (100 ms here, one day by default).
  • Both kiwi records survived. The second one was in the active segment, which the cleaner never touches, so it did not yet count as newer than the first.

Compacted topics are how Kafka stores state: __consumer_offsets is compacted, as are Kafka Streams changelogs and Kafka Connect's offset and config topics. Compaction is not immediate. It waits until the share of uncleaned data reaches min.cleanable.dirty.ratio (0.5 by default), so consumers must expect duplicates for a key. A consumer that reads the topic from offset 0 must finish within delete.retention.ms, or it may miss tombstones and keep deleted keys.

Replication: leaders, followers and failover

Replication is what makes a broker failure harmless, and it needs several brokers. This program starts a three-broker cluster in one JVM, writes to a partition with three replicas, then shuts down the partition's leader:

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 kafka.server.BrokerServer;
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.common.Node;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.TopicPartitionInfo;
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.EmbeddedKafkaKraftBroker;

public class Replication {

    public static void main(String[] args) throws Exception {
        EmbeddedKafkaKraftBroker cluster = startBrokers(3);
        String servers = cluster.getBrokersAsString();
        try (Admin admin = Admin.create(Map.of("bootstrap.servers", servers));
             KafkaProducer<String, String> producer = new KafkaProducer<>(Map.of(
                     "bootstrap.servers", servers,
                     "key.serializer", StringSerializer.class,
                     "value.serializer", StringSerializer.class))) {
            admin.createTopics(List.of(new NewTopic("accounts", 1, (short) 3)
                    .configs(Map.of("min.insync.replicas", "2")))).all().get();
            System.out.println("before: " + describe(admin));
            for (int i = 1; i <= 3; i++) {
                producer.send(new ProducerRecord<>("accounts", "deposit " + i)).get();
            }

            int leader = partition(admin).leader().id();
            BrokerServer leaderBroker = cluster.getCluster().brokers().get(leader);
            // a controlled shutdown first hands leadership to another replica
            Thread stopper = new Thread(leaderBroker::shutdown);
            stopper.setDaemon(true);
            stopper.start();
            System.out.println("broker " + leader + " (the leader) is shutting down");
            while (partition(admin).isr().size() == 3 || partition(admin).leader() == null
                    || partition(admin).leader().id() == leader) {
                Thread.sleep(200);
            }
            System.out.println("after : " + describe(admin));

            for (int i = 4; i <= 5; i++) { // acks=all still works: 2 in-sync copies remain
                producer.send(new ProducerRecord<>("accounts", "deposit " + i)).get();
            }
            System.out.println("read back: " + readAll(servers));
        }
        // the test kit can hang closing a cluster with a stopped broker, so end the JVM here
        System.exit(0);
    }

    static TopicPartitionInfo partition(Admin admin) throws Exception {
        return admin.describeTopics(List.of("accounts")).allTopicNames().get().get("accounts")
                .partitions().get(0);
    }

    static String describe(Admin admin) throws Exception {
        TopicPartitionInfo p = partition(admin);
        return "leader " + p.leader().id() + ", replicas "
                + p.replicas().stream().map(Node::id).toList() + ", in sync "
                + p.isr().stream().map(Node::id).sorted().toList();
    }

    static List<String> readAll(String servers) {
        List<String> values = new ArrayList<>();
        try (KafkaConsumer<String, String> consumer = new KafkaConsumer<>(Map.of(
                "bootstrap.servers", servers,
                "key.deserializer", StringDeserializer.class,
                "value.deserializer", StringDeserializer.class))) {
            TopicPartition p = new TopicPartition("accounts", 0);
            consumer.assign(List.of(p));
            consumer.seekToBeginning(List.of(p));
            while (values.size() < 5) {
                for (ConsumerRecord<String, String> r : consumer.poll(Duration.ofSeconds(1))) {
                    values.add(r.offset() + ":" + r.value());
                }
            }
        }
        return values;
    }

    // Starts a KRaft cluster of n brokers inside this JVM, from spring-kafka-test
    static EmbeddedKafkaKraftBroker startBrokers(int n) {
        // the brokers log at INFO and print their storage setup, so both are turned off.
        // 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.OFF);
        PrintStream stdout = System.out;
        System.setOut(new PrintStream(OutputStream.nullOutputStream()));
        try {
            EmbeddedKafkaKraftBroker cluster = new EmbeddedKafkaKraftBroker(n, 1);
            cluster.afterPropertiesSet();
            return cluster;
        } finally {
            System.setOut(stdout);
        }
    }
}
Output
before: leader 0, replicas [0, 1, 2], in sync [0, 1, 2]
broker 0 (the leader) is shutting down
after : leader 1, replicas [0, 1, 2], in sync [1, 2]
read back: [0:deposit 1, 1:deposit 2, 2:deposit 3, 3:deposit 4, 4:deposit 5]
  • The partition had three replicas, one per broker, and all were in sync. One of them was the leader, which handles all reads and writes; the others are followers that copy it. Which broker becomes leader varies between runs.
  • When the leader shut down, the controller made another in-sync replica the leader, and the stopped broker left the in-sync set. The replica list did not change: the stopped broker is still assigned and catches up when it returns.
  • Two in-sync copies still met min.insync.replicas=2, so the producer's acks=all writes 4 and 5 succeeded. The producer found the new leader by refreshing its metadata.
  • The consumer read all five records, offsets 0 to 4. Records acknowledged by the old leader had already been copied to the followers, so none was lost.

The program starts the shutdown on a separate thread and ends with System.exit, because the test harness can hang while it waits for a stopped broker. In production, set broker.rack so that the replicas of a partition are placed in different racks or availability zones. Keep unclean.leader.election.enable=false, the default: when no in-sync replica is left, it makes Kafka wait instead of electing an out-of-date replica and losing records. A replication factor of 3 with min.insync.replicas=2 tolerates one broker failure without losing writes; the configuration page shows what happens with too few replicas.

How many partitions?

There is no formula, but a few rules of thumb hold. Start from the throughput you need per consumer: if one consumer can handle a tenth of the topic's peak traffic, you need at least ten partitions, plus room to grow, since growing later moves keys. More partitions also mean more files, more open file handles, more replication traffic and more work for the controller when brokers fail, so thousands of partitions for a small topic cost more than they help.

KRaft, the only mode since Kafka 4.0, handles far larger numbers of partitions per cluster than ZooKeeper-based clusters did, because the controller keeps metadata in memory and in its own log. The limit that bites first is usually per broker: disk, memory for indexes and the time to move leaders. Keys matter as much as counts: a few very busy keys make hot partitions whatever their number.

Choosing topic settings

Needs and the topic settings that fit
NeedSettings
An event stream kept for a whilecleanup.policy=delete, retention.ms set to how far back consumers may need to replay
The current state per keycleanup.policy=compact, tombstones for deletes
State plus a bounded historycleanup.policy=compact,delete
No data loss on one broker failureReplication factor 3, min.insync.replicas=2, producers with acks=all
Ordered processing per entityEntity id as the key, and a partition count chosen once with room to grow
Free disk space nowdeleteRecords or a shorter retention.ms, remembering that only closed segments are removed
Disk-bounded topicsretention.bytes, which is per partition

Related pages: Kafka introduction, producers and partitioners, offsets, configuration and cluster administration.