Kafka rebalancing: how partitions move between consumers

When consumers join or leave a group, Kafka moves partitions between them, and how it does so decides how long processing stops and whether records are repeated. This page explains both rebalance protocols, then runs eager and cooperative assignors, the new consumer protocol, static membership and commits on revocation.

Share

Contents

What a rebalance is and why it happens

A consumer group shares the partitions of its topics among its members, one member per partition. A rebalance is the process of working out a new assignment when that set changes: a member joins, leaves or is considered dead, partitions are added to a subscribed topic, or a subscription changes. During a rebalance, some partitions are moved from one member to another, and the records of a partition being moved are not processed until its new owner starts.

Kafka 4.2 offers two rebalance protocols, chosen on the consumer with group.protocol:

  • classic (the default): the members do the work. Every member sends a JoinGroup request, one member, the group leader, computes the assignment with the client-side partition.assignment.strategy, and the coordinator hands it out with SyncGroup. Every member must take part, so one slow member delays the whole group.
  • consumer (KIP-848, generally available since Kafka 4.0): the group coordinator on the broker computes the assignment with a server-side assignor, and tells each member, through its regular heartbeat, which partitions to give up and which to take. Members never wait for each other.

Within the classic protocol, the assignor also decides how disruptive a rebalance is. Eager assignors such as RangeAssignor make every member give up all its partitions at the start of each rebalance, a "stop-the-world" pause. CooperativeStickyAssignor revokes only the partitions that actually move, in two rounds.

