Kafka cluster administration

Running Kafka means changing it while it serves traffic: creating topics, adding partitions, tuning configs, moving replicas and fixing consumer offsets. This page explains how a KRaft cluster stores those decisions, then performs each task with the Java Admin API and the command-line tools against a real three-broker cluster started inside each program.

Share

Contents

How a KRaft cluster is administered

A Kafka cluster has two kinds of server. Brokers store partitions and serve producers and consumers. Controllers decide everything else: which topics exist, where each partition's replicas live, which replica leads, and which configs apply. Since Kafka 4.0 the controllers always run KRaft, a Raft quorum that keeps this state in a replicated metadata log; ZooKeeper is gone. Brokers follow the metadata log and apply each change as it arrives.

Every administrative action is therefore a request that ends up as a record in the metadata log. The client sends it to any broker, the broker forwards it to the active controller, the controller validates it and appends a record, and the brokers catch up a moment later. Two consequences show up in the programs below: a change is visible on all brokers only after a short delay, and the controller rejects anything that would break the cluster's rules before writing anything.

Tools for administering Kafka
ToolSinceBest for
Admin (Java, kafka-clients)0.11 as AdminClient; Admin interface since 2.4Automation, operators, platform tooling
kafka-topics.sh, kafka-configs.sh, kafka-consumer-groups.shBuilt on the Admin APIOne-off changes and checks by hand
kafka-reassign-partitions.sh, kafka-leader-election.shBuilt on the Admin APIMoving replicas and leaders
kafka-metadata-quorum.sh, kafka-features.shKRaft tools, Kafka 3.xController quorum and feature levels
Spring KafkaAdmin, NewTopic beansSpring for Apache KafkaDeclaring an application's topics at start-up

Every Admin method returns a result object of KafkaFutures, so it never blocks by itself; the programs call get() to wait. Each program starts its own cluster inside the JVM with KafkaClusterTestKit, Kafka 4.2.2's test cluster, which spring-kafka-test's EmbeddedKafkaKraftBroker is built on: one controller (id 3000) and three brokers (ids 0, 1 and 2), with production feature levels. Production clusters run three or five controllers on separate machines.

Looking at the cluster

The first thing an operator checks is who is in the cluster and which version of the metadata it runs. The program asks the brokers, the quorum and the feature levels, then reads a few broker settings that matter for every topic:

Java
import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
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.QuorumInfo;
import org.apache.kafka.common.Node;
import org.apache.kafka.common.config.ConfigResource;
import org.apache.kafka.common.test.KafkaClusterTestKit;
import org.apache.kafka.common.test.TestKitNodes;
import org.apache.kafka.metadata.bootstrap.BootstrapMetadata;
import org.apache.kafka.server.common.Feature;
import org.apache.kafka.server.common.MetadataVersion;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ClusterOverview {

    public static void main(String[] args) throws Exception {
        KafkaClusterTestKit cluster = startCluster();
        try (Admin admin = Admin.create(Map.<String, Object>of(
                "bootstrap.servers", cluster.bootstrapServers()))) {
            DescribeClusterResult described = admin.describeCluster();
            System.out.println("cluster id length: " + described.clusterId().get().length());
            for (Node node : described.nodes().get()) {
                System.out.println("broker " + node.id() + " at " + node.host()
                        + ", rack " + node.rack());
            }
            int shown = described.controller().get().id();
            System.out.println("'controller' as clients see it is a broker: "
                    + cluster.brokers().containsKey(shown) + ", a controller: "
                    + cluster.controllers().containsKey(shown));

            QuorumInfo quorum = admin.describeMetadataQuorum().quorumInfo().get();
            System.out.println("metadata quorum leader: " + quorum.leaderId());
            System.out.println("voters (controllers): "
                    + quorum.voters().stream().map(QuorumInfo.ReplicaState::replicaId).toList());
            System.out.println("observers (brokers):  "
                    + quorum.observers().stream().map(QuorumInfo.ReplicaState::replicaId)
                            .sorted().toList());

            FeatureMetadata features = admin.describeFeatures().featureMetadata().get();
            short level = features.finalizedFeatures().get("metadata.version").maxVersionLevel();
            System.out.println("metadata.version level " + level + " = "
                    + MetadataVersion.fromFeatureLevel(level));
            Map<String, Short> finalized = new TreeMap<>();
            features.finalizedFeatures().forEach((k, v) -> finalized.put(k, v.maxVersionLevel()));
            System.out.println("finalized features: " + finalized);

            ConfigResource broker0 = new ConfigResource(ConfigResource.Type.BROKER, "0");
            Config config = admin.describeConfigs(List.of(broker0)).all().get().get(broker0);
            for (String key : List.of("num.partitions", "default.replication.factor",
                    "min.insync.replicas", "auto.create.topics.enable",
                    "unclean.leader.election.enable", "log.retention.hours",
                    "log.segment.bytes", "num.network.threads", "num.io.threads")) {
                System.out.printf("  %-31s %-11s %s%n", key, config.get(key).value(),
                        config.get(key).source());
            }
        } finally {
            cluster.close();
        }
    }

    // Starts a KRaft cluster in this JVM with KafkaClusterTestKit, Kafka's own test
    // cluster (EmbeddedKafkaKraftBroker is built on it): one controller, three brokers
    static KafkaClusterTestKit startCluster() throws Exception {
        // 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 {
            // production metadata version and feature levels, as a new 4.2 cluster gets
            Map<String, Short> features = new HashMap<>();
            for (Feature f : Feature.PRODUCTION_FEATURES) {
                if (f != Feature.KRAFT_VERSION) {
                    features.put(f.featureName(), f.latestProduction());
                }
            }
            KafkaClusterTestKit cluster = new KafkaClusterTestKit.Builder(
                    new TestKitNodes.Builder()
                            .setCombined(false)
                            .setNumControllerNodes(1)
                            .setNumBrokerNodes(3)
                            .setBootstrapMetadata(BootstrapMetadata.fromVersions(
                                    MetadataVersion.latestProduction(), features, "demo"))
                            .build())
                    .build();
            cluster.format();
            cluster.startup();
            cluster.waitForReadyBrokers();
            return cluster;
        } finally {
            System.setOut(stdout);
        }
    }
}
Output
cluster id length: 22
broker 0 at localhost, rack null
broker 1 at localhost, rack null
broker 2 at localhost, rack null
'controller' as clients see it is a broker: true, a controller: false
metadata quorum leader: 3000
voters (controllers): [3000]
observers (brokers):  [0, 1, 2]
metadata.version level 29 = 4.2-IV1
finalized features: {eligible.leader.replicas.version=1, group.version=1, metadata.version=29, share.version=1, streams.version=1, transaction.version=2}
  num.partitions                  1           DEFAULT_CONFIG
  default.replication.factor      1           DEFAULT_CONFIG
  min.insync.replicas             1           DYNAMIC_DEFAULT_BROKER_CONFIG
  auto.create.topics.enable       true        DEFAULT_CONFIG
  unclean.leader.election.enable  false       DEFAULT_CONFIG
  log.retention.hours             168         DEFAULT_CONFIG
  log.segment.bytes               1073741824  DEFAULT_CONFIG
  num.network.threads             3           DEFAULT_CONFIG
  num.io.threads                  8           DEFAULT_CONFIG
  • describeCluster listed brokers 0, 1 and 2 with no rack. Setting broker.rack lets Kafka place a partition's replicas in different racks or availability zones.
  • The "controller" in describeCluster is one of the brokers, not controller 3000. Clients cannot reach KRaft controllers, so brokers report a random broker there, and old tools that relied on this field no longer find the real controller.
  • describeMetadataQuorum shows the real picture: controller 3000 is the quorum leader and the only voter, and the three brokers are observers that replicate the metadata log without voting.
  • metadata.version level 29 is 4.2-IV1, the metadata format of Kafka 4.2. The other features enable newer protocols: group.version=1 allows the KIP-848 consumer group protocol, transaction.version=2 the newer transaction protocol, share.version=1 share groups. After upgrading the software, an operator raises these levels with kafka-features.sh upgrade.
  • All broker settings shown are DEFAULT_CONFIG. Three of them deserve changing in production: default.replication.factor to 3, min.insync.replicas to 2, and auto.create.topics.enable to false, so that a typo in a topic name does not create a topic.