Rebalance options in Kafka 4.2
OptionAssignment computed byPartitions revokedSince
Classic, RangeAssignor (default list's first entry)Group leader (a client)All, on every memberOriginal protocol
Classic, CooperativeStickyAssignorGroup leaderOnly the moved onesThe 2.4 release (KIP-429)
group.protocol=consumerGroup coordinator (broker)Only the moved onesKafka 4.0 (KIP-848)
Static membership, group.instance.idEither protocolNone on a quick restartThe 2.3 release (KIP-345)

The examples use kafka-clients 4.2.2. Each program first starts its own single-node Kafka 4.2 broker inside the JVM, with EmbeddedKafkaKraftBroker from spring-kafka-test. Several consumers run in one thread, polled in turn, which is enough to make the group rebalance exactly as separate processes would. A real cluster has three or more brokers.

Eager, cooperative and the new consumer protocol

One scenario shows the difference: consumer c1 owns all four partitions of a topic, then c2 joins. A ConsumerRebalanceListener on each consumer prints every partition it loses or gains:

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.Collection;
import java.util.HashMap;
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.ConsumerRebalanceListener;
import org.apache.kafka.clients.consumer.CooperativeStickyAssignor;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.consumer.RangeAssignor;
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 EagerVsCooperative {

    static String servers;
    static volatile boolean quiet; // set while the program closes everything at the end

    public static void main(String[] args) throws Exception {
        EmbeddedKafkaBroker broker = startBroker();
        servers = broker.getBrokersAsString();
        try {
            broker.addTopics(new NewTopic("clicks", 4, (short) 1));
            scenario("classic protocol, RangeAssignor (eager)",
                    Map.of("partition.assignment.strategy", RangeAssignor.class.getName()));
            scenario("classic protocol, CooperativeStickyAssignor", Map.of(
                    "partition.assignment.strategy", CooperativeStickyAssignor.class.getName()));
            scenario("consumer protocol (KIP-848)", Map.of("group.protocol", "consumer"));
        } finally {
            broker.destroy();
        }
    }

    // c1 owns all four partitions, then c2 joins the group
    static void scenario(String title, Map<String, Object> settings) {
        System.out.println(title + ":");
        String group = "g-" + title.hashCode();
        List<KafkaConsumer<String, String>> members = new ArrayList<>();
        try {
            members.add(join("c1", group, settings));
            settle(members, 4);
            members.add(join("c2", group, settings));
            settle(members, 4);
        } finally {
            quiet = true;
            members.forEach(KafkaConsumer::close);
            quiet = false;
        }
    }

    static KafkaConsumer<String, String> join(String name, String group,
            Map<String, Object> settings) {
        Map<String, Object> props = new HashMap<>(settings);
        props.put("bootstrap.servers", servers);
        props.put("group.id", group);
        props.put("key.deserializer", StringDeserializer.class);
        props.put("value.deserializer", StringDeserializer.class);
        KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props);
        consumer.subscribe(List.of("clicks"), new ConsumerRebalanceListener() {
            @Override
            public void onPartitionsRevoked(Collection<TopicPartition> partitions) {
                if (!partitions.isEmpty() && !quiet) {
                    System.out.println("   " + name + " revoked  " + numbers(partitions));
                }
            }

            @Override
            public void onPartitionsAssigned(Collection<TopicPartition> partitions) {
                if (!partitions.isEmpty()) {
                    System.out.println("   " + name + " assigned " + numbers(partitions));
                }
            }
        });
        return consumer;
    }

    // polls every member until the partitions are spread and nothing has changed for 3 s
    static void settle(List<KafkaConsumer<String, String>> members, int partitions) {
        String last = "";
        long stableSince = System.currentTimeMillis();
        while (System.currentTimeMillis() - stableSince < 3000) {
            members.forEach(c -> c.poll(Duration.ofMillis(100)));
            StringBuilder now = new StringBuilder();
            int total = 0;
            for (KafkaConsumer<String, String> c : members) {
                now.append(numbers(c.assignment()));
                total += c.assignment().size();
            }
            boolean spread = members.stream().noneMatch(c -> c.assignment().isEmpty());
            if (!now.toString().equals(last) || total != partitions || !spread) {
                last = now.toString();
                stableSince = System.currentTimeMillis();
            }
        }
    }

    static TreeSet<Integer> numbers(Collection<TopicPartition> partitions) {
        TreeSet<Integer> set = new TreeSet<>();
        partitions.forEach(p -> set.add(p.partition()));
        return set;
    }

    // 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
classic protocol, RangeAssignor (eager):
   c1 assigned [0, 1, 2, 3]
   c1 revoked  [0, 1, 2, 3]
   c1 assigned [0, 1]
   c2 assigned [2, 3]
classic protocol, CooperativeStickyAssignor:
   c1 assigned [0, 1, 2, 3]
   c1 revoked  [2, 3]
   c2 assigned [2, 3]
consumer protocol (KIP-848):
   c1 assigned [0, 1, 2, 3]
   c1 revoked  [2, 3]
   c2 assigned [2, 3]
  • With the eager RangeAssignor, c1 lost all four partitions when c2 joined, then got 0 and 1 back. Partitions 0 and 1 never changed owner, yet c1 stopped processing them for the length of the rebalance.
  • With CooperativeStickyAssignor, c1 gave up only partitions 2 and 3, which c2 received. c1 kept processing partitions 0 and 1 throughout.
  • The consumer protocol produced the same minimal movement, with the assignment computed by the broker and no client-side assignor configured.

The difference grows with the size of the group. With eager rebalancing, every member stops for every change, so a group of fifty instances restarted one by one stops fifty times, twice. With cooperative rebalancing and the consumer protocol, only the partitions that change owner pause, and only for as long as the handover takes. The cooperative assignor needs a second round to hand out the revoked partitions, which is why c2 received them in a separate step; the consumer protocol does the same through ordinary heartbeats, without a group-wide barrier.

The default partition.assignment.strategy is the list [RangeAssignor, CooperativeStickyAssignor], which behaves eagerly. The list exists so that a group can move to cooperative rebalancing with one rolling restart that removes RangeAssignor; switching straight from one to the other in a single restart is not supported. For the consumer protocol, the broker must have it enabled, which is the default in Kafka 4.x, and every member of the group should switch together.

Static membership for restarts

A rolling deploy restarts every instance of a service, and with dynamic membership each restart causes two rebalances: one when the instance leaves, one when it comes back. Static membership gives each instance a fixed group.instance.id. The program restarts web-1 in a group of two, first as dynamic members, then as static ones:

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.Collection;
import java.util.HashMap;
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.ConsumerRebalanceListener;
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 StaticMembership {

    static String servers;
    static volatile boolean quiet; // set while the program closes everything at the end

    public static void main(String[] args) throws Exception {
        EmbeddedKafkaBroker broker = startBroker();
        servers = broker.getBrokersAsString();
        try {
            broker.addTopics(new NewTopic("carts", 4, (short) 1));
            for (boolean isStatic : new boolean[] {false, true}) {
                System.out.println(isStatic ? "static members (group.instance.id set):"
                        : "dynamic members:");
                String group = isStatic ? "carts-static" : "carts-dynamic";
                List<KafkaConsumer<String, String>> members = new ArrayList<>();
                members.add(join("web-1", group, settings(isStatic, "web-1")));
                settle(members, 4);
                members.add(join("web-2", group, settings(isStatic, "web-2")));
                settle(members, 4);
                System.out.println("   -- web-1 restarts (a rolling deploy) --");
                members.remove(0).close();
                if (!isStatic) {
                    settle(members, 4); // the group reacts to the leave at once
                }
                members.add(0, join("web-1", group, settings(isStatic, "web-1")));
                settle(members, 4);
                quiet = true;
                members.forEach(KafkaConsumer::close);
                quiet = false;
            }
        } finally {
            broker.destroy();
        }
    }

    static Map<String, Object> settings(boolean isStatic, String instance) {
        Map<String, Object> settings = new HashMap<>();
        settings.put("session.timeout.ms", 10000);
        if (isStatic) {
            settings.put("group.instance.id", instance);
        }
        return settings;
    }

    static KafkaConsumer<String, String> join(String name, String group,
            Map<String, Object> settings) {
        Map<String, Object> props = new HashMap<>(settings);
        props.put("bootstrap.servers", servers);
        props.put("group.id", group);
        props.put("key.deserializer", StringDeserializer.class);
        props.put("value.deserializer", StringDeserializer.class);
        KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props);
        consumer.subscribe(List.of("carts"), new ConsumerRebalanceListener() {
            @Override
            public void onPartitionsRevoked(Collection<TopicPartition> partitions) {
                if (!partitions.isEmpty() && !quiet) {
                    System.out.println("   " + name + " revoked  " + numbers(partitions));
                }
            }

            @Override
            public void onPartitionsAssigned(Collection<TopicPartition> partitions) {
                if (!partitions.isEmpty()) {
                    System.out.println("   " + name + " assigned " + numbers(partitions));
                }
            }
        });
        return consumer;
    }

    // polls every member until the partitions are spread and nothing has changed for 3 s
    static void settle(List<KafkaConsumer<String, String>> members, int partitions) {
        String last = "";
        long stableSince = System.currentTimeMillis();
        while (System.currentTimeMillis() - stableSince < 3000) {
            members.forEach(c -> c.poll(Duration.ofMillis(100)));
            StringBuilder now = new StringBuilder();
            int total = 0;
            for (KafkaConsumer<String, String> c : members) {
                now.append(numbers(c.assignment()));
                total += c.assignment().size();
            }
            boolean spread = members.stream().noneMatch(c -> c.assignment().isEmpty());
            if (!now.toString().equals(last) || total != partitions || !spread) {
                last = now.toString();
                stableSince = System.currentTimeMillis();
            }
        }
    }

    static TreeSet<Integer> numbers(Collection<TopicPartition> partitions) {
        TreeSet<Integer> set = new TreeSet<>();
        partitions.forEach(p -> set.add(p.partition()));
        return set;
    }

    // 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
dynamic members:
   web-1 assigned [0, 1, 2, 3]
   web-1 revoked  [0, 1, 2, 3]
   web-1 assigned [0, 1]
   web-2 assigned [2, 3]
   -- web-1 restarts (a rolling deploy) --
   web-1 revoked  [0, 1]
   web-2 revoked  [2, 3]
   web-2 assigned [0, 1, 2, 3]
   web-2 revoked  [0, 1, 2, 3]
   web-2 assigned [0, 1]
   web-1 assigned [2, 3]
static members (group.instance.id set):
   web-1 assigned [0, 1, 2, 3]
   web-1 revoked  [0, 1, 2, 3]
   web-1 assigned [0, 1]
   web-2 assigned [2, 3]
   -- web-1 restarts (a rolling deploy) --
   web-1 revoked  [0, 1]
   web-1 assigned [0, 1]
  • As dynamic members, web-1's close() sent a leave request. The group rebalanced at once and web-2 took all four partitions. When web-1 came back, the group rebalanced a second time, and the partitions were split again, with web-1 now on 2 and 3 instead of 0 and 1.
  • As static members, close() did not leave the group. The coordinator kept web-1's partitions reserved for session.timeout.ms, 10 seconds here. The new web-1 came back with the same instance id, got partitions 0 and 1 again, and web-2 noticed nothing at all.

The price is slower failure detection: if a static member really dies, its partitions are idle until the session timeout expires. Choose a session.timeout.ms a little longer than a normal restart. Each group.instance.id must be unique within the group, for example the pod name in Kubernetes; a second consumer with the same id fences the first one.

Committing before partitions move

A partition that moves takes its committed offset with it, not the position of the consumer that had it. A consumer that commits only now and then loses its uncommitted work to the next owner. Here c1 sends e-mails for 20 records and plans to commit every 50, when c2 joins:

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.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.clients.consumer.ConsumerRebalanceListener;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;

public class CommitOnRevoke {

    static String servers;

    public static void main(String[] args) throws Exception {
        EmbeddedKafkaBroker broker = startBroker();
        servers = broker.getBrokersAsString();
        try {
            broker.addTopics(new NewTopic("emails", 2, (short) 1));
            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 < 20; i++) {
                    producer.send(new ProducerRecord<>("emails", i % 2, null, "mail-" + i));
                }
            }
            run("commits every 50 records only", false);
            run("also commits in onPartitionsRevoked", true);
        } finally {
            broker.destroy();
        }
    }

    static void run(String title, boolean commitOnRevoke) {
        String group = commitOnRevoke ? "mailer-b" : "mailer-a";
        List<String> sent = new ArrayList<>();
        Map<TopicPartition, OffsetAndMetadata> pending = new HashMap<>();
        KafkaConsumer<String, String> c1 = consumer(group);
        c1.subscribe(List.of("emails"), new ConsumerRebalanceListener() {
            @Override
            public void onPartitionsRevoked(Collection<TopicPartition> partitions) {
                if (commitOnRevoke && !pending.isEmpty()) {
                    c1.commitSync(pending); // runs inside poll(), before the move
                    pending.clear();
                }
            }

            @Override
            public void onPartitionsAssigned(Collection<TopicPartition> partitions) {
            }
        });
        while (sent.size() < 20) {
            for (ConsumerRecord<String, String> r : c1.poll(Duration.ofSeconds(1))) {
                sent.add(r.value()); // "send the e-mail"
                pending.put(new TopicPartition(r.topic(), r.partition()),
                        new OffsetAndMetadata(r.offset() + 1));
            }
        }
        // a second instance joins before c1 reached its 50-record commit
        try (KafkaConsumer<String, String> c2 = consumer(group)) {
            c2.subscribe(List.of("emails"));
            long quietSince = System.currentTimeMillis();
            while (System.currentTimeMillis() - quietSince < 3000) {
                c1.poll(Duration.ofMillis(100));
                for (ConsumerRecord<String, String> r : c2.poll(Duration.ofMillis(100))) {
                    sent.add(r.value());
                    quietSince = System.currentTimeMillis();
                }
                if (c2.assignment().isEmpty()) {
                    quietSince = System.currentTimeMillis();
                }
            }
            System.out.println(title + ": c2 got partitions " + c2.assignment().stream()
                    .map(TopicPartition::partition).toList() + ", e-mails sent " + sent.size()
                    + " for 20 records, duplicates " + (sent.size() - 20));
        }
        c1.close();
    }

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

    // 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
commits every 50 records only: c2 got partitions [1], e-mails sent 30 for 20 records, duplicates 10
also commits in onPartitionsRevoked: c2 got partitions [1], e-mails sent 20 for 20 records, duplicates 0
  • Without a commit on revocation, partition 1 moved to c2 with no committed offset, so c2 started from the beginning and sent its 10 e-mails a second time: 30 e-mails for 20 records.
  • With commitSync(pending) in onPartitionsRevoked, c1 committed what it had processed before giving the partition up, and c2 started after it, so no e-mail was sent twice.

The listener runs inside poll() on the consumer's own thread, so it may call commitSync safely. Keep it short: with the classic protocol, the whole group waits for it. onPartitionsAssigned is the matching place to seek to offsets kept outside Kafka, as the offsets page shows. There is a third callback, onPartitionsLost, for partitions taken away after a session timeout; they already belong to someone else, so it must not commit.

Inspecting a group

Admin.describeConsumerGroups, which kafka-consumer-groups.sh --describe also uses, shows a group's protocol, state and assignment. The program runs one group with each protocol, and tries a setting that the new protocol does not accept:

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 org.apache.kafka.clients.admin.Admin;
import org.apache.kafka.clients.admin.ConsumerGroupDescription;
import org.apache.kafka.clients.admin.MemberDescription;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.config.ConfigException;
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 GroupDescription {

    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))) {
            broker.addTopics(new NewTopic("payments", 3, (short) 1));
            for (String protocol : List.of("classic", "consumer")) {
                try (KafkaConsumer<String, String> a = consumer(protocol, "a");
                     KafkaConsumer<String, String> b = consumer(protocol, "b")) {
                    a.subscribe(List.of("payments"));
                    b.subscribe(List.of("payments"));
                    while (a.assignment().size() + b.assignment().size() < 3
                            || a.assignment().isEmpty() || b.assignment().isEmpty()) {
                        a.poll(Duration.ofMillis(100));
                        b.poll(Duration.ofMillis(100));
                    }
                    ConsumerGroupDescription d = admin.describeConsumerGroups(
                            List.of("pay-" + protocol)).all().get().get("pay-" + protocol);
                    System.out.println("group pay-" + protocol + ": type " + d.type()
                            + ", state " + d.groupState() + ", assignor "
                            + d.partitionAssignor());
                    for (MemberDescription m : d.members().stream()
                            .sorted((x, y) -> x.clientId().compareTo(y.clientId())).toList()) {
                        System.out.println("   member " + m.clientId() + " -> partitions "
                                + m.assignment().topicPartitions().stream()
                                .map(tp -> tp.partition()).sorted().toList());
                    }
                }
            }
            try {
                Map<String, Object> props = props("consumer", "x");
                props.put("partition.assignment.strategy",
                        "org.apache.kafka.clients.consumer.CooperativeStickyAssignor");
                new KafkaConsumer<String, String>(props).close();
            } catch (ConfigException e) {
                System.out.println("assignment strategy with group.protocol=consumer: "
                        + e.getMessage());
            }
        } finally {
            broker.destroy();
        }
    }

    static Map<String, Object> props(String protocol, String name) {
        Map<String, Object> props = new HashMap<>();
        props.put("bootstrap.servers", servers);
        props.put("group.id", "pay-" + protocol);
        props.put("group.protocol", protocol);
        props.put("client.id", protocol + "-" + name);
        props.put("key.deserializer", StringDeserializer.class);
        props.put("value.deserializer", StringDeserializer.class);
        return props;
    }

    static KafkaConsumer<String, String> consumer(String protocol, String name) {
        return new KafkaConsumer<>(props(protocol, name));
    }

    // 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