Creating topics and adding partitions

Topics are the most common administrative change, and the partition count is the one setting that is hard to change later. The program does a dry run, creates a topic with three replicas, grows it from 3 to 6 partitions, and then tries three invalid requests:

Java
import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.ExecutionException;
import org.apache.kafka.clients.admin.Admin;
import org.apache.kafka.clients.admin.CreateTopicsOptions;
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.common.TopicPartitionInfo;
import org.apache.kafka.common.test.KafkaClusterTestKit;
import org.apache.kafka.common.test.TestKitNodes;
import org.apache.kafka.metadata.bootstrap.BootstrapMetadata;
import org.apache.kafka.server.common.Feature;
import org.apache.kafka.common.utils.Utils;
import org.apache.kafka.server.common.MetadataVersion;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TopicLifecycle {

    public static void main(String[] args) throws Exception {
        KafkaClusterTestKit cluster = startCluster();
        try (Admin admin = Admin.create(Map.<String, Object>of(
                "bootstrap.servers", cluster.bootstrapServers()))) {
            NewTopic orders = new NewTopic("orders", 3, (short) 3).configs(Map.of(
                    "min.insync.replicas", "2", "retention.ms", "604800000"));

            // a dry run: the controller checks the request but creates nothing
            admin.createTopics(List.of(orders), new CreateTopicsOptions().validateOnly(true))
                    .all().get();
            System.out.println("after validateOnly, topics: " + admin.listTopics().names().get());

            admin.createTopics(List.of(orders)).all().get();
            describe(admin, "orders", 3);

            System.out.println("key customer-42 goes to partition " + partitionOf("customer-42", 3)
                    + " of 3");
            admin.createPartitions(Map.of("orders", NewPartitions.increaseTo(6))).all().get();
            describe(admin, "orders", 6);
            System.out.println("key customer-42 goes to partition " + partitionOf("customer-42", 6)
                    + " of 6");

            attempt("shrink to 2 partitions", () -> admin.createPartitions(
                    Map.of("orders", NewPartitions.increaseTo(2))).all().get());
            attempt("replication factor 4 on 3 brokers", () -> admin.createTopics(
                    List.of(new NewTopic("audit", 1, (short) 4))).all().get());
            attempt("create orders again", () -> admin.createTopics(
                    List.of(new NewTopic("orders", 1, (short) 1))).all().get());

            admin.deleteTopics(List.of("orders")).all().get();
            System.out.println("after delete, topics: " + admin.listTopics().names().get());
        } finally {
            cluster.close();
        }
    }

    // prints how the controller placed the partitions; which broker gets the first
    // replica is random, so the program prints the pattern instead of broker ids
    static void describe(Admin admin, String topic, int expected) throws Exception {
        TopicDescription d;
        do { // new partitions take a moment to reach every broker's metadata
            d = admin.describeTopics(List.of(topic)).allTopicNames().get().get(topic);
        } while (d.partitions().size() < expected);
        Map<Integer, Integer> leaders = new TreeMap<>();
        boolean preferred = true;
        boolean fullIsr = true;
        for (TopicPartitionInfo p : d.partitions()) {
            leaders.merge(p.leader().id(), 1, Integer::sum);
            preferred &= p.leader().id() == p.replicas().get(0).id();
            fullIsr &= p.isr().size() == 3;
        }
        System.out.println(topic + ": " + d.partitions().size() + " partitions, leaders per broker "
                + leaders + ", leader is the first replica: " + preferred
                + ", all 3 replicas in sync: " + fullIsr);
    }

    // the default partitioner's choice for a keyed record: murmur2 hash modulo partitions
    static int partitionOf(String key, int partitions) {
        return Utils.toPositive(Utils.murmur2(key.getBytes(StandardCharsets.UTF_8))) % partitions;
    }

    interface AdminCall {
        void run() throws Exception;
    }

    static void attempt(String label, AdminCall call) throws Exception {
        try {
            call.run();
            System.out.println(label + ": succeeded");
        } catch (ExecutionException e) {
            System.out.println(label + ": " + e.getCause().getClass().getSimpleName() + ": "
                    + e.getCause().getMessage());
        }
    }

    // Starts a KRaft cluster in this JVM with KafkaClusterTestKit, Kafka's own test
    // cluster (EmbeddedKafkaKraftBroker is built on it): one controller, three brokers
    static KafkaClusterTestKit startCluster() throws Exception {
        // 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 {
            // production metadata version and feature levels, as a new 4.2 cluster gets
            Map<String, Short> features = new HashMap<>();
            for (Feature f : Feature.PRODUCTION_FEATURES) {
                if (f != Feature.KRAFT_VERSION) {
                    features.put(f.featureName(), f.latestProduction());
                }
            }
            KafkaClusterTestKit cluster = new KafkaClusterTestKit.Builder(
                    new TestKitNodes.Builder()
                            .setCombined(false)
                            .setNumControllerNodes(1)
                            .setNumBrokerNodes(3)
                            .setBootstrapMetadata(BootstrapMetadata.fromVersions(
                                    MetadataVersion.latestProduction(), features, "demo"))
                            .build())
                    .build();
            cluster.format();
            cluster.startup();
            cluster.waitForReadyBrokers();
            return cluster;
        } finally {
            System.setOut(stdout);
        }
    }
}
Output
after validateOnly, topics: []
orders: 3 partitions, leaders per broker {0=1, 1=1, 2=1}, leader is the first replica: true, all 3 replicas in sync: true
key customer-42 goes to partition 0 of 3
orders: 6 partitions, leaders per broker {0=2, 1=2, 2=2}, leader is the first replica: true, all 3 replicas in sync: true
key customer-42 goes to partition 3 of 6
shrink to 2 partitions: InvalidPartitionsException: The topic orders currently has 6 partition(s); 2 would not be an increase.
replication factor 4 on 3 brokers: InvalidReplicationFactorException: Unable to replicate the partition 4 time(s): The target replication factor of 4 cannot be reached because only 3 broker(s) are registered.
create orders again: TopicExistsException: Topic 'orders' already exists.
after delete, topics: []
  • validateOnly(true) ran every check on the controller but created nothing, so the topic list stayed empty. Use it in a deployment pipeline before the real change.
  • The controller spread the leaders evenly, one per broker, and later two per broker. Each partition's leader is its first replica, the preferred leader. The broker that gets the first partition is chosen at random, which is why the program prints the pattern instead of broker ids.
  • The key customer-42 moved from partition 0 to partition 3 when the topic grew to 6 partitions. The default partitioner takes the key's murmur2 hash modulo the partition count, so most keys map elsewhere afterwards, and a consumer can see a key's newer events before its older ones. Add partitions before the data arrives, or accept that ordering per key breaks once.
  • Shrinking failed with InvalidPartitionsException: a partition cannot be removed, since its records would have nowhere to go. To get fewer partitions, create a new topic and copy the data.
  • A replication factor of 4 failed because only 3 brokers are registered. The controller checks this before writing any metadata.
  • TopicExistsException for an existing name is common in start-up code that creates its topics. Catch it, or compare the existing topic's settings, instead of failing.

Deleting a topic took effect at once for the topic list; the brokers then delete the log files in the background. A topic's name can be reused right away, but it gets a new topic id, so consumers that cached the old one see the new topic as different.

Dynamic configuration

Most topic settings and many broker settings can change without a restart. incrementalAlterConfigs changes individual keys. describeConfigs shows each value with its source, which tells you where a value comes from when several levels define it:

Java
import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Collection;
import java.util.HashMap;
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.AlterConfigOp;
import org.apache.kafka.clients.admin.AlterConfigOp.OpType;
import org.apache.kafka.clients.admin.Config;
import org.apache.kafka.clients.admin.ConfigEntry;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.common.config.ConfigResource;
import org.apache.kafka.common.test.KafkaClusterTestKit;
import org.apache.kafka.common.test.TestKitNodes;
import org.apache.kafka.metadata.bootstrap.BootstrapMetadata;
import org.apache.kafka.server.common.Feature;
import org.apache.kafka.server.common.MetadataVersion;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DynamicConfigs {

    public static void main(String[] args) throws Exception {
        KafkaClusterTestKit cluster = startCluster();
        try (Admin admin = Admin.create(Map.<String, Object>of(
                "bootstrap.servers", cluster.bootstrapServers()))) {
            admin.createTopics(List.of(new NewTopic("payments", 1, (short) 3))).all().get();
            ConfigResource topic = new ConfigResource(ConfigResource.Type.TOPIC, "payments");
            show(admin, topic, "retention.ms", "cleanup.policy", "max.message.bytes");

            alter(admin, topic,
                    op("retention.ms", "86400000", OpType.SET),
                    op("cleanup.policy", "compact", OpType.APPEND),
                    op("max.message.bytes", "2097152", OpType.SET));
            show(admin, topic, "retention.ms", "cleanup.policy", "max.message.bytes");

            alter(admin, topic, op("max.message.bytes", null, OpType.DELETE));
            show(admin, topic, "max.message.bytes");

            // an empty broker name changes the default for every broker in the cluster
            ConfigResource allBrokers = new ConfigResource(ConfigResource.Type.BROKER, "");
            ConfigResource broker1 = new ConfigResource(ConfigResource.Type.BROKER, "1");
            alter(admin, allBrokers, op("message.max.bytes", "2097152", OpType.SET));
            alter(admin, broker1, op("message.max.bytes", "3145728", OpType.SET));
            for (String id : List.of("0", "1")) {
                show(admin, new ConfigResource(ConfigResource.Type.BROKER, id),
                        "message.max.bytes");
            }

            try {
                alter(admin, broker1, op("log.dirs", "/data/kafka", OpType.SET));
            } catch (ExecutionException e) {
                System.out.println("log.dirs: " + e.getCause().getClass().getSimpleName()
                        + ": " + e.getCause().getMessage());
            }
            try {
                alter(admin, topic, op("retention.ms", "soon", OpType.SET));
            } catch (ExecutionException e) {
                System.out.println("retention.ms=soon: " + e.getCause().getClass()
                        .getSimpleName() + ": " + e.getCause().getMessage());
            }
        } finally {
            cluster.close();
        }
    }

    static AlterConfigOp op(String key, String value, OpType type) {
        return new AlterConfigOp(new ConfigEntry(key, value), type);
    }

    static void alter(Admin admin, ConfigResource resource, AlterConfigOp... ops)
            throws Exception {
        Map<ConfigResource, Collection<AlterConfigOp>> request = Map.of(resource, List.of(ops));
        admin.incrementalAlterConfigs(request).all().get();
        Thread.sleep(500); // the change reaches every broker through the metadata log
    }

    static void show(Admin admin, ConfigResource resource, String... keys) throws Exception {
        Config config = admin.describeConfigs(List.of(resource)).all().get().get(resource);
        String name = resource.type() + " " + resource.name();
        for (String key : keys) {
            ConfigEntry e = config.get(key);
            System.out.printf("%-10s %-20s %-17s %s%n", name, key, e.value(), e.source());
        }
    }

    // Starts a KRaft cluster in this JVM with KafkaClusterTestKit, Kafka's own test
    // cluster (EmbeddedKafkaKraftBroker is built on it): one controller, three brokers
    static KafkaClusterTestKit startCluster() throws Exception {
        // 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 {
            // production metadata version and feature levels, as a new 4.2 cluster gets
            Map<String, Short> features = new HashMap<>();
            for (Feature f : Feature.PRODUCTION_FEATURES) {
                if (f != Feature.KRAFT_VERSION) {
                    features.put(f.featureName(), f.latestProduction());
                }
            }
            KafkaClusterTestKit cluster = new KafkaClusterTestKit.Builder(
                    new TestKitNodes.Builder()
                            .setCombined(false)
                            .setNumControllerNodes(1)
                            .setNumBrokerNodes(3)
                            .setBootstrapMetadata(BootstrapMetadata.fromVersions(
                                    MetadataVersion.latestProduction(), features, "demo"))
                            .build())
                    .build();
            cluster.format();
            cluster.startup();
            cluster.waitForReadyBrokers();
            return cluster;
        } finally {
            System.setOut(stdout);
        }
    }
}
Output
TOPIC payments retention.ms         604800000         DEFAULT_CONFIG
TOPIC payments cleanup.policy       delete            DEFAULT_CONFIG
TOPIC payments max.message.bytes    1048588           DEFAULT_CONFIG
TOPIC payments retention.ms         86400000          DYNAMIC_TOPIC_CONFIG
TOPIC payments cleanup.policy       delete,compact    DYNAMIC_TOPIC_CONFIG
TOPIC payments max.message.bytes    2097152           DYNAMIC_TOPIC_CONFIG
TOPIC payments max.message.bytes    1048588           DEFAULT_CONFIG
BROKER 0   message.max.bytes    2097152           DYNAMIC_DEFAULT_BROKER_CONFIG
BROKER 1   message.max.bytes    3145728           DYNAMIC_BROKER_CONFIG
log.dirs: InvalidRequestException: Cannot update these configs dynamically: Set(log.dirs)
retention.ms=soon: InvalidConfigurationException: Invalid value soon for configuration retention.ms: Not a number of type LONG
  • A new topic inherits every value from the brokers: the source of all three is DEFAULT_CONFIG, and retention.ms is 604800000, which is 7 days.
  • SET replaced retention.ms with one day. APPEND added compact to the list-typed cleanup.policy, giving delete,compact: the topic now keeps the latest record per key and also drops records older than a day. The source of the three changed values is now DYNAMIC_TOPIC_CONFIG.
  • DELETE removed the override for max.message.bytes, and the value went back to the default, 1048588 bytes.
  • A broker resource with an empty name sets a cluster-wide default: broker 0 shows message.max.bytes of 2097152 with source DYNAMIC_DEFAULT_BROKER_CONFIG. Broker 1's own override of 3145728, source DYNAMIC_BROKER_CONFIG, wins over that default.
  • log.dirs cannot change at runtime, and the broker said so. Read-only settings belong in server.properties and need a restart.
  • A value of the wrong type failed with InvalidConfigurationException before anything was stored.