group pay-classic: type Classic, state Stable, assignor range
   member classic-a -> partitions [0, 1]
   member classic-b -> partitions [2]
group pay-consumer: type Consumer, state Stable, assignor uniform
   member consumer-a -> partitions [0, 1]
   member consumer-b -> partitions [2]
assignment strategy with group.protocol=consumer: partition.assignment.strategy cannot be set when group.protocol=CONSUMER
  • The classic group reported type Classic, state Stable and the client-side assignor range, chosen by the group leader from the members' lists.
  • The consumer-protocol group reported type Consumer and the server-side assignor uniform, the broker's first entry in group.consumer.assignors. A member can ask for another with group.remote.assignor, for example range.
  • Both groups split three partitions as two and one.
  • Setting partition.assignment.strategy together with group.protocol=consumer was refused in the constructor: the client-side assignor has no role in the new protocol.

Other settings also move to the broker with the new protocol: the session timeout and heartbeat interval are group settings (group.consumer.session.timeout.ms and group.consumer.heartbeat.interval.ms on the broker, or per group), so the client-side session.timeout.ms and heartbeat.interval.ms are not used. max.poll.interval.ms still applies on the client.

Diagnosing frequent rebalances

A group that rebalances again and again processes little. The usual causes, and how to recognise them:

  • Slow processing: a batch takes longer than max.poll.interval.ms, the member leaves, rejoins, and the cycle repeats. The client logs that the poll interval was exceeded; lower max.poll.records or speed up processing (see the consumer page).
  • Missed heartbeats: long garbage-collection pauses or an overloaded host stop the heartbeat thread for longer than the session timeout.
  • Deploys and autoscaling: every instance that starts or stops triggers rebalances; static membership and the consumer protocol remove most of them.
  • Unstable subscriptions: a pattern subscription that keeps matching new topics, or members with different subscriptions in one group.

The consumer's rebalance-total, rebalance-rate-per-hour and last-rebalance-seconds-ago metrics, in the consumer-coordinator-metrics group, show how often it happens; the monitoring page covers collecting them.

Choosing a rebalance setup

Situations and the rebalance setup that fits
SituationSetup
New applications on Kafka 4.x brokersgroup.protocol=consumer
Existing classic groupsCooperativeStickyAssignor, reached with two rolling restarts
Frequent rolling deploys, stable instance namesStatic membership with a session timeout longer than a restart
Work committed in batchesCommit in onPartitionsRevoked
Offsets stored outside Kafkaseek in onPartitionsAssigned
Slow recordsSmaller max.poll.records, or pause() with a worker thread

Related pages: Kafka consumers, offsets and lag monitoring. Spring's listener containers handle the listener callbacks for you; see @KafkaListener.