The order of precedence for a topic is: the topic's own override, then the per-broker dynamic value, then the cluster-wide dynamic default, then server.properties, then Kafka's built-in default. The older alterConfigs method, which replaced a resource's whole configuration and silently dropped keys left out, was removed from the Admin API in Kafka 4.0.

Moving replicas and electing leaders

Replicas move when a broker is added, removed or overloaded. A reassignment copies the partition to the new brokers, waits until they are in sync, and only then drops the old replicas. This program places a partition on brokers 0 and 1, moves it to brokers 2 and 1, then changes the preferred leader:

Java
import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.TreeMap;
import org.apache.kafka.clients.admin.Admin;
import org.apache.kafka.clients.admin.LogDirDescription;
import org.apache.kafka.clients.admin.NewPartitionReassignment;
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.ElectionType;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.TopicPartitionInfo;
import org.apache.kafka.common.serialization.StringSerializer;
import org.apache.kafka.common.test.KafkaClusterTestKit;
import org.apache.kafka.common.test.TestKitNodes;
import org.apache.kafka.metadata.bootstrap.BootstrapMetadata;
import org.apache.kafka.server.common.Feature;
import org.apache.kafka.server.common.MetadataVersion;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ReassignAndElect {

    public static void main(String[] args) throws Exception {
        KafkaClusterTestKit cluster = startCluster();
        TopicPartition p0 = new TopicPartition("payments", 0);
        try (Admin admin = Admin.create(Map.<String, Object>of(
                "bootstrap.servers", cluster.bootstrapServers()))) {
            // an explicit assignment: partition 0 on brokers 0 and 1, broker 0 preferred
            admin.createTopics(List.of(new NewTopic("payments",
                    Map.of(0, List.of(0, 1))))).all().get();
            try (KafkaProducer<String, String> producer = new KafkaProducer<>(Map.of(
                    "bootstrap.servers", cluster.bootstrapServers()),
                    new StringSerializer(), new StringSerializer())) {
                for (int i = 0; i < 1000; i++) {
                    producer.send(new ProducerRecord<>("payments", "payment-" + i));
                }
            }
            show(admin, "created", List.of(0, 1));
            logDirs(admin, Set.of(0, 1));

            // move the partition from brokers 0,1 to brokers 2,1
            admin.alterPartitionReassignments(Map.of(p0, Optional.of(
                    new NewPartitionReassignment(List.of(2, 1))))).all().get();
            while (!admin.listPartitionReassignments().reassignments().get().isEmpty()) {
                Thread.sleep(100);
            }
            show(admin, "after moving to [2, 1]", List.of(2, 1));
            logDirs(admin, Set.of(1, 2));

            // swap the order: broker 1 becomes the preferred leader
            admin.alterPartitionReassignments(Map.of(p0, Optional.of(
                    new NewPartitionReassignment(List.of(1, 2))))).all().get();
            while (!admin.listPartitionReassignments().reassignments().get().isEmpty()) {
                Thread.sleep(100);
            }
            show(admin, "after reordering to [1, 2]", List.of(1, 2));
            var result = admin.electLeaders(ElectionType.PREFERRED, Set.of(p0)).partitions().get();
            System.out.println("preferred election: " + result.get(p0)
                    .map(e -> e.getClass().getSimpleName()).orElse("ok"));
            Thread.sleep(500);
            show(admin, "after the election", List.of(1, 2));
            result = admin.electLeaders(ElectionType.PREFERRED, Set.of(p0)).partitions().get();
            System.out.println("second election: " + result.get(p0)
                    .map(e -> e.getClass().getSimpleName()).orElse("ok"));
        } finally {
            cluster.close();
        }
    }

    // waits until the metadata shows the expected replica list, then prints the partition
    static void show(Admin admin, String label, List<Integer> replicas) throws Exception {
        TopicPartitionInfo p;
        do {
            TopicDescription d = admin.describeTopics(List.of("payments")).allTopicNames().get()
                    .get("payments");
            p = d.partitions().get(0);
        } while (!p.replicas().stream().map(n -> n.id()).toList().equals(replicas));
        System.out.println(label + ": replicas " + replicas + ", leader " + p.leader().id()
                + ", isr " + p.isr().stream().map(n -> n.id()).sorted().toList());
    }

    // how many bytes of payments-0 each broker holds on disk
    // (the old replica's files are removed a moment after the move, so it waits for that)
    static void logDirs(Admin admin, Set<Integer> expected) throws Exception {
        Map<Integer, Long> bytes = new TreeMap<>();
        while (!bytes.keySet().equals(expected)) {
            bytes.clear();
            var dirs = admin.describeLogDirs(List.of(0, 1, 2)).allDescriptions().get();
            for (var broker : dirs.entrySet()) {
                for (LogDirDescription dir : broker.getValue().values()) {
                    var info = dir.replicaInfos().get(new TopicPartition("payments", 0));
                    if (info != null) {
                        bytes.put(broker.getKey(), info.size());
                    }
                }
            }
        }
        System.out.println("  bytes of payments-0 per broker: " + bytes);
    }

    // Starts a KRaft cluster in this JVM with KafkaClusterTestKit, Kafka's own test
    // cluster (EmbeddedKafkaKraftBroker is built on it): one controller, three brokers
    static KafkaClusterTestKit startCluster() throws Exception {
        // 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 {
            // production metadata version and feature levels, as a new 4.2 cluster gets
            Map<String, Short> features = new HashMap<>();
            for (Feature f : Feature.PRODUCTION_FEATURES) {
                if (f != Feature.KRAFT_VERSION) {
                    features.put(f.featureName(), f.latestProduction());
                }
            }
            KafkaClusterTestKit cluster = new KafkaClusterTestKit.Builder(
                    new TestKitNodes.Builder()
                            .setCombined(false)
                            .setNumControllerNodes(1)
                            .setNumBrokerNodes(3)
                            .setBootstrapMetadata(BootstrapMetadata.fromVersions(
                                    MetadataVersion.latestProduction(), features, "demo"))
                            .build())
                    .build();
            cluster.format();
            cluster.startup();
            cluster.waitForReadyBrokers();
            return cluster;
        } finally {
            System.setOut(stdout);
        }
    }
}
Output
created: replicas [0, 1], leader 0, isr [0, 1]
  bytes of payments-0 per broker: {0=19072, 1=19072}
after moving to [2, 1]: replicas [2, 1], leader 2, isr [1, 2]
  bytes of payments-0 per broker: {1=19072, 2=19072}
after reordering to [1, 2]: replicas [1, 2], leader 2, isr [1, 2]
preferred election: ok
after the election: replicas [1, 2], leader 1, isr [1, 2]
second election: ElectionNotNeededException
  • The explicit assignment put the partition on brokers 0 and 1, with broker 0 leading. The per-broker byte counts are the same on both: each holds a full copy of the 1,000 records.
  • After the move to [2, 1], broker 0 no longer holds the partition at all, and broker 2 has the same number of bytes. Since broker 0 was removed, leadership moved to broker 2.
  • Reordering the replicas to [1, 2] changed the preferred leader to broker 1, but broker 2 kept leading. A reassignment does not move leadership by itself while the current leader is still a replica.
  • electLeaders(PREFERRED) moved leadership to broker 1. Running it again failed with ElectionNotNeededException, because the preferred replica already led.

Brokers also run preferred elections on their own: with auto.leader.rebalance.enable=true, the default, the controller checks every leader.imbalance.check.interval.seconds (300) and moves leaders back when a broker leads too few of its preferred partitions. A reassignment of a large partition copies all its data over the network, so on a busy cluster limit it with kafka-reassign-partitions.sh --throttle, which sets leader.replication.throttled.rate and follower.replication.throttled.rate on the brokers. The UNCLEAN election type can make an out-of-sync replica the leader, which loses the records it lacks; use it only when the alternative is a partition that stays offline.

Consumer groups and deleting records

Fixing consumer offsets is a frequent task after a bad deployment or a poison record. The program reads ten records with a group, inspects the group, tries to reset it while it runs, resets it after it stops, and deletes old records from the partition:

Java
import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.time.Duration;
import java.util.HashMap;
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.ConsumerGroupDescription;
import org.apache.kafka.clients.admin.GroupListing;
import org.apache.kafka.clients.admin.ListOffsetsResult.ListOffsetsResultInfo;
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.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.consumer.OffsetAndMetadata;
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.apache.kafka.common.test.KafkaClusterTestKit;
import org.apache.kafka.common.test.TestKitNodes;
import org.apache.kafka.metadata.bootstrap.BootstrapMetadata;
import org.apache.kafka.server.common.Feature;
import org.apache.kafka.server.common.MetadataVersion;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class GroupsAndRecords {

    public static void main(String[] args) throws Exception {
        KafkaClusterTestKit cluster = startCluster();
        String bootstrap = cluster.bootstrapServers();
        TopicPartition tp = new TopicPartition("events", 0);
        try (Admin admin = Admin.create(Map.<String, Object>of("bootstrap.servers", bootstrap))) {
            admin.createTopics(List.of(new NewTopic("events", 1, (short) 3))).all().get();
            try (KafkaProducer<String, String> producer = new KafkaProducer<>(
                    Map.of("bootstrap.servers", bootstrap),
                    new StringSerializer(), new StringSerializer())) {
                for (int i = 0; i < 10; i++) {
                    producer.send(new ProducerRecord<>("events", "event-" + i));
                }
            }

            try (KafkaConsumer<String, String> consumer = consumer(bootstrap)) {
                consumer.subscribe(List.of("events"));
                int read = 0;
                while (read < 10) {
                    read += consumer.poll(Duration.ofMillis(500)).count();
                }
                consumer.commitSync();

                for (GroupListing g : admin.listGroups().all().get()) {
                    System.out.println("group " + g.groupId() + ", type " + g.type().orElseThrow()
                            + ", state " + g.groupState().orElseThrow());
                }
                ConsumerGroupDescription d = admin.describeConsumerGroups(List.of("reports"))
                        .all().get().get("reports");
                System.out.println("members " + d.members().size() + ", assignment "
                        + d.members().iterator().next().assignment().topicPartitions());
                System.out.println("committed: " + committed(admin));
                try {
                    admin.alterConsumerGroupOffsets("reports",
                            Map.of(tp, new OffsetAndMetadata(0))).all().get();
                } catch (ExecutionException e) {
                    System.out.println("reset while active: " + e.getCause().getClass()
                            .getSimpleName());
                }
            }

            // the consumer is closed, so the group is empty and can be changed
            admin.alterConsumerGroupOffsets("reports", Map.of(tp, new OffsetAndMetadata(4)))
                    .all().get();
            System.out.println("after reset to 4: " + committed(admin));

            admin.deleteRecords(Map.of(tp, RecordsToDelete.beforeOffset(7))).all().get();
            ListOffsetsResultInfo earliest = admin.listOffsets(Map.of(tp, OffsetSpec.earliest()))
                    .all().get().get(tp);
            ListOffsetsResultInfo latest = admin.listOffsets(Map.of(tp, OffsetSpec.latest()))
                    .all().get().get(tp);
            System.out.println("after deleteRecords(7): earliest " + earliest.offset()
                    + ", latest " + latest.offset());

            try (KafkaConsumer<String, String> consumer = consumer(bootstrap)) {
                consumer.subscribe(List.of("events"));
                ConsumerRecord<String, String> first = null;
                while (first == null) {
                    var records = consumer.poll(Duration.ofMillis(500));
                    first = records.isEmpty() ? null : records.iterator().next();
                }
                System.out.println("group restarts at offset " + first.offset() + ": "
                        + first.value());
            }
            admin.deleteConsumerGroups(List.of("reports")).all().get();
            System.out.println("groups after delete: " + admin.listGroups().all().get().size());
        } finally {
            cluster.close();
        }
    }

    static String committed(Admin admin) throws Exception {
        return admin.listConsumerGroupOffsets("reports").partitionsToOffsetAndMetadata().get()
                .toString();
    }

    static KafkaConsumer<String, String> consumer(String bootstrap) {
        return new KafkaConsumer<>(Map.of("bootstrap.servers", bootstrap,
                "group.id", "reports", "group.protocol", "consumer",
                "auto.offset.reset", "earliest", "enable.auto.commit", "false"),
                new StringDeserializer(), new StringDeserializer());
    }

    // Starts a KRaft cluster in this JVM with KafkaClusterTestKit, Kafka's own test
    // cluster (EmbeddedKafkaKraftBroker is built on it): one controller, three brokers
    static KafkaClusterTestKit startCluster() throws Exception {
        // 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 {
            // production metadata version and feature levels, as a new 4.2 cluster gets
            Map<String, Short> features = new HashMap<>();
            for (Feature f : Feature.PRODUCTION_FEATURES) {
                if (f != Feature.KRAFT_VERSION) {
                    features.put(f.featureName(), f.latestProduction());
                }
            }
            KafkaClusterTestKit cluster = new KafkaClusterTestKit.Builder(
                    new TestKitNodes.Builder()
                            .setCombined(false)
                            .setNumControllerNodes(1)
                            .setNumBrokerNodes(3)
                            .setBootstrapMetadata(BootstrapMetadata.fromVersions(
                                    MetadataVersion.latestProduction(), features, "demo"))
                            .build())
                    .build();
            cluster.format();
            cluster.startup();
            cluster.waitForReadyBrokers();
            return cluster;
        } finally {
            System.setOut(stdout);
        }
    }
}
Output
group reports, type Consumer, state Stable
members 1, assignment [events-0]
committed: {events-0=OffsetAndMetadata{offset=10, leaderEpoch=0, metadata=''}}
reset while active: UnknownMemberIdException
after reset to 4: {events-0=OffsetAndMetadata{offset=4, leaderEpoch=null, metadata=''}}
after deleteRecords(7): earliest 7, latest 10
group restarts at offset 7: event-7
groups after delete: 0
  • listGroups, added in Kafka 4.0, lists groups of every type. This one has type Consumer, because the program set group.protocol=consumer, the KIP-848 protocol that group.version=1 enables. Groups using the older protocol show the type Classic.
  • The group was Stable with one member that owned events-0, and had committed offset 10, the next record to read.
  • Resetting the offsets while the member was active failed with UnknownMemberIdException. The broker only lets the Admin API change offsets of a group with no active members, so that a running consumer cannot overwrite the change a second later.
  • Once the consumer had closed, the reset to offset 4 worked.
  • deleteRecords before offset 7 moved the partition's earliest offset to 7. The records stay on disk until their segment is deleted, but no client can read them.
  • The group restarted at offset 7, not 4: its committed offset pointed at deleted records, so auto.offset.reset=earliest applied and the consumer jumped to the new earliest offset.

The same operations exist on the command line as kafka-consumer-groups.sh --reset-offsets, which also takes --to-datetime and --shift-by, and kafka-delete-records.sh. Always run the reset with --dry-run first, then with --execute.

The command-line tools

The bin/*.sh scripts are thin wrappers around Java classes in kafka-tools and the broker jar. The program runs those classes directly against the same kind of cluster, so the output below is exactly what the scripts print:

Java
import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.HashMap;
import java.util.Map;
import kafka.admin.ConfigCommand;
import org.apache.kafka.common.test.KafkaClusterTestKit;
import org.apache.kafka.common.test.TestKitNodes;
import org.apache.kafka.common.utils.Exit;
import org.apache.kafka.metadata.bootstrap.BootstrapMetadata;
import org.apache.kafka.server.common.Feature;
import org.apache.kafka.server.common.MetadataVersion;
import org.apache.kafka.tools.TopicCommand;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CliTools {

    public static void main(String[] args) throws Exception {
        KafkaClusterTestKit cluster = startCluster();
        String bootstrap = cluster.bootstrapServers();
        // the tools call System.exit when they finish; Kafka's own tests swap that out
        Exit.setExitProcedure((code, message) -> {
            if (code != 0) {
                System.out.println("(exit code " + code + ")");
            }
        });
        try {
            run("kafka-topics.sh --create", () -> TopicCommand.main("--bootstrap-server",
                    bootstrap, "--create", "--topic", "orders", "--partitions", "3",
                    "--replication-factor", "3", "--config", "min.insync.replicas=2"));
            run("kafka-topics.sh --describe", () -> TopicCommand.main("--bootstrap-server",
                    bootstrap, "--describe", "--topic", "orders"));
            run("kafka-configs.sh --alter", () -> ConfigCommand.main(new String[] {
                "--bootstrap-server", bootstrap, "--alter", "--entity-type", "topics",
                "--entity-name", "orders", "--add-config", "retention.ms=86400000"}));
            run("kafka-configs.sh --describe", () -> ConfigCommand.main(new String[] {
                "--bootstrap-server", bootstrap, "--describe", "--entity-type", "topics",
                "--entity-name", "orders"}));
            run("kafka-topics.sh --describe --under-replicated-partitions",
                    () -> TopicCommand.main("--bootstrap-server", bootstrap, "--describe",
                            "--under-replicated-partitions"));
        } finally {
            Exit.resetExitProcedure();
            cluster.close();
        }
    }

    static void run(String label, Runnable tool) {
        System.out.println("$ " + label);
        tool.run();
        System.out.println();
    }

    // Starts a KRaft cluster in this JVM with KafkaClusterTestKit, Kafka's own test
    // cluster (EmbeddedKafkaKraftBroker is built on it): one controller, three brokers
    static KafkaClusterTestKit startCluster() throws Exception {
        // 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 {
            // production metadata version and feature levels, as a new 4.2 cluster gets
            Map<String, Short> features = new HashMap<>();
            for (Feature f : Feature.PRODUCTION_FEATURES) {
                if (f != Feature.KRAFT_VERSION) {
                    features.put(f.featureName(), f.latestProduction());
                }
            }
            KafkaClusterTestKit cluster = new KafkaClusterTestKit.Builder(
                    new TestKitNodes.Builder()
                            .setCombined(false)
                            .setNumControllerNodes(1)
                            .setNumBrokerNodes(3)
                            .setBootstrapMetadata(BootstrapMetadata.fromVersions(
                                    MetadataVersion.latestProduction(), features, "demo"))
                            .build())
                    .build();
            cluster.format();
            cluster.startup();
            cluster.waitForReadyBrokers();
            return cluster;
        } finally {
            System.setOut(stdout);
        }
    }
}
Output
$ kafka-topics.sh --create
Created topic orders.

$ kafka-topics.sh --describe
Topic: orders	TopicId: qMcjc39ERFSa3LZ8VpTvDg	PartitionCount: 3	ReplicationFactor: 3	Configs: min.insync.replicas=2
	Topic: orders	Partition: 0	Leader: 1	Replicas: 1,2,0	Isr: 1,2,0	Elr: 	LastKnownElr: 
	Topic: orders	Partition: 1	Leader: 2	Replicas: 2,0,1	Isr: 2,0,1	Elr: 	LastKnownElr: 
	Topic: orders	Partition: 2	Leader: 0	Replicas: 0,1,2	Isr: 0,1,2	Elr: 	LastKnownElr: 

$ kafka-configs.sh --alter
Completed updating config for topic orders.

$ kafka-configs.sh --describe
Dynamic configs for topic orders are:
  min.insync.replicas=2 sensitive=false synonyms={DYNAMIC_TOPIC_CONFIG:min.insync.replicas=2, DYNAMIC_DEFAULT_BROKER_CONFIG:min.insync.replicas=1, DEFAULT_CONFIG:min.insync.replicas=1}
  retention.ms=86400000 sensitive=false synonyms={DYNAMIC_TOPIC_CONFIG:retention.ms=86400000}

$ kafka-topics.sh --describe --under-replicated-partitions
  • --describe prints one line per topic and one per partition. The TopicId is a random UUID that changes on every run. Elr and LastKnownElr list eligible leader replicas (KIP-966), enabled here by eligible.leader.replicas.version=1; they are empty while every replica is in sync.
  • kafka-configs.sh --describe lists only dynamic values, each with its synonyms in order of precedence. min.insync.replicas=2 on the topic overrides a cluster-wide dynamic default of 1. The program never set that default; the cluster keeps a cluster-level min.insync.replicas when eligible leader replicas are enabled.
  • --under-replicated-partitions printed nothing, which is the healthy answer. Its sibling flags --unavailable-partitions and --under-min-isr-partitions make quick health checks.

The tools exit the JVM when they finish; the program replaces that with Exit.setExitProcedure, as Kafka's own tests do. In a shell, every tool takes --bootstrap-server, and --command-config client.properties for a secured cluster, as on Kafka security.

Choosing the right operation

Administrative tasks and how to do them
TaskAdmin APICommand line
Check brokers and controllersdescribeCluster, describeMetadataQuorumkafka-metadata-quorum.sh describe --status
Create a topic safelycreateTopics with validateOnly, then withoutkafka-topics.sh --create
More consumer parallelismcreatePartitions, accepting the key remappingkafka-topics.sh --alter --partitions
Change retention or compactionincrementalAlterConfigs on the topickafka-configs.sh --alter --add-config
Change a setting on every brokerincrementalAlterConfigs on broker ""kafka-configs.sh --entity-type brokers --entity-default
Add or remove a brokeralterPartitionReassignmentskafka-reassign-partitions.sh with --throttle
Rebalance leadershipelectLeaders(PREFERRED)kafka-leader-election.sh --election-type preferred
Replay or skip records for a groupalterConsumerGroupOffsets on a stopped groupkafka-consumer-groups.sh --reset-offsets
Remove old or bad recordsdeleteRecordskafka-delete-records.sh

The partition model behind these operations is explained on Kafka topics and partitions, and committed offsets on Kafka offsets. To watch the cluster's health between changes, see Kafka monitoring and consumer lag monitoring.