You are viewing a plain text version of this content. The canonical link for it is here.
Posted to jira@kafka.apache.org by "Hangleton (via GitHub)" <gi...@apache.org> on 2023/04/04 12:04:01 UTC

[GitHub] [kafka] Hangleton commented on a diff in pull request #13476: KAFKA-14462; [4/N] Add GroupMetadataManager: ConsumerGroups Management, Members Management and Reconciliation Logic

Hangleton commented on code in PR #13476:
URL: https://github.com/apache/kafka/pull/13476#discussion_r1155927791


##########
group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java:
##########
@@ -0,0 +1,860 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.kafka.coordinator.group;
+
+import org.apache.kafka.common.Uuid;
+import org.apache.kafka.common.errors.FencedMemberEpochException;
+import org.apache.kafka.common.errors.GroupIdNotFoundException;
+import org.apache.kafka.common.errors.GroupMaxSizeReachedException;
+import org.apache.kafka.common.errors.InvalidRequestException;
+import org.apache.kafka.common.errors.NotCoordinatorException;
+import org.apache.kafka.common.errors.UnsupportedAssignorException;
+import org.apache.kafka.common.message.ConsumerGroupHeartbeatRequestData;
+import org.apache.kafka.common.message.ConsumerGroupHeartbeatResponseData;
+import org.apache.kafka.common.requests.RequestContext;
+import org.apache.kafka.common.utils.LogContext;
+import org.apache.kafka.coordinator.group.assignor.PartitionAssignor;
+import org.apache.kafka.coordinator.group.consumer.ConsumerGroup;
+import org.apache.kafka.coordinator.group.consumer.ConsumerGroupMember;
+import org.apache.kafka.coordinator.group.consumer.ConsumerGroupMemberAssignment;
+import org.apache.kafka.coordinator.group.consumer.CurrentAssignmentBuilder;
+import org.apache.kafka.coordinator.group.consumer.TargetAssignmentBuilder;
+import org.apache.kafka.coordinator.group.consumer.TopicMetadata;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupCurrentMemberAssignmentKey;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupCurrentMemberAssignmentValue;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupMemberMetadataKey;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupMemberMetadataValue;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupMetadataKey;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupMetadataValue;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupPartitionMetadataKey;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupPartitionMetadataValue;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupTargetAssignmentMemberKey;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupTargetAssignmentMemberValue;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupTargetAssignmentMetadataKey;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupTargetAssignmentMetadataValue;
+import org.apache.kafka.image.TopicsImage;
+import org.apache.kafka.timeline.SnapshotRegistry;
+import org.apache.kafka.timeline.TimelineHashMap;
+import org.apache.kafka.timeline.TimelineHashSet;
+import org.slf4j.Logger;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.OptionalInt;
+import java.util.Set;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+
+import static org.apache.kafka.coordinator.group.RecordHelpers.newCurrentAssignmentRecord;
+import static org.apache.kafka.coordinator.group.RecordHelpers.newCurrentAssignmentTombstoneRecord;
+import static org.apache.kafka.coordinator.group.RecordHelpers.newGroupEpochRecord;
+import static org.apache.kafka.coordinator.group.RecordHelpers.newGroupSubscriptionMetadataRecord;
+import static org.apache.kafka.coordinator.group.RecordHelpers.newMemberSubscriptionRecord;
+import static org.apache.kafka.coordinator.group.RecordHelpers.newMemberSubscriptionTombstoneRecord;
+import static org.apache.kafka.coordinator.group.RecordHelpers.newTargetAssignmentTombstoneRecord;
+
+/**
+ * The GroupMetadataManager manages the metadata of all generic and consumer groups. It holds
+ * the hard and the soft state of the groups. This class has two kinds of methods:
+ * 1) The request handlers which handle the requests and generate a response and records to
+ *    mutate the hard state. Those records will be written by the runtime and applied to the
+ *    hard stay via the replay methods.

Review Comment:
   nit: stay -> state



##########
group-coordinator/src/test/java/org/apache/kafka/coordinator/group/consumer/AssignmentTestUtil.java:
##########
@@ -0,0 +1,68 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.kafka.coordinator.group.consumer;
+
+import org.apache.kafka.common.Uuid;
+
+import java.util.AbstractMap;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeSet;
+
+public class AssignmentTestUtil {
+    public static Map.Entry<Uuid, Set<Integer>> mkTopicAssignment(
+        Uuid topicId,
+        Integer... partitions
+    ) {
+        return new AbstractMap.SimpleEntry<>(
+            topicId,
+            new HashSet<>(Arrays.asList(partitions))
+        );
+    }
+
+    public static Map.Entry<Uuid, Set<Integer>> mkOrderedTopicAssignment(

Review Comment:
   nit: ordered -> sorted



##########
group-coordinator/src/main/java/org/apache/kafka/coordinator/group/RecordHelpers.java:
##########
@@ -0,0 +1,283 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.kafka.coordinator.group;
+
+import org.apache.kafka.common.Uuid;
+import org.apache.kafka.coordinator.group.consumer.ConsumerGroupMember;
+import org.apache.kafka.coordinator.group.consumer.TopicMetadata;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupCurrentMemberAssignmentKey;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupCurrentMemberAssignmentValue;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupMemberMetadataKey;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupMemberMetadataValue;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupMetadataKey;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupMetadataValue;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupPartitionMetadataKey;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupPartitionMetadataValue;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupTargetAssignmentMemberKey;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupTargetAssignmentMemberValue;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupTargetAssignmentMetadataKey;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupTargetAssignmentMetadataValue;
+import org.apache.kafka.server.common.ApiMessageAndVersion;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+public class RecordHelpers {
+    private RecordHelpers() {}
+
+    public static Record newMemberSubscriptionRecord(
+        String groupId,
+        ConsumerGroupMember member
+    ) {
+        return new Record(
+            new ApiMessageAndVersion(
+                new ConsumerGroupMemberMetadataKey()
+                    .setGroupId(groupId)
+                    .setMemberId(member.memberId()),
+                (short) 5
+            ),
+            new ApiMessageAndVersion(
+                new ConsumerGroupMemberMetadataValue()

Review Comment:
   nit: could maybe be added as `ConsumerGroupMember#toRecord()`?



##########
group-coordinator/src/main/java/org/apache/kafka/coordinator/group/consumer/TargetAssignmentBuilder.java:
##########
@@ -0,0 +1,284 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.kafka.coordinator.group.consumer;
+
+import org.apache.kafka.common.Uuid;
+import org.apache.kafka.coordinator.group.assignor.AssignmentMemberSpec;
+import org.apache.kafka.coordinator.group.assignor.AssignmentSpec;
+import org.apache.kafka.coordinator.group.assignor.AssignmentTopicMetadata;
+import org.apache.kafka.coordinator.group.assignor.GroupAssignment;
+import org.apache.kafka.coordinator.group.assignor.MemberAssignment;
+import org.apache.kafka.coordinator.group.assignor.PartitionAssignor;
+import org.apache.kafka.coordinator.group.assignor.PartitionAssignorException;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Set;
+
+import static org.apache.kafka.coordinator.group.RecordHelpers.newTargetAssignmentEpochRecord;
+import static org.apache.kafka.coordinator.group.RecordHelpers.newTargetAssignmentRecord;
+
+/**
+ * Build a new Target Assignment based on the provided parameters. As a result,
+ * it yields the records that must be persisted to the log and the new member
+ * assignments as a map.
+ *
+ * Records are only created for members which have a new target assignment. If
+ * their assignment did not change, no new record is needed.
+ *
+ * When a member is deleted, it is assumed that its target assignment record
+ * is deleted as part of the member deletion process. In other words, this class
+ * does not yield a tombstone for remove members.
+ */
+public class TargetAssignmentBuilder {
+    public static class TargetAssignmentResult {
+        private final List<org.apache.kafka.coordinator.group.Record> records;
+        private final Map<String, ConsumerGroupMemberAssignment> assignments;
+
+        TargetAssignmentResult(
+            List<org.apache.kafka.coordinator.group.Record> records,
+            Map<String, ConsumerGroupMemberAssignment> assignments
+        ) {
+            Objects.requireNonNull(records);
+            Objects.requireNonNull(assignments);
+            this.records = records;

Review Comment:
   nit - `this.records = Objects.requireNonNull(records);`



##########
group-coordinator/src/main/java/org/apache/kafka/coordinator/group/consumer/ConsumerGroup.java:
##########
@@ -0,0 +1,538 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.kafka.coordinator.group.consumer;
+
+import org.apache.kafka.common.Uuid;
+import org.apache.kafka.common.errors.UnknownMemberIdException;
+import org.apache.kafka.coordinator.group.Group;
+import org.apache.kafka.image.TopicImage;
+import org.apache.kafka.image.TopicsImage;
+import org.apache.kafka.timeline.SnapshotRegistry;
+import org.apache.kafka.timeline.TimelineHashMap;
+import org.apache.kafka.timeline.TimelineInteger;
+import org.apache.kafka.timeline.TimelineObject;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Set;
+import java.util.function.Consumer;
+
+/**
+ * A Consumer Group. All the metadata in this class are backed by
+ * records in the __consumer_offsets partitions.
+ */
+public class ConsumerGroup implements Group {
+
+    public enum ConsumerGroupState {
+        EMPTY("empty"),
+        ASSIGNING("assigning"),
+        RECONCILING("reconciling"),
+        STABLE("stable"),
+        DEAD("dead");
+
+        private final String name;
+
+        ConsumerGroupState(String name) {
+            this.name = name;
+        }
+
+        @Override
+        public String toString() {
+            return name;
+        }
+    }
+
+    /**
+     * The snapshot registry.
+     */
+    private final SnapshotRegistry snapshotRegistry;
+
+    /**
+     * The group id.
+     */
+    private final String groupId;
+
+    /**
+     * The group state.
+     */
+    private final TimelineObject<ConsumerGroupState> state;
+
+    /**
+     * The group epoch. The epoch is incremented whenever the subscriptions
+     * are updated and it will trigger the computation of a new assignment
+     * for the group.
+     */
+    private final TimelineInteger groupEpoch;
+
+    /**
+     * The group members.
+     */
+    private final TimelineHashMap<String, ConsumerGroupMember> members;
+
+    /**
+     * The metadata of the subscribed topics.
+     */
+    private final TimelineHashMap<String, TopicMetadata> subscribedTopicMetadata;
+
+    /**
+     * The assignment epoch. An assignment epoch smaller than the group epoch means
+     * that a new assignment is required. The assignment epoch is updated when a new
+     * assignment is installed.
+     */
+    private final TimelineInteger assignmentEpoch;
+
+    /**
+     * The target assignment.
+     */
+    private final TimelineHashMap<String, ConsumerGroupMemberAssignment> assignments;
+
+    /**
+     * The current partition epoch maps each topic-partitions to their current epoch where
+     * the epoch is the epoch of their owners. When a member revokes a partition, it removes
+     * itself from this map. When a member gets a partition, it adds itself to this map.
+     */
+    private final TimelineHashMap<Uuid, TimelineHashMap<Integer, Integer>> currentPartitionEpoch;
+
+    public ConsumerGroup(
+        SnapshotRegistry snapshotRegistry,
+        String groupId
+    ) {
+        Objects.requireNonNull(snapshotRegistry);
+        Objects.requireNonNull(groupId);
+
+        this.snapshotRegistry = snapshotRegistry;
+        this.groupId = groupId;
+        this.state = new TimelineObject<>(snapshotRegistry, ConsumerGroupState.EMPTY);
+        this.groupEpoch = new TimelineInteger(snapshotRegistry);
+        this.members = new TimelineHashMap<>(snapshotRegistry, 0);
+        this.subscribedTopicMetadata = new TimelineHashMap<>(snapshotRegistry, 0);
+        this.assignmentEpoch = new TimelineInteger(snapshotRegistry);
+        this.assignments = new TimelineHashMap<>(snapshotRegistry, 0);
+        this.currentPartitionEpoch = new TimelineHashMap<>(snapshotRegistry, 0);
+    }
+
+    /**
+     * The type of this group.
+     *
+     * @return The group type (Consumer).
+     */
+    @Override
+    public GroupType type() {
+        return GroupType.CONSUMER;
+    }
+
+    /**
+     * The state of this group.
+     *
+     * @return The current state as a String.
+     */
+    @Override
+    public String stateAsString() {
+        return state.get().toString();
+    }
+
+    /**
+     * The group id.
+     *
+     * @return The group id.
+     */
+    @Override
+    public String groupId() {
+        return groupId;
+    }
+
+    /**
+     * The state of this group.
+     *
+     * @return The current state.
+     */
+    public ConsumerGroupState state() {
+        return state.get();
+    }
+
+    /**
+     * Returns the current group epoch.
+     *
+     * @return The group epoch.
+     */
+    public int groupEpoch() {
+        return groupEpoch.get();
+    }
+
+    /**
+     * Sets the group epoch.
+     *
+     * @param groupEpoch The new group epoch.
+     */
+    public void setGroupEpoch(int groupEpoch) {
+        this.groupEpoch.set(groupEpoch);
+        maybeUpdateGroupState();
+    }
+
+    /**
+     * Returns the current assignment epoch.
+     *
+     * @return The current assignment epoch.
+     */
+    public int assignmentEpoch() {
+        return assignmentEpoch.get();
+    }
+
+    /**
+     * Sets the assignment epoch.
+     *
+     * @param assignmentEpoch The new assignment epoch.
+     */
+    public void setAssignmentEpoch(int assignmentEpoch) {
+        this.assignmentEpoch.set(assignmentEpoch);
+        maybeUpdateGroupState();
+    }
+
+    /**
+     * Gets or creates a member.
+     *
+     * @param memberId          The member id.
+     * @param createIfNotExists Booleans indicating whether the member must be
+     *                          created if it does not exist.
+     *
+     * @return A ConsumerGroupMember.
+     */
+    public ConsumerGroupMember getOrMaybeCreateMember(
+        String memberId,
+        boolean createIfNotExists
+    ) {
+        ConsumerGroupMember member = members.get(memberId);
+        if (member == null) {
+            if (!createIfNotExists) {
+                throw new UnknownMemberIdException(String.format("Member %s is not a member of group %s.",
+                    memberId, groupId));
+            }
+            member = new ConsumerGroupMember.Builder(memberId).build();

Review Comment:
   Should the new member creation be logged?



##########
group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java:
##########
@@ -0,0 +1,860 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.kafka.coordinator.group;
+
+import org.apache.kafka.common.Uuid;
+import org.apache.kafka.common.errors.FencedMemberEpochException;
+import org.apache.kafka.common.errors.GroupIdNotFoundException;
+import org.apache.kafka.common.errors.GroupMaxSizeReachedException;
+import org.apache.kafka.common.errors.InvalidRequestException;
+import org.apache.kafka.common.errors.NotCoordinatorException;
+import org.apache.kafka.common.errors.UnsupportedAssignorException;
+import org.apache.kafka.common.message.ConsumerGroupHeartbeatRequestData;
+import org.apache.kafka.common.message.ConsumerGroupHeartbeatResponseData;
+import org.apache.kafka.common.requests.RequestContext;
+import org.apache.kafka.common.utils.LogContext;
+import org.apache.kafka.coordinator.group.assignor.PartitionAssignor;
+import org.apache.kafka.coordinator.group.consumer.ConsumerGroup;
+import org.apache.kafka.coordinator.group.consumer.ConsumerGroupMember;
+import org.apache.kafka.coordinator.group.consumer.ConsumerGroupMemberAssignment;
+import org.apache.kafka.coordinator.group.consumer.CurrentAssignmentBuilder;
+import org.apache.kafka.coordinator.group.consumer.TargetAssignmentBuilder;
+import org.apache.kafka.coordinator.group.consumer.TopicMetadata;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupCurrentMemberAssignmentKey;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupCurrentMemberAssignmentValue;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupMemberMetadataKey;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupMemberMetadataValue;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupMetadataKey;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupMetadataValue;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupPartitionMetadataKey;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupPartitionMetadataValue;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupTargetAssignmentMemberKey;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupTargetAssignmentMemberValue;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupTargetAssignmentMetadataKey;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupTargetAssignmentMetadataValue;
+import org.apache.kafka.image.TopicsImage;
+import org.apache.kafka.timeline.SnapshotRegistry;
+import org.apache.kafka.timeline.TimelineHashMap;
+import org.apache.kafka.timeline.TimelineHashSet;
+import org.slf4j.Logger;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.OptionalInt;
+import java.util.Set;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+
+import static org.apache.kafka.coordinator.group.RecordHelpers.newCurrentAssignmentRecord;
+import static org.apache.kafka.coordinator.group.RecordHelpers.newCurrentAssignmentTombstoneRecord;
+import static org.apache.kafka.coordinator.group.RecordHelpers.newGroupEpochRecord;
+import static org.apache.kafka.coordinator.group.RecordHelpers.newGroupSubscriptionMetadataRecord;
+import static org.apache.kafka.coordinator.group.RecordHelpers.newMemberSubscriptionRecord;
+import static org.apache.kafka.coordinator.group.RecordHelpers.newMemberSubscriptionTombstoneRecord;
+import static org.apache.kafka.coordinator.group.RecordHelpers.newTargetAssignmentTombstoneRecord;
+
+/**
+ * The GroupMetadataManager manages the metadata of all generic and consumer groups. It holds
+ * the hard and the soft state of the groups. This class has two kinds of methods:
+ * 1) The request handlers which handle the requests and generate a response and records to
+ *    mutate the hard state. Those records will be written by the runtime and applied to the
+ *    hard stay via the replay methods.
+ * 2) The replay methods which apply records to the hard state. Those are used in the request
+ *    handling as well as during the initial loading of the records from the partitions.
+ */
+public class GroupMetadataManager {
+
+    public static class Builder {
+        private LogContext logContext = null;
+        private SnapshotRegistry snapshotRegistry = null;
+        private List<PartitionAssignor> assignors = null;
+        private TopicsImage topicsImage = null;
+        private int consumerGroupMaxSize = Integer.MAX_VALUE;
+        private int consumerGroupHeartbeatIntervalMs = 5000;
+
+        Builder withLogContext(LogContext logContext) {
+            this.logContext = logContext;
+            return this;
+        }
+
+        Builder withSnapshotRegistry(SnapshotRegistry snapshotRegistry) {
+            this.snapshotRegistry = snapshotRegistry;
+            return this;
+        }
+
+        Builder withAssignors(List<PartitionAssignor> assignors) {
+            this.assignors = assignors;
+            return this;
+        }
+
+        Builder withConsumerGroupMaxSize(int consumerGroupMaxSize) {
+            this.consumerGroupMaxSize = consumerGroupMaxSize;
+            return this;
+        }
+
+        Builder withConsumerGroupHeartbeatInterval(int consumerGroupHeartbeatIntervalMs) {
+            this.consumerGroupHeartbeatIntervalMs = consumerGroupHeartbeatIntervalMs;
+            return this;
+        }
+
+        Builder withTopicsImage(TopicsImage topicsImage) {
+            this.topicsImage = topicsImage;
+            return this;
+        }
+
+        GroupMetadataManager build() {
+            if (logContext == null) logContext = new LogContext();
+            if (snapshotRegistry == null) snapshotRegistry = new SnapshotRegistry(logContext);
+            if (topicsImage == null) topicsImage = TopicsImage.EMPTY;
+
+            if (assignors == null || assignors.isEmpty()) {
+                throw new IllegalStateException("Assignors must be set before building.");
+            }
+
+            return new GroupMetadataManager(
+                snapshotRegistry,
+                logContext,
+                assignors,
+                topicsImage,
+                consumerGroupMaxSize,
+                consumerGroupHeartbeatIntervalMs
+            );
+        }
+    }
+
+    /**
+     * The logger.
+     */
+    private final Logger log;
+
+    /**
+     * The snapshot registry.
+     */
+    private final SnapshotRegistry snapshotRegistry;
+
+    /**
+     * The list of supported assignors.
+     */
+    private final Map<String, PartitionAssignor> assignors;
+
+    /**
+     * The default assignor used.
+     */
+    private final PartitionAssignor defaultAssignor;
+
+    /**
+     * The generic and consumer groups keyed by their name.
+     */
+    private final TimelineHashMap<String, Group> groups;
+
+    /**
+     * The generic and consumer groups keyed by their subscribed topics.
+     */
+    private final TimelineHashMap<String, TimelineHashSet<Group>> groupsByTopicName;
+
+    /**
+     * The maximum number of members allowed in a single consumer group.
+     */
+    private final int consumerGroupMaxSize;
+
+    /**
+     * The heartbeat interval for consumer groups.
+     */
+    private final int consumerGroupHeartbeatIntervalMs;
+
+    /**
+     * The topics metadata (or image).
+     */
+    private TopicsImage topicsImage;
+
+    private GroupMetadataManager(
+        SnapshotRegistry snapshotRegistry,
+        LogContext logContext,
+        List<PartitionAssignor> assignors,
+        TopicsImage topicsImage,
+        int consumerGroupMaxSize,
+        int consumerGroupHeartbeatIntervalMs
+    ) {
+        this.log = logContext.logger(GroupMetadataManager.class);
+        this.snapshotRegistry = snapshotRegistry;
+        this.topicsImage = topicsImage;
+        this.assignors = assignors.stream().collect(Collectors.toMap(PartitionAssignor::name, Function.identity()));
+        this.defaultAssignor = assignors.get(0);
+        this.groups = new TimelineHashMap<>(snapshotRegistry, 0);
+        this.groupsByTopicName = new TimelineHashMap<>(snapshotRegistry, 0);
+        this.consumerGroupMaxSize = consumerGroupMaxSize;
+        this.consumerGroupHeartbeatIntervalMs = consumerGroupHeartbeatIntervalMs;
+    }
+
+    /**
+     * Gets or maybe creates a consumer group.
+     *
+     * @param groupId           The group id.
+     * @param createIfNotExists A boolean indicating whether the group should be
+     *                          created if it does not exist.
+     *
+     * @return A ConsumerGroup.
+     * @throws GroupIdNotFoundException if the group does not exist and createIfNotExists is false or
+     *                                  if the group is not a consumer group.
+     */
+    // Package private for testing.
+    ConsumerGroup getOrMaybeCreateConsumerGroup(
+        String groupId,
+        boolean createIfNotExists
+    ) throws GroupIdNotFoundException {
+        Group group = groups.get(groupId);
+
+        if (group == null && !createIfNotExists) {
+            throw new GroupIdNotFoundException(String.format("Consumer group %s not found.", groupId));
+        }
+
+        if (group == null) {
+            ConsumerGroup consumerGroup = new ConsumerGroup(snapshotRegistry, groupId);
+            groups.put(groupId, consumerGroup);
+            return consumerGroup;
+        } else {
+            if (group.type() == Group.GroupType.CONSUMER) {
+                return (ConsumerGroup) group;
+            } else {
+                // We don't support upgrading/downgrading between protocols at the moment so
+                // we throw an exception if a group exists with the wrong type.
+                throw new GroupIdNotFoundException(String.format("Group %s is not a consumer group.", groupId));
+            }
+        }
+    }
+
+    /**
+     * Removes the group.
+     *
+     * @param groupId The group id.
+     *
+     * @return The Group removed.
+     */
+    private Group removeGroup(
+        String groupId
+    ) {
+        return groups.remove(groupId);
+    }
+
+    /**
+     * Validates the request.
+     *
+     * @param request The request to validate.
+     *
+     * @throws InvalidRequestException if the request is not valid.
+     * @throws UnsupportedAssignorException if the assignor is not supported.
+     */
+    private void throwIfConsumerGroupHeartbeatRequestIsInvalid(
+        ConsumerGroupHeartbeatRequestData request
+    ) throws InvalidRequestException, UnsupportedAssignorException {
+        if (request.groupId().isEmpty()) {
+            throw new InvalidRequestException("GroupId can't be empty.");
+        }
+
+        if (request.memberEpoch() > 0 || request.memberEpoch() == -1) {
+            if (request.memberId().isEmpty()) {
+                throw new InvalidRequestException("MemberId can't be empty.");
+            }
+            if (request.instanceId() != null) {
+                throw new InvalidRequestException("InstanceId should only be provided in first request.");
+            }
+            if (request.rackId() != null) {
+                throw new InvalidRequestException("RackId should only be provided in first request.");
+            }
+        } else if (request.memberEpoch() == 0) {
+            if (request.rebalanceTimeoutMs() == -1) {
+                throw new InvalidRequestException("RebalanceTimeoutMs must in first request.");
+            }
+            if (request.topicPartitions() == null || !request.topicPartitions().isEmpty()) {
+                throw new InvalidRequestException("TopicPartitions must be empty when (re-)joining.");
+            }
+            if (request.subscribedTopicNames() == null || request.subscribedTopicNames().isEmpty()) {
+                throw new InvalidRequestException("SubscribedTopicNames must be set in first request.");
+            }
+            if (request.serverAssignor() != null && !assignors.containsKey(request.serverAssignor())) {
+                throw new UnsupportedAssignorException("ServerAssignor " + request.serverAssignor()
+                    + " is not supported. Supported assignors: " + String.join(", ", assignors.keySet())
+                    + ".");
+            }
+        } else {
+            throw new InvalidRequestException("MemberEpoch is invalid.");
+        }
+
+        if (request.subscribedTopicRegex() != null) {
+            throw new InvalidRequestException("SubscribedTopicRegex is not supported yet.");
+        }
+
+        if (request.clientAssignors() != null) {
+            // TODO We need to remove them from the request.
+            throw new InvalidRequestException("Client side assignors are not supported yet.");
+        }
+    }
+
+    /**
+     * Verifies that the partitions currently owned by the member (the ones set in the
+     * request) matches the ones that the member should own. It matches if the client
+     * has a least of subset of them.
+     *
+     * @param ownedTopicPartitions  The partitions provided by the client in the request.
+     * @param target                The partitions that they client should have.
+     *
+     * @return A boolean indicating whether the owned partitions are a subset of not.
+     */
+    private boolean isSubset(
+        List<ConsumerGroupHeartbeatRequestData.TopicPartitions> ownedTopicPartitions,
+        Map<Uuid, Set<Integer>> target
+    ) {
+        if (ownedTopicPartitions == null) return false;
+
+        for (ConsumerGroupHeartbeatRequestData.TopicPartitions topicPartitions : ownedTopicPartitions) {
+            Set<Integer> partitions = target.get(topicPartitions.topicId());
+            if (partitions == null) return false;
+            for (Integer partitionId : topicPartitions.partitions()) {
+                if (!partitions.contains(partitionId)) return false;
+            }
+        }
+
+        return true;
+    }
+
+    /**
+     * Checks whether the consumer group can accept a new member or not based on the
+     * max group side defined.
+     *
+     * @param group     The consumer group.
+     * @param memberId  The member id.
+     *
+     * @throws GroupMaxSizeReachedException if the maximum capacity has been reached.
+     */
+    private void throwIfConsumerGroupIsFull(
+        ConsumerGroup group,
+        String memberId
+    ) throws GroupMaxSizeReachedException {
+        // If the consumer group has reached its maximum capacity, the member is rejected if it is not
+        // already a member of the consumer group.
+        if (group.numMembers() >= consumerGroupMaxSize && (memberId.isEmpty() || !group.hasMember(memberId))) {
+            throw new GroupMaxSizeReachedException("The consumer group has reached its maximum capacity of "
+                + consumerGroupMaxSize + " members.");
+        }
+    }
+
+    /**
+     * Validates the member epoch provided in the heartbeat request.
+     *
+     * @param member                The consumer group member.
+     * @param memberEpoch           The member epoch.
+     * @param ownedTopicPartitions  The owned partitions.
+     *
+     * @throws NotCoordinatorException if the provided epoch is ahead of the epoch known
+     *                                 by this coordinator. This suggests that the member
+     *                                 got a higher epoch from another coordinator.
+     * @throws FencedMemberEpochException if the provided epoch is behind the epoch known
+     *                                    by this coordinator.
+     */
+    private void throwIfMemberEpochIsInvalid(
+        ConsumerGroupMember member,
+        int memberEpoch,
+        List<ConsumerGroupHeartbeatRequestData.TopicPartitions> ownedTopicPartitions
+    ) {
+        if (memberEpoch > member.memberEpoch()) {
+            // The member has likely got a bump from another coordinator and this coordinator
+            // is stale. Return NOT_COORDINATOR to force the member to refresh its coordinator.
+            throw new NotCoordinatorException("The consumer group member has got a larger member "
+                + "epoch (" + memberEpoch + ") than the one known by this group coordinator ("
+                + member.memberEpoch() + ").");
+        } else if (memberEpoch < member.memberEpoch()) {
+            // If the member comes with the previous epoch and has a subset of the current assignment partitions,
+            // we accept it because the response with the bumped epoch may have been lost.
+            if (memberEpoch != member.previousMemberEpoch() || !isSubset(ownedTopicPartitions, member.assigned())) {
+                throw new FencedMemberEpochException("The consumer group member has an old member "
+                    + "epoch. The member must abandon all its partitions and rejoin.");
+            }
+        }
+    }
+
+    private ConsumerGroupHeartbeatResponseData.Assignment createResponseAssignment(
+        ConsumerGroupMember member
+    ) {
+        ConsumerGroupHeartbeatResponseData.Assignment assignment = new ConsumerGroupHeartbeatResponseData.Assignment()
+            .setAssignedTopicPartitions(fromAssignmentMap(member.assigned()));
+
+        if (member.state() == ConsumerGroupMember.MemberState.ASSIGNING) {
+            assignment.setPendingTopicPartitions(fromAssignmentMap(member.assigning()));
+        }
+
+        return assignment;
+    }
+
+    private List<ConsumerGroupHeartbeatResponseData.TopicPartitions> fromAssignmentMap(
+        Map<Uuid, Set<Integer>> assignment
+    ) {
+        return assignment.entrySet().stream()
+            .map(keyValue -> new ConsumerGroupHeartbeatResponseData.TopicPartitions()
+                .setTopicId(keyValue.getKey())
+                .setPartitions(new ArrayList<>(keyValue.getValue())))
+            .collect(Collectors.toList());
+    }
+
+    private OptionalInt ofSentinel(int value) {
+        return value != -1 ? OptionalInt.of(value) : OptionalInt.empty();
+    }
+
+    /**
+     * Handles a regular heartbeat from a consumer group member.
+     *
+     * @param groupId               The group id from the request.
+     * @param memberId              The member id from the request.
+     * @param memberEpoch           The member epoch from the request.
+     * @param instanceId            The instance id from the request or null.
+     * @param rackId                The rack id from the request or null.
+     * @param rebalanceTimeoutMs    The rebalance timeout from the request or -1.
+     * @param clientId              The client id.
+     * @param clientHost            The client host.
+     * @param subscribedTopicNames  The list of subscribed topic names from the request
+     *                              of null.
+     * @param subscribedTopicRegex  The regular expression based subscription from the
+     *                              request or null.
+     * @param assignorName          The assignor name from the request or null.
+     * @param ownedTopicPartitions  The list of owned partitions from the request or null.
+     *
+     * @return A Result containing the ConsumerGroupHeartbeat response and
+     *         a list of records to update the state machine.
+     */
+    private Result<ConsumerGroupHeartbeatResponseData> consumerGroupHeartbeat(
+        String groupId,
+        String memberId,
+        int memberEpoch,
+        String instanceId,
+        String rackId,
+        int rebalanceTimeoutMs,
+        String clientId,
+        String clientHost,
+        List<String> subscribedTopicNames,
+        String subscribedTopicRegex,
+        String assignorName,
+        List<ConsumerGroupHeartbeatRequestData.TopicPartitions> ownedTopicPartitions
+    ) {
+        List<Record> records = new ArrayList<>();
+        boolean createIfNotExists = memberEpoch == 0;
+
+        ConsumerGroup group = getOrMaybeCreateConsumerGroup(groupId, createIfNotExists);
+        throwIfConsumerGroupIsFull(group, memberId);
+
+        if (memberId.isEmpty()) memberId = Uuid.randomUuid().toString();
+        ConsumerGroupMember member = group.getOrMaybeCreateMember(memberId, createIfNotExists);
+        throwIfMemberEpochIsInvalid(member, memberEpoch, ownedTopicPartitions);
+
+        if (memberEpoch == 0) {
+            log.info("[GroupId " + groupId + "] Member " + memberId + " re-joins the consumer group.");
+        }
+
+        // Update the subscription part of the member if we received new values. If the member has
+        // changed, we write it to the log. If the subscribed topics have changed, we also recompute
+        // the subscription metadata.
+        int groupEpoch = group.groupEpoch();
+        Map<String, TopicMetadata> subscriptionMetadata = group.subscriptionMetadata();
+        ConsumerGroupMember updatedMember = new ConsumerGroupMember.Builder(member)
+            .maybeUpdateInstanceId(Optional.ofNullable(instanceId))
+            .maybeUpdateRackId(Optional.ofNullable(rackId))
+            .maybeUpdateRebalanceTimeoutMs(ofSentinel(rebalanceTimeoutMs))
+            .maybeUpdateServerAssignorName(Optional.ofNullable(assignorName))
+            .maybeUpdateSubscribedTopicNames(Optional.ofNullable(subscribedTopicNames))
+            .maybeUpdateSubscribedTopicRegex(Optional.ofNullable(subscribedTopicRegex))
+            .setClientId(clientId)
+            .setClientHost(clientHost)
+            .build();
+
+        if (!updatedMember.equals(member)) {
+            records.add(newMemberSubscriptionRecord(groupId, updatedMember));
+
+            if (!updatedMember.subscribedTopicNames().equals(member.subscribedTopicNames())) {
+                log.info("[GroupId " + groupId + "] Member " + memberId + " updated its subscribed topics to: " +
+                    updatedMember.subscribedTopicNames());
+
+                subscriptionMetadata = group.computeSubscriptionMetadata(
+                    updatedMember.memberId(),
+                    updatedMember.subscribedTopicNames(),
+                    topicsImage
+                );
+
+                if (!subscriptionMetadata.equals(group.subscriptionMetadata())) {
+                    log.info("[GroupId " + groupId + "] Computed new subscription metadata: "
+                        + subscriptionMetadata + ".");
+                    records.add(newGroupSubscriptionMetadataRecord(groupId, subscriptionMetadata));
+                }
+
+                groupEpoch += 1;
+                records.add(newGroupEpochRecord(groupId, groupEpoch));
+
+                log.info("[GroupId " + groupId + "] Bumped group epoch to " + groupEpoch + ".");
+            }
+
+            member = updatedMember;
+        }
+
+        // Update target assignment if needed. If the new target has any changes, we write the
+        // changes to the log.
+        int targetAssignmentEpoch = group.assignmentEpoch();
+        ConsumerGroupMemberAssignment targetAssignment = group.targetAssignment(memberId);
+        if (groupEpoch > targetAssignmentEpoch) {
+            String preferredServerAssignor = group.preferredServerAssignor(
+                member.memberId(),
+                member.serverAssignorName()
+            ).orElse(defaultAssignor.name());
+
+            TargetAssignmentBuilder.TargetAssignmentResult assignmentResult =
+                new TargetAssignmentBuilder(groupId, groupEpoch, assignors.get(preferredServerAssignor))
+                    .withMembers(group.members())
+                    .withSubscriptionMetadata(subscriptionMetadata)
+                    .withTargetAssignments(group.targetAssignments())
+                    .withUpdatedMember(member.memberId(), member)
+                    .build();
+
+            log.info("[GroupId " + groupId + "] Computed a new target assignment for epoch " + groupEpoch + ": "
+                + assignmentResult.assignments() + ".");
+
+            records.addAll(assignmentResult.records());
+            targetAssignment = assignmentResult.assignments().get(member.memberId());
+            targetAssignmentEpoch = groupEpoch;
+        }
+
+        // If the member is stable and its next epoch matches the current target epoch
+        // of the assignment, we can skip this reconciliation.
+        boolean assignmentUpdated = false;
+        if (member.state() != ConsumerGroupMember.MemberState.STABLE
+            || member.nextMemberEpoch() != targetAssignmentEpoch) {
+            updatedMember = new CurrentAssignmentBuilder(member)
+                .withTargetAssignment(targetAssignmentEpoch, targetAssignment)
+                .withCurrentPartitionEpoch(group::currentPartitionEpoch)
+                .withOwnedTopicPartitions(ownedTopicPartitions)
+                .build();
+
+            // Checking the reference is enough here because a new instance
+            // is created only the state has changed.
+            if (updatedMember != member) {
+                assignmentUpdated = true;
+                records.add(newCurrentAssignmentRecord(groupId, updatedMember));
+
+                log.info("[GroupId " + groupId + "] Member " + memberId + " transitioned from " +
+                    member.currentAssignmentSummary() + " to " + updatedMember.currentAssignmentSummary() + ".");
+
+                // TODO(dajac) Starts or restarts the timer for the revocation timeout.
+
+                member = updatedMember;
+            }
+        }
+
+        // TODO(dajac) Starts or restarts the timer for the session timeout.
+
+        ConsumerGroupHeartbeatResponseData response = new ConsumerGroupHeartbeatResponseData()
+            .setMemberId(member.memberId())
+            .setMemberEpoch(member.memberEpoch())
+            .setHeartbeatIntervalMs(consumerGroupHeartbeatIntervalMs);
+
+        if (ownedTopicPartitions != null || memberEpoch == 0 || assignmentUpdated) {
+            response.setAssignment(createResponseAssignment(member));
+        }
+
+        return new Result<>(records, response);
+    }
+
+    /**
+     * Handles leave request from a consumer group member.
+     * @param groupId       The group id from the request.
+     * @param memberId      The member id from the request.
+     *
+     * @return A Result containing the ConsumerGroupHeartbeat response and
+     *         a list of records to update the state machine.
+     */
+    private Result<ConsumerGroupHeartbeatResponseData> consumerGroupLeave(
+        String groupId,
+        String memberId
+    ) {
+        List<Record> records = new ArrayList<>();
+
+        ConsumerGroup group = getOrMaybeCreateConsumerGroup(groupId, false);

Review Comment:
   Just for my understanding, does the consumer group protocol allows the use case where the coordinator receives a `LeaveGroup` but the consumer group and/or member is not registered with the coordinator? Can it happen in case of heartbeat request loss, an invalid client request, or after a coordinator change?
   
   If it is the case the group did not exist, do we need to compute a new assignment?



##########
group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java:
##########
@@ -0,0 +1,860 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.kafka.coordinator.group;
+
+import org.apache.kafka.common.Uuid;
+import org.apache.kafka.common.errors.FencedMemberEpochException;
+import org.apache.kafka.common.errors.GroupIdNotFoundException;
+import org.apache.kafka.common.errors.GroupMaxSizeReachedException;
+import org.apache.kafka.common.errors.InvalidRequestException;
+import org.apache.kafka.common.errors.NotCoordinatorException;
+import org.apache.kafka.common.errors.UnsupportedAssignorException;
+import org.apache.kafka.common.message.ConsumerGroupHeartbeatRequestData;
+import org.apache.kafka.common.message.ConsumerGroupHeartbeatResponseData;
+import org.apache.kafka.common.requests.RequestContext;
+import org.apache.kafka.common.utils.LogContext;
+import org.apache.kafka.coordinator.group.assignor.PartitionAssignor;
+import org.apache.kafka.coordinator.group.consumer.ConsumerGroup;
+import org.apache.kafka.coordinator.group.consumer.ConsumerGroupMember;
+import org.apache.kafka.coordinator.group.consumer.ConsumerGroupMemberAssignment;
+import org.apache.kafka.coordinator.group.consumer.CurrentAssignmentBuilder;
+import org.apache.kafka.coordinator.group.consumer.TargetAssignmentBuilder;
+import org.apache.kafka.coordinator.group.consumer.TopicMetadata;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupCurrentMemberAssignmentKey;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupCurrentMemberAssignmentValue;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupMemberMetadataKey;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupMemberMetadataValue;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupMetadataKey;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupMetadataValue;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupPartitionMetadataKey;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupPartitionMetadataValue;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupTargetAssignmentMemberKey;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupTargetAssignmentMemberValue;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupTargetAssignmentMetadataKey;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupTargetAssignmentMetadataValue;
+import org.apache.kafka.image.TopicsImage;
+import org.apache.kafka.timeline.SnapshotRegistry;
+import org.apache.kafka.timeline.TimelineHashMap;
+import org.apache.kafka.timeline.TimelineHashSet;
+import org.slf4j.Logger;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.OptionalInt;
+import java.util.Set;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+
+import static org.apache.kafka.coordinator.group.RecordHelpers.newCurrentAssignmentRecord;
+import static org.apache.kafka.coordinator.group.RecordHelpers.newCurrentAssignmentTombstoneRecord;
+import static org.apache.kafka.coordinator.group.RecordHelpers.newGroupEpochRecord;
+import static org.apache.kafka.coordinator.group.RecordHelpers.newGroupSubscriptionMetadataRecord;
+import static org.apache.kafka.coordinator.group.RecordHelpers.newMemberSubscriptionRecord;
+import static org.apache.kafka.coordinator.group.RecordHelpers.newMemberSubscriptionTombstoneRecord;
+import static org.apache.kafka.coordinator.group.RecordHelpers.newTargetAssignmentTombstoneRecord;
+
+/**
+ * The GroupMetadataManager manages the metadata of all generic and consumer groups. It holds
+ * the hard and the soft state of the groups. This class has two kinds of methods:
+ * 1) The request handlers which handle the requests and generate a response and records to
+ *    mutate the hard state. Those records will be written by the runtime and applied to the
+ *    hard stay via the replay methods.
+ * 2) The replay methods which apply records to the hard state. Those are used in the request
+ *    handling as well as during the initial loading of the records from the partitions.
+ */
+public class GroupMetadataManager {
+
+    public static class Builder {
+        private LogContext logContext = null;
+        private SnapshotRegistry snapshotRegistry = null;
+        private List<PartitionAssignor> assignors = null;
+        private TopicsImage topicsImage = null;
+        private int consumerGroupMaxSize = Integer.MAX_VALUE;
+        private int consumerGroupHeartbeatIntervalMs = 5000;
+
+        Builder withLogContext(LogContext logContext) {
+            this.logContext = logContext;
+            return this;
+        }
+
+        Builder withSnapshotRegistry(SnapshotRegistry snapshotRegistry) {
+            this.snapshotRegistry = snapshotRegistry;
+            return this;
+        }
+
+        Builder withAssignors(List<PartitionAssignor> assignors) {
+            this.assignors = assignors;
+            return this;
+        }
+
+        Builder withConsumerGroupMaxSize(int consumerGroupMaxSize) {
+            this.consumerGroupMaxSize = consumerGroupMaxSize;
+            return this;
+        }
+
+        Builder withConsumerGroupHeartbeatInterval(int consumerGroupHeartbeatIntervalMs) {
+            this.consumerGroupHeartbeatIntervalMs = consumerGroupHeartbeatIntervalMs;
+            return this;
+        }
+
+        Builder withTopicsImage(TopicsImage topicsImage) {
+            this.topicsImage = topicsImage;
+            return this;
+        }
+
+        GroupMetadataManager build() {
+            if (logContext == null) logContext = new LogContext();
+            if (snapshotRegistry == null) snapshotRegistry = new SnapshotRegistry(logContext);
+            if (topicsImage == null) topicsImage = TopicsImage.EMPTY;
+
+            if (assignors == null || assignors.isEmpty()) {
+                throw new IllegalStateException("Assignors must be set before building.");
+            }
+
+            return new GroupMetadataManager(
+                snapshotRegistry,
+                logContext,
+                assignors,
+                topicsImage,
+                consumerGroupMaxSize,
+                consumerGroupHeartbeatIntervalMs
+            );
+        }
+    }
+
+    /**
+     * The logger.
+     */
+    private final Logger log;
+
+    /**
+     * The snapshot registry.
+     */
+    private final SnapshotRegistry snapshotRegistry;
+
+    /**
+     * The list of supported assignors.
+     */
+    private final Map<String, PartitionAssignor> assignors;
+
+    /**
+     * The default assignor used.
+     */
+    private final PartitionAssignor defaultAssignor;
+
+    /**
+     * The generic and consumer groups keyed by their name.
+     */
+    private final TimelineHashMap<String, Group> groups;
+
+    /**
+     * The generic and consumer groups keyed by their subscribed topics.
+     */
+    private final TimelineHashMap<String, TimelineHashSet<Group>> groupsByTopicName;
+
+    /**
+     * The maximum number of members allowed in a single consumer group.
+     */
+    private final int consumerGroupMaxSize;
+
+    /**
+     * The heartbeat interval for consumer groups.
+     */
+    private final int consumerGroupHeartbeatIntervalMs;
+
+    /**
+     * The topics metadata (or image).
+     */
+    private TopicsImage topicsImage;
+
+    private GroupMetadataManager(
+        SnapshotRegistry snapshotRegistry,
+        LogContext logContext,
+        List<PartitionAssignor> assignors,
+        TopicsImage topicsImage,
+        int consumerGroupMaxSize,
+        int consumerGroupHeartbeatIntervalMs
+    ) {
+        this.log = logContext.logger(GroupMetadataManager.class);
+        this.snapshotRegistry = snapshotRegistry;
+        this.topicsImage = topicsImage;
+        this.assignors = assignors.stream().collect(Collectors.toMap(PartitionAssignor::name, Function.identity()));
+        this.defaultAssignor = assignors.get(0);
+        this.groups = new TimelineHashMap<>(snapshotRegistry, 0);
+        this.groupsByTopicName = new TimelineHashMap<>(snapshotRegistry, 0);
+        this.consumerGroupMaxSize = consumerGroupMaxSize;
+        this.consumerGroupHeartbeatIntervalMs = consumerGroupHeartbeatIntervalMs;
+    }
+
+    /**
+     * Gets or maybe creates a consumer group.
+     *
+     * @param groupId           The group id.
+     * @param createIfNotExists A boolean indicating whether the group should be
+     *                          created if it does not exist.
+     *
+     * @return A ConsumerGroup.
+     * @throws GroupIdNotFoundException if the group does not exist and createIfNotExists is false or
+     *                                  if the group is not a consumer group.
+     */
+    // Package private for testing.
+    ConsumerGroup getOrMaybeCreateConsumerGroup(
+        String groupId,
+        boolean createIfNotExists
+    ) throws GroupIdNotFoundException {
+        Group group = groups.get(groupId);
+
+        if (group == null && !createIfNotExists) {
+            throw new GroupIdNotFoundException(String.format("Consumer group %s not found.", groupId));
+        }
+
+        if (group == null) {
+            ConsumerGroup consumerGroup = new ConsumerGroup(snapshotRegistry, groupId);
+            groups.put(groupId, consumerGroup);
+            return consumerGroup;
+        } else {
+            if (group.type() == Group.GroupType.CONSUMER) {
+                return (ConsumerGroup) group;
+            } else {
+                // We don't support upgrading/downgrading between protocols at the moment so
+                // we throw an exception if a group exists with the wrong type.
+                throw new GroupIdNotFoundException(String.format("Group %s is not a consumer group.", groupId));
+            }
+        }
+    }
+
+    /**
+     * Removes the group.
+     *
+     * @param groupId The group id.
+     *
+     * @return The Group removed.
+     */
+    private Group removeGroup(
+        String groupId
+    ) {
+        return groups.remove(groupId);
+    }
+
+    /**
+     * Validates the request.
+     *
+     * @param request The request to validate.
+     *
+     * @throws InvalidRequestException if the request is not valid.
+     * @throws UnsupportedAssignorException if the assignor is not supported.
+     */
+    private void throwIfConsumerGroupHeartbeatRequestIsInvalid(
+        ConsumerGroupHeartbeatRequestData request
+    ) throws InvalidRequestException, UnsupportedAssignorException {
+        if (request.groupId().isEmpty()) {
+            throw new InvalidRequestException("GroupId can't be empty.");
+        }
+
+        if (request.memberEpoch() > 0 || request.memberEpoch() == -1) {
+            if (request.memberId().isEmpty()) {
+                throw new InvalidRequestException("MemberId can't be empty.");
+            }
+            if (request.instanceId() != null) {
+                throw new InvalidRequestException("InstanceId should only be provided in first request.");
+            }
+            if (request.rackId() != null) {
+                throw new InvalidRequestException("RackId should only be provided in first request.");
+            }
+        } else if (request.memberEpoch() == 0) {
+            if (request.rebalanceTimeoutMs() == -1) {
+                throw new InvalidRequestException("RebalanceTimeoutMs must in first request.");
+            }
+            if (request.topicPartitions() == null || !request.topicPartitions().isEmpty()) {
+                throw new InvalidRequestException("TopicPartitions must be empty when (re-)joining.");
+            }
+            if (request.subscribedTopicNames() == null || request.subscribedTopicNames().isEmpty()) {
+                throw new InvalidRequestException("SubscribedTopicNames must be set in first request.");
+            }
+            if (request.serverAssignor() != null && !assignors.containsKey(request.serverAssignor())) {
+                throw new UnsupportedAssignorException("ServerAssignor " + request.serverAssignor()
+                    + " is not supported. Supported assignors: " + String.join(", ", assignors.keySet())
+                    + ".");
+            }
+        } else {
+            throw new InvalidRequestException("MemberEpoch is invalid.");
+        }
+
+        if (request.subscribedTopicRegex() != null) {
+            throw new InvalidRequestException("SubscribedTopicRegex is not supported yet.");
+        }
+
+        if (request.clientAssignors() != null) {
+            // TODO We need to remove them from the request.
+            throw new InvalidRequestException("Client side assignors are not supported yet.");
+        }
+    }
+
+    /**
+     * Verifies that the partitions currently owned by the member (the ones set in the
+     * request) matches the ones that the member should own. It matches if the client
+     * has a least of subset of them.
+     *
+     * @param ownedTopicPartitions  The partitions provided by the client in the request.
+     * @param target                The partitions that they client should have.
+     *
+     * @return A boolean indicating whether the owned partitions are a subset of not.
+     */
+    private boolean isSubset(
+        List<ConsumerGroupHeartbeatRequestData.TopicPartitions> ownedTopicPartitions,
+        Map<Uuid, Set<Integer>> target
+    ) {
+        if (ownedTopicPartitions == null) return false;
+
+        for (ConsumerGroupHeartbeatRequestData.TopicPartitions topicPartitions : ownedTopicPartitions) {
+            Set<Integer> partitions = target.get(topicPartitions.topicId());
+            if (partitions == null) return false;
+            for (Integer partitionId : topicPartitions.partitions()) {
+                if (!partitions.contains(partitionId)) return false;
+            }
+        }
+
+        return true;
+    }
+
+    /**
+     * Checks whether the consumer group can accept a new member or not based on the
+     * max group side defined.
+     *
+     * @param group     The consumer group.
+     * @param memberId  The member id.
+     *
+     * @throws GroupMaxSizeReachedException if the maximum capacity has been reached.
+     */
+    private void throwIfConsumerGroupIsFull(
+        ConsumerGroup group,
+        String memberId
+    ) throws GroupMaxSizeReachedException {
+        // If the consumer group has reached its maximum capacity, the member is rejected if it is not
+        // already a member of the consumer group.
+        if (group.numMembers() >= consumerGroupMaxSize && (memberId.isEmpty() || !group.hasMember(memberId))) {
+            throw new GroupMaxSizeReachedException("The consumer group has reached its maximum capacity of "
+                + consumerGroupMaxSize + " members.");
+        }
+    }
+
+    /**
+     * Validates the member epoch provided in the heartbeat request.
+     *
+     * @param member                The consumer group member.
+     * @param memberEpoch           The member epoch.
+     * @param ownedTopicPartitions  The owned partitions.
+     *
+     * @throws NotCoordinatorException if the provided epoch is ahead of the epoch known
+     *                                 by this coordinator. This suggests that the member
+     *                                 got a higher epoch from another coordinator.
+     * @throws FencedMemberEpochException if the provided epoch is behind the epoch known
+     *                                    by this coordinator.
+     */
+    private void throwIfMemberEpochIsInvalid(
+        ConsumerGroupMember member,
+        int memberEpoch,
+        List<ConsumerGroupHeartbeatRequestData.TopicPartitions> ownedTopicPartitions
+    ) {
+        if (memberEpoch > member.memberEpoch()) {
+            // The member has likely got a bump from another coordinator and this coordinator
+            // is stale. Return NOT_COORDINATOR to force the member to refresh its coordinator.
+            throw new NotCoordinatorException("The consumer group member has got a larger member "
+                + "epoch (" + memberEpoch + ") than the one known by this group coordinator ("
+                + member.memberEpoch() + ").");
+        } else if (memberEpoch < member.memberEpoch()) {
+            // If the member comes with the previous epoch and has a subset of the current assignment partitions,
+            // we accept it because the response with the bumped epoch may have been lost.
+            if (memberEpoch != member.previousMemberEpoch() || !isSubset(ownedTopicPartitions, member.assigned())) {
+                throw new FencedMemberEpochException("The consumer group member has an old member "
+                    + "epoch. The member must abandon all its partitions and rejoin.");
+            }
+        }
+    }
+
+    private ConsumerGroupHeartbeatResponseData.Assignment createResponseAssignment(
+        ConsumerGroupMember member
+    ) {
+        ConsumerGroupHeartbeatResponseData.Assignment assignment = new ConsumerGroupHeartbeatResponseData.Assignment()
+            .setAssignedTopicPartitions(fromAssignmentMap(member.assigned()));
+
+        if (member.state() == ConsumerGroupMember.MemberState.ASSIGNING) {
+            assignment.setPendingTopicPartitions(fromAssignmentMap(member.assigning()));
+        }
+
+        return assignment;
+    }
+
+    private List<ConsumerGroupHeartbeatResponseData.TopicPartitions> fromAssignmentMap(
+        Map<Uuid, Set<Integer>> assignment
+    ) {
+        return assignment.entrySet().stream()
+            .map(keyValue -> new ConsumerGroupHeartbeatResponseData.TopicPartitions()
+                .setTopicId(keyValue.getKey())
+                .setPartitions(new ArrayList<>(keyValue.getValue())))
+            .collect(Collectors.toList());
+    }
+
+    private OptionalInt ofSentinel(int value) {
+        return value != -1 ? OptionalInt.of(value) : OptionalInt.empty();
+    }
+
+    /**
+     * Handles a regular heartbeat from a consumer group member.
+     *
+     * @param groupId               The group id from the request.
+     * @param memberId              The member id from the request.
+     * @param memberEpoch           The member epoch from the request.
+     * @param instanceId            The instance id from the request or null.
+     * @param rackId                The rack id from the request or null.
+     * @param rebalanceTimeoutMs    The rebalance timeout from the request or -1.
+     * @param clientId              The client id.
+     * @param clientHost            The client host.
+     * @param subscribedTopicNames  The list of subscribed topic names from the request
+     *                              of null.
+     * @param subscribedTopicRegex  The regular expression based subscription from the
+     *                              request or null.
+     * @param assignorName          The assignor name from the request or null.
+     * @param ownedTopicPartitions  The list of owned partitions from the request or null.
+     *
+     * @return A Result containing the ConsumerGroupHeartbeat response and
+     *         a list of records to update the state machine.
+     */
+    private Result<ConsumerGroupHeartbeatResponseData> consumerGroupHeartbeat(
+        String groupId,

Review Comment:
   nit: maybe a class could encapsulate all these parameters? Or maybe a DTO could be re-used?



##########
group-coordinator/src/main/java/org/apache/kafka/coordinator/group/consumer/ConsumerGroupMember.java:
##########
@@ -0,0 +1,555 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.kafka.coordinator.group.consumer;
+
+import org.apache.kafka.common.Uuid;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupCurrentMemberAssignmentValue;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupMemberMetadataValue;
+
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.OptionalInt;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+/**
+ * ConsumerGroupMember contains all the information related to a member
+ * within a consumer group. This class is immutable.
+ */
+public class ConsumerGroupMember {
+    /**
+     * A builder allowing to create a new member or update an
+     * existing one.
+     */
+    public static class Builder {
+        private final String memberId;
+        private int memberEpoch = 0;
+        private int previousMemberEpoch = -1;
+        private int nextMemberEpoch = 0;
+        private String instanceId = null;
+        private String rackId = null;
+        private int rebalanceTimeoutMs = -1;
+        private String clientId = "";
+        private String clientHost = "";
+        private List<String> subscribedTopicNames = Collections.emptyList();
+        private String subscribedTopicRegex = "";
+        private String serverAssignorName = null;
+        private List<ClientAssignor> clientAssignors = Collections.emptyList();
+        private Map<Uuid, Set<Integer>> assigned = Collections.emptyMap();
+        private Map<Uuid, Set<Integer>> revoking = Collections.emptyMap();
+        private Map<Uuid, Set<Integer>> assigning = Collections.emptyMap();
+
+        public Builder(String memberId) {
+            this.memberId = Objects.requireNonNull(memberId);
+        }
+
+        public Builder(ConsumerGroupMember member) {
+            Objects.requireNonNull(member);
+
+            this.memberId = member.memberId;
+            this.memberEpoch = member.memberEpoch;
+            this.previousMemberEpoch = member.previousMemberEpoch;
+            this.nextMemberEpoch = member.nextMemberEpoch;
+            this.instanceId = member.instanceId;
+            this.rackId = member.rackId;
+            this.rebalanceTimeoutMs = member.rebalanceTimeoutMs;
+            this.clientId = member.clientId;
+            this.clientHost = member.clientHost;
+            this.subscribedTopicNames = member.subscribedTopicNames;
+            this.subscribedTopicRegex = member.subscribedTopicRegex;
+            this.serverAssignorName = member.serverAssignorName;
+            this.clientAssignors = member.clientAssignors;
+            this.assigned = member.assigned;
+            this.revoking = member.revoking;
+            this.assigning = member.assigning;
+        }
+
+        public Builder setMemberEpoch(int memberEpoch) {
+            this.memberEpoch = memberEpoch;
+            return this;
+        }
+
+        public Builder setPreviousMemberEpoch(int previousMemberEpoch) {
+            this.previousMemberEpoch = previousMemberEpoch;
+            return this;
+        }
+
+        public Builder setNextMemberEpoch(int nextMemberEpoch) {
+            this.nextMemberEpoch = nextMemberEpoch;
+            return this;
+        }
+
+        public Builder setInstanceId(String instanceId) {
+            this.instanceId = instanceId;
+            return this;
+        }
+
+        public Builder maybeUpdateInstanceId(Optional<String> instanceId) {
+            this.instanceId = instanceId.orElse(this.instanceId);
+            return this;
+        }
+
+        public Builder setRackId(String rackId) {
+            this.rackId = rackId;
+            return this;
+        }
+
+        public Builder maybeUpdateRackId(Optional<String> rackId) {
+            this.rackId = rackId.orElse(this.rackId);
+            return this;
+        }
+
+        public Builder setRebalanceTimeoutMs(int rebalanceTimeoutMs) {
+            this.rebalanceTimeoutMs = rebalanceTimeoutMs;
+            return this;
+        }
+
+        public Builder maybeUpdateRebalanceTimeoutMs(OptionalInt rebalanceTimeoutMs) {
+            this.rebalanceTimeoutMs = rebalanceTimeoutMs.orElse(this.rebalanceTimeoutMs);
+            return this;
+        }
+
+        public Builder setClientId(String clientId) {
+            this.clientId = clientId;
+            return this;
+        }
+
+        public Builder setClientHost(String clientHost) {
+            this.clientHost = clientHost;
+            return this;
+        }
+
+        public Builder setSubscribedTopicNames(List<String> subscribedTopicNames) {
+            this.subscribedTopicNames = subscribedTopicNames;
+            this.subscribedTopicNames.sort(Comparator.naturalOrder());
+            return this;
+        }
+
+        public Builder maybeUpdateSubscribedTopicNames(Optional<List<String>> subscribedTopicNames) {
+            this.subscribedTopicNames = subscribedTopicNames.orElse(this.subscribedTopicNames);
+            this.subscribedTopicNames.sort(Comparator.naturalOrder());
+            return this;
+        }
+
+        public Builder setSubscribedTopicRegex(String subscribedTopicRegex) {
+            this.subscribedTopicRegex = subscribedTopicRegex;
+            return this;
+        }
+
+        public Builder maybeUpdateSubscribedTopicRegex(Optional<String> subscribedTopicRegex) {
+            this.subscribedTopicRegex = subscribedTopicRegex.orElse(this.subscribedTopicRegex);
+            return this;
+        }
+
+        public Builder setServerAssignorName(String serverAssignorName) {
+            this.serverAssignorName = serverAssignorName;
+            return this;
+        }
+
+        public Builder maybeUpdateServerAssignorName(Optional<String> serverAssignorName) {
+            this.serverAssignorName = serverAssignorName.orElse(this.serverAssignorName);
+            return this;
+        }
+
+        public Builder setClientAssignors(List<ClientAssignor> clientAssignors) {
+            this.clientAssignors = clientAssignors;
+            return this;
+        }
+
+        public Builder maybeUpdateClientAssignors(Optional<List<ClientAssignor>> clientAssignors) {
+            this.clientAssignors = clientAssignors.orElse(this.clientAssignors);
+            return this;
+        }
+
+        public Builder setAssigned(Map<Uuid, Set<Integer>> assigned) {
+            this.assigned = assigned;
+            return this;
+        }
+
+        public Builder setRevoking(Map<Uuid, Set<Integer>> revoking) {
+            this.revoking = revoking;
+            return this;
+        }
+
+        public Builder setAssigning(Map<Uuid, Set<Integer>> assigning) {
+            this.assigning = assigning;
+            return this;
+        }
+
+        public Builder mergeWith(ConsumerGroupMemberMetadataValue record) {
+            setInstanceId(record.instanceId());
+            setRackId(record.rackId());
+            setClientId(record.clientId());
+            setClientHost(record.clientHost());
+            setSubscribedTopicNames(record.subscribedTopicNames());
+            setSubscribedTopicRegex(record.subscribedTopicRegex());
+            setRebalanceTimeoutMs(record.rebalanceTimeoutMs());
+            setServerAssignorName(record.serverAssignor());
+            setClientAssignors(record.assignors().stream()
+                .map(ClientAssignor::fromRecord)
+                .collect(Collectors.toList()));
+            return this;
+        }
+
+        public Builder mergeWith(ConsumerGroupCurrentMemberAssignmentValue record) {
+            setMemberEpoch(record.memberEpoch());
+            setPreviousMemberEpoch(record.previousMemberEpoch());
+            setNextMemberEpoch(record.targetMemberEpoch());
+            setAssigned(assignmentFromTopicPartitions(record.assigned()));
+            setRevoking(assignmentFromTopicPartitions(record.revoking()));
+            setAssigning(assignmentFromTopicPartitions(record.assigning()));
+            return this;
+        }
+
+        private Map<Uuid, Set<Integer>> assignmentFromTopicPartitions(
+            List<ConsumerGroupCurrentMemberAssignmentValue.TopicPartitions> topicPartitionsList
+        ) {
+            return topicPartitionsList.stream().collect(Collectors.toMap(
+                ConsumerGroupCurrentMemberAssignmentValue.TopicPartitions::topicId,
+                topicPartitions -> Collections.unmodifiableSet(new HashSet<>(topicPartitions.partitions()))));
+        }
+
+        public ConsumerGroupMember build() {
+            MemberState state;
+            if (!revoking.isEmpty()) {
+                state = MemberState.REVOKING;
+            } else if (!assigning.isEmpty()) {
+                state = MemberState.ASSIGNING;
+            } else {
+                state = MemberState.STABLE;
+            }
+
+            return new ConsumerGroupMember(
+                memberId,
+                memberEpoch,
+                previousMemberEpoch,
+                nextMemberEpoch,
+                instanceId,
+                rackId,
+                rebalanceTimeoutMs,
+                clientId,
+                clientHost,
+                subscribedTopicNames,
+                subscribedTopicRegex,
+                serverAssignorName,
+                clientAssignors,
+                state,
+                assigned,
+                revoking,
+                assigning
+            );
+        }
+    }
+
+    public enum MemberState {
+        REVOKING("revoking"),
+        ASSIGNING("assigning"),
+        STABLE("stable");
+
+        private final String name;
+
+        MemberState(String name) {
+            this.name = name;
+        }
+
+        @Override
+        public String toString() {
+            return name;
+        }
+    }
+
+    /**
+     * The member id.
+     */
+    private final String memberId;
+
+    /**
+     * The current member epoch.
+     */
+    private final int memberEpoch;
+
+    /**
+     * The previous member epoch.
+     */
+    private final int previousMemberEpoch;
+
+    /**
+     * The next member epoch. This corresponds to the target
+     * assignment epoch used to compute the current assigned,
+     * revoking and assigning partitions.
+     */
+    private final int nextMemberEpoch;
+
+    /**
+     * The instance id provided by the member.
+     */
+    private final String instanceId;
+
+    /**
+     * The rack id provided by the member.
+     */
+    private final String rackId;
+
+    /**
+     * The rebalance timeout provided by the member.
+     */
+    private final int rebalanceTimeoutMs;
+
+    /**
+     * The client id reported by the member.
+     */
+    private final String clientId;
+
+    /**
+     * The host reported by the member.
+     */
+    private final String clientHost;
+
+    /**
+     * The list of subscriptions (topic names) configured by the member.
+     */
+    private final List<String> subscribedTopicNames;
+
+    /**
+     * The subscription pattern configured by the member,
+     */
+    private final String subscribedTopicRegex;
+
+    /**
+     * The server side assignor selected by the member.
+     */
+    private final String serverAssignorName;
+
+    /**
+     * The states of the client side assignors of the member.
+     */
+    private final List<ClientAssignor> clientAssignors;
+
+    /**
+     * The member state.
+     */
+    private final MemberState state;
+
+    /**
+     * The partitions assigned to this member.
+     */
+    private final Map<Uuid, Set<Integer>> assigned;
+
+    /**
+     * The partitions being revoked by this member.
+     */
+    private final Map<Uuid, Set<Integer>> revoking;
+
+    /**
+     * The partitions waiting to be assigned to this
+     * member. They will be assigned when they are
+     * released by their previous owners.
+     */
+    private final Map<Uuid, Set<Integer>> assigning;
+
+    private ConsumerGroupMember(
+        String memberId,
+        int memberEpoch,
+        int previousMemberEpoch,
+        int nextMemberEpoch,
+        String instanceId,
+        String rackId,
+        int rebalanceTimeoutMs,
+        String clientId,
+        String clientHost,
+        List<String> subscribedTopicNames,
+        String subscribedTopicRegex,
+        String serverAssignorName,
+        List<ClientAssignor> clientAssignors,
+        MemberState state,
+        Map<Uuid, Set<Integer>> assigned,
+        Map<Uuid, Set<Integer>> revoking,
+        Map<Uuid, Set<Integer>> assigning
+    ) {
+        this.memberId = memberId;

Review Comment:
   nit: use a `Builder` instance as constructor parameter?



##########
group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java:
##########
@@ -0,0 +1,860 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.kafka.coordinator.group;
+
+import org.apache.kafka.common.Uuid;
+import org.apache.kafka.common.errors.FencedMemberEpochException;
+import org.apache.kafka.common.errors.GroupIdNotFoundException;
+import org.apache.kafka.common.errors.GroupMaxSizeReachedException;
+import org.apache.kafka.common.errors.InvalidRequestException;
+import org.apache.kafka.common.errors.NotCoordinatorException;
+import org.apache.kafka.common.errors.UnsupportedAssignorException;
+import org.apache.kafka.common.message.ConsumerGroupHeartbeatRequestData;
+import org.apache.kafka.common.message.ConsumerGroupHeartbeatResponseData;
+import org.apache.kafka.common.requests.RequestContext;
+import org.apache.kafka.common.utils.LogContext;
+import org.apache.kafka.coordinator.group.assignor.PartitionAssignor;
+import org.apache.kafka.coordinator.group.consumer.ConsumerGroup;
+import org.apache.kafka.coordinator.group.consumer.ConsumerGroupMember;
+import org.apache.kafka.coordinator.group.consumer.ConsumerGroupMemberAssignment;
+import org.apache.kafka.coordinator.group.consumer.CurrentAssignmentBuilder;
+import org.apache.kafka.coordinator.group.consumer.TargetAssignmentBuilder;
+import org.apache.kafka.coordinator.group.consumer.TopicMetadata;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupCurrentMemberAssignmentKey;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupCurrentMemberAssignmentValue;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupMemberMetadataKey;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupMemberMetadataValue;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupMetadataKey;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupMetadataValue;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupPartitionMetadataKey;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupPartitionMetadataValue;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupTargetAssignmentMemberKey;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupTargetAssignmentMemberValue;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupTargetAssignmentMetadataKey;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupTargetAssignmentMetadataValue;
+import org.apache.kafka.image.TopicsImage;
+import org.apache.kafka.timeline.SnapshotRegistry;
+import org.apache.kafka.timeline.TimelineHashMap;
+import org.apache.kafka.timeline.TimelineHashSet;
+import org.slf4j.Logger;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.OptionalInt;
+import java.util.Set;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+
+import static org.apache.kafka.coordinator.group.RecordHelpers.newCurrentAssignmentRecord;
+import static org.apache.kafka.coordinator.group.RecordHelpers.newCurrentAssignmentTombstoneRecord;
+import static org.apache.kafka.coordinator.group.RecordHelpers.newGroupEpochRecord;
+import static org.apache.kafka.coordinator.group.RecordHelpers.newGroupSubscriptionMetadataRecord;
+import static org.apache.kafka.coordinator.group.RecordHelpers.newMemberSubscriptionRecord;
+import static org.apache.kafka.coordinator.group.RecordHelpers.newMemberSubscriptionTombstoneRecord;
+import static org.apache.kafka.coordinator.group.RecordHelpers.newTargetAssignmentTombstoneRecord;
+
+/**
+ * The GroupMetadataManager manages the metadata of all generic and consumer groups. It holds
+ * the hard and the soft state of the groups. This class has two kinds of methods:
+ * 1) The request handlers which handle the requests and generate a response and records to
+ *    mutate the hard state. Those records will be written by the runtime and applied to the
+ *    hard stay via the replay methods.
+ * 2) The replay methods which apply records to the hard state. Those are used in the request
+ *    handling as well as during the initial loading of the records from the partitions.
+ */
+public class GroupMetadataManager {
+
+    public static class Builder {
+        private LogContext logContext = null;
+        private SnapshotRegistry snapshotRegistry = null;
+        private List<PartitionAssignor> assignors = null;
+        private TopicsImage topicsImage = null;
+        private int consumerGroupMaxSize = Integer.MAX_VALUE;
+        private int consumerGroupHeartbeatIntervalMs = 5000;
+
+        Builder withLogContext(LogContext logContext) {
+            this.logContext = logContext;
+            return this;
+        }
+
+        Builder withSnapshotRegistry(SnapshotRegistry snapshotRegistry) {
+            this.snapshotRegistry = snapshotRegistry;
+            return this;
+        }
+
+        Builder withAssignors(List<PartitionAssignor> assignors) {
+            this.assignors = assignors;
+            return this;
+        }
+
+        Builder withConsumerGroupMaxSize(int consumerGroupMaxSize) {
+            this.consumerGroupMaxSize = consumerGroupMaxSize;
+            return this;
+        }
+
+        Builder withConsumerGroupHeartbeatInterval(int consumerGroupHeartbeatIntervalMs) {
+            this.consumerGroupHeartbeatIntervalMs = consumerGroupHeartbeatIntervalMs;
+            return this;
+        }
+
+        Builder withTopicsImage(TopicsImage topicsImage) {
+            this.topicsImage = topicsImage;
+            return this;
+        }
+
+        GroupMetadataManager build() {
+            if (logContext == null) logContext = new LogContext();
+            if (snapshotRegistry == null) snapshotRegistry = new SnapshotRegistry(logContext);
+            if (topicsImage == null) topicsImage = TopicsImage.EMPTY;
+
+            if (assignors == null || assignors.isEmpty()) {
+                throw new IllegalStateException("Assignors must be set before building.");
+            }
+
+            return new GroupMetadataManager(
+                snapshotRegistry,
+                logContext,
+                assignors,
+                topicsImage,
+                consumerGroupMaxSize,
+                consumerGroupHeartbeatIntervalMs
+            );
+        }
+    }
+
+    /**
+     * The logger.
+     */
+    private final Logger log;
+
+    /**
+     * The snapshot registry.
+     */
+    private final SnapshotRegistry snapshotRegistry;
+
+    /**
+     * The list of supported assignors.
+     */
+    private final Map<String, PartitionAssignor> assignors;
+
+    /**
+     * The default assignor used.
+     */
+    private final PartitionAssignor defaultAssignor;
+
+    /**
+     * The generic and consumer groups keyed by their name.
+     */
+    private final TimelineHashMap<String, Group> groups;
+
+    /**
+     * The generic and consumer groups keyed by their subscribed topics.
+     */
+    private final TimelineHashMap<String, TimelineHashSet<Group>> groupsByTopicName;
+
+    /**
+     * The maximum number of members allowed in a single consumer group.
+     */
+    private final int consumerGroupMaxSize;
+
+    /**
+     * The heartbeat interval for consumer groups.
+     */
+    private final int consumerGroupHeartbeatIntervalMs;
+
+    /**
+     * The topics metadata (or image).
+     */
+    private TopicsImage topicsImage;
+
+    private GroupMetadataManager(
+        SnapshotRegistry snapshotRegistry,
+        LogContext logContext,
+        List<PartitionAssignor> assignors,
+        TopicsImage topicsImage,
+        int consumerGroupMaxSize,
+        int consumerGroupHeartbeatIntervalMs
+    ) {
+        this.log = logContext.logger(GroupMetadataManager.class);
+        this.snapshotRegistry = snapshotRegistry;
+        this.topicsImage = topicsImage;
+        this.assignors = assignors.stream().collect(Collectors.toMap(PartitionAssignor::name, Function.identity()));
+        this.defaultAssignor = assignors.get(0);
+        this.groups = new TimelineHashMap<>(snapshotRegistry, 0);
+        this.groupsByTopicName = new TimelineHashMap<>(snapshotRegistry, 0);
+        this.consumerGroupMaxSize = consumerGroupMaxSize;
+        this.consumerGroupHeartbeatIntervalMs = consumerGroupHeartbeatIntervalMs;
+    }
+
+    /**
+     * Gets or maybe creates a consumer group.
+     *
+     * @param groupId           The group id.
+     * @param createIfNotExists A boolean indicating whether the group should be
+     *                          created if it does not exist.
+     *
+     * @return A ConsumerGroup.
+     * @throws GroupIdNotFoundException if the group does not exist and createIfNotExists is false or
+     *                                  if the group is not a consumer group.
+     */
+    // Package private for testing.
+    ConsumerGroup getOrMaybeCreateConsumerGroup(
+        String groupId,
+        boolean createIfNotExists
+    ) throws GroupIdNotFoundException {
+        Group group = groups.get(groupId);
+
+        if (group == null && !createIfNotExists) {
+            throw new GroupIdNotFoundException(String.format("Consumer group %s not found.", groupId));
+        }
+
+        if (group == null) {
+            ConsumerGroup consumerGroup = new ConsumerGroup(snapshotRegistry, groupId);

Review Comment:
   Should the consumer group creation be logged?



##########
group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java:
##########
@@ -0,0 +1,860 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.kafka.coordinator.group;
+
+import org.apache.kafka.common.Uuid;
+import org.apache.kafka.common.errors.FencedMemberEpochException;
+import org.apache.kafka.common.errors.GroupIdNotFoundException;
+import org.apache.kafka.common.errors.GroupMaxSizeReachedException;
+import org.apache.kafka.common.errors.InvalidRequestException;
+import org.apache.kafka.common.errors.NotCoordinatorException;
+import org.apache.kafka.common.errors.UnsupportedAssignorException;
+import org.apache.kafka.common.message.ConsumerGroupHeartbeatRequestData;
+import org.apache.kafka.common.message.ConsumerGroupHeartbeatResponseData;
+import org.apache.kafka.common.requests.RequestContext;
+import org.apache.kafka.common.utils.LogContext;
+import org.apache.kafka.coordinator.group.assignor.PartitionAssignor;
+import org.apache.kafka.coordinator.group.consumer.ConsumerGroup;
+import org.apache.kafka.coordinator.group.consumer.ConsumerGroupMember;
+import org.apache.kafka.coordinator.group.consumer.ConsumerGroupMemberAssignment;
+import org.apache.kafka.coordinator.group.consumer.CurrentAssignmentBuilder;
+import org.apache.kafka.coordinator.group.consumer.TargetAssignmentBuilder;
+import org.apache.kafka.coordinator.group.consumer.TopicMetadata;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupCurrentMemberAssignmentKey;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupCurrentMemberAssignmentValue;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupMemberMetadataKey;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupMemberMetadataValue;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupMetadataKey;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupMetadataValue;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupPartitionMetadataKey;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupPartitionMetadataValue;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupTargetAssignmentMemberKey;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupTargetAssignmentMemberValue;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupTargetAssignmentMetadataKey;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupTargetAssignmentMetadataValue;
+import org.apache.kafka.image.TopicsImage;
+import org.apache.kafka.timeline.SnapshotRegistry;
+import org.apache.kafka.timeline.TimelineHashMap;
+import org.apache.kafka.timeline.TimelineHashSet;
+import org.slf4j.Logger;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.OptionalInt;
+import java.util.Set;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+
+import static org.apache.kafka.coordinator.group.RecordHelpers.newCurrentAssignmentRecord;
+import static org.apache.kafka.coordinator.group.RecordHelpers.newCurrentAssignmentTombstoneRecord;
+import static org.apache.kafka.coordinator.group.RecordHelpers.newGroupEpochRecord;
+import static org.apache.kafka.coordinator.group.RecordHelpers.newGroupSubscriptionMetadataRecord;
+import static org.apache.kafka.coordinator.group.RecordHelpers.newMemberSubscriptionRecord;
+import static org.apache.kafka.coordinator.group.RecordHelpers.newMemberSubscriptionTombstoneRecord;
+import static org.apache.kafka.coordinator.group.RecordHelpers.newTargetAssignmentTombstoneRecord;
+
+/**
+ * The GroupMetadataManager manages the metadata of all generic and consumer groups. It holds
+ * the hard and the soft state of the groups. This class has two kinds of methods:
+ * 1) The request handlers which handle the requests and generate a response and records to
+ *    mutate the hard state. Those records will be written by the runtime and applied to the
+ *    hard stay via the replay methods.
+ * 2) The replay methods which apply records to the hard state. Those are used in the request
+ *    handling as well as during the initial loading of the records from the partitions.
+ */
+public class GroupMetadataManager {
+
+    public static class Builder {
+        private LogContext logContext = null;
+        private SnapshotRegistry snapshotRegistry = null;
+        private List<PartitionAssignor> assignors = null;
+        private TopicsImage topicsImage = null;
+        private int consumerGroupMaxSize = Integer.MAX_VALUE;
+        private int consumerGroupHeartbeatIntervalMs = 5000;
+
+        Builder withLogContext(LogContext logContext) {
+            this.logContext = logContext;
+            return this;
+        }
+
+        Builder withSnapshotRegistry(SnapshotRegistry snapshotRegistry) {
+            this.snapshotRegistry = snapshotRegistry;
+            return this;
+        }
+
+        Builder withAssignors(List<PartitionAssignor> assignors) {
+            this.assignors = assignors;
+            return this;
+        }
+
+        Builder withConsumerGroupMaxSize(int consumerGroupMaxSize) {
+            this.consumerGroupMaxSize = consumerGroupMaxSize;
+            return this;
+        }
+
+        Builder withConsumerGroupHeartbeatInterval(int consumerGroupHeartbeatIntervalMs) {
+            this.consumerGroupHeartbeatIntervalMs = consumerGroupHeartbeatIntervalMs;
+            return this;
+        }
+
+        Builder withTopicsImage(TopicsImage topicsImage) {
+            this.topicsImage = topicsImage;
+            return this;
+        }
+
+        GroupMetadataManager build() {
+            if (logContext == null) logContext = new LogContext();
+            if (snapshotRegistry == null) snapshotRegistry = new SnapshotRegistry(logContext);
+            if (topicsImage == null) topicsImage = TopicsImage.EMPTY;
+
+            if (assignors == null || assignors.isEmpty()) {
+                throw new IllegalStateException("Assignors must be set before building.");
+            }
+
+            return new GroupMetadataManager(
+                snapshotRegistry,
+                logContext,
+                assignors,
+                topicsImage,
+                consumerGroupMaxSize,
+                consumerGroupHeartbeatIntervalMs
+            );
+        }
+    }
+
+    /**
+     * The logger.
+     */
+    private final Logger log;
+
+    /**
+     * The snapshot registry.
+     */
+    private final SnapshotRegistry snapshotRegistry;
+
+    /**
+     * The list of supported assignors.
+     */
+    private final Map<String, PartitionAssignor> assignors;
+
+    /**
+     * The default assignor used.
+     */
+    private final PartitionAssignor defaultAssignor;
+
+    /**
+     * The generic and consumer groups keyed by their name.
+     */
+    private final TimelineHashMap<String, Group> groups;
+
+    /**
+     * The generic and consumer groups keyed by their subscribed topics.
+     */
+    private final TimelineHashMap<String, TimelineHashSet<Group>> groupsByTopicName;
+
+    /**
+     * The maximum number of members allowed in a single consumer group.
+     */
+    private final int consumerGroupMaxSize;
+
+    /**
+     * The heartbeat interval for consumer groups.
+     */
+    private final int consumerGroupHeartbeatIntervalMs;
+
+    /**
+     * The topics metadata (or image).
+     */
+    private TopicsImage topicsImage;
+
+    private GroupMetadataManager(
+        SnapshotRegistry snapshotRegistry,
+        LogContext logContext,
+        List<PartitionAssignor> assignors,
+        TopicsImage topicsImage,
+        int consumerGroupMaxSize,
+        int consumerGroupHeartbeatIntervalMs
+    ) {
+        this.log = logContext.logger(GroupMetadataManager.class);
+        this.snapshotRegistry = snapshotRegistry;
+        this.topicsImage = topicsImage;
+        this.assignors = assignors.stream().collect(Collectors.toMap(PartitionAssignor::name, Function.identity()));
+        this.defaultAssignor = assignors.get(0);
+        this.groups = new TimelineHashMap<>(snapshotRegistry, 0);
+        this.groupsByTopicName = new TimelineHashMap<>(snapshotRegistry, 0);
+        this.consumerGroupMaxSize = consumerGroupMaxSize;
+        this.consumerGroupHeartbeatIntervalMs = consumerGroupHeartbeatIntervalMs;
+    }
+
+    /**
+     * Gets or maybe creates a consumer group.
+     *
+     * @param groupId           The group id.
+     * @param createIfNotExists A boolean indicating whether the group should be
+     *                          created if it does not exist.
+     *
+     * @return A ConsumerGroup.
+     * @throws GroupIdNotFoundException if the group does not exist and createIfNotExists is false or
+     *                                  if the group is not a consumer group.
+     */
+    // Package private for testing.
+    ConsumerGroup getOrMaybeCreateConsumerGroup(
+        String groupId,
+        boolean createIfNotExists
+    ) throws GroupIdNotFoundException {
+        Group group = groups.get(groupId);
+
+        if (group == null && !createIfNotExists) {
+            throw new GroupIdNotFoundException(String.format("Consumer group %s not found.", groupId));
+        }
+
+        if (group == null) {
+            ConsumerGroup consumerGroup = new ConsumerGroup(snapshotRegistry, groupId);
+            groups.put(groupId, consumerGroup);
+            return consumerGroup;
+        } else {
+            if (group.type() == Group.GroupType.CONSUMER) {
+                return (ConsumerGroup) group;
+            } else {
+                // We don't support upgrading/downgrading between protocols at the moment so
+                // we throw an exception if a group exists with the wrong type.
+                throw new GroupIdNotFoundException(String.format("Group %s is not a consumer group.", groupId));
+            }
+        }
+    }
+
+    /**
+     * Removes the group.
+     *
+     * @param groupId The group id.
+     *
+     * @return The Group removed.
+     */
+    private Group removeGroup(
+        String groupId
+    ) {
+        return groups.remove(groupId);
+    }
+
+    /**
+     * Validates the request.
+     *
+     * @param request The request to validate.
+     *
+     * @throws InvalidRequestException if the request is not valid.
+     * @throws UnsupportedAssignorException if the assignor is not supported.
+     */
+    private void throwIfConsumerGroupHeartbeatRequestIsInvalid(
+        ConsumerGroupHeartbeatRequestData request
+    ) throws InvalidRequestException, UnsupportedAssignorException {
+        if (request.groupId().isEmpty()) {
+            throw new InvalidRequestException("GroupId can't be empty.");
+        }
+
+        if (request.memberEpoch() > 0 || request.memberEpoch() == -1) {
+            if (request.memberId().isEmpty()) {
+                throw new InvalidRequestException("MemberId can't be empty.");
+            }
+            if (request.instanceId() != null) {
+                throw new InvalidRequestException("InstanceId should only be provided in first request.");
+            }
+            if (request.rackId() != null) {
+                throw new InvalidRequestException("RackId should only be provided in first request.");
+            }
+        } else if (request.memberEpoch() == 0) {
+            if (request.rebalanceTimeoutMs() == -1) {
+                throw new InvalidRequestException("RebalanceTimeoutMs must in first request.");
+            }
+            if (request.topicPartitions() == null || !request.topicPartitions().isEmpty()) {
+                throw new InvalidRequestException("TopicPartitions must be empty when (re-)joining.");
+            }
+            if (request.subscribedTopicNames() == null || request.subscribedTopicNames().isEmpty()) {
+                throw new InvalidRequestException("SubscribedTopicNames must be set in first request.");
+            }
+            if (request.serverAssignor() != null && !assignors.containsKey(request.serverAssignor())) {
+                throw new UnsupportedAssignorException("ServerAssignor " + request.serverAssignor()
+                    + " is not supported. Supported assignors: " + String.join(", ", assignors.keySet())
+                    + ".");
+            }
+        } else {
+            throw new InvalidRequestException("MemberEpoch is invalid.");
+        }
+
+        if (request.subscribedTopicRegex() != null) {
+            throw new InvalidRequestException("SubscribedTopicRegex is not supported yet.");
+        }
+
+        if (request.clientAssignors() != null) {
+            // TODO We need to remove them from the request.
+            throw new InvalidRequestException("Client side assignors are not supported yet.");
+        }
+    }
+
+    /**
+     * Verifies that the partitions currently owned by the member (the ones set in the
+     * request) matches the ones that the member should own. It matches if the client
+     * has a least of subset of them.
+     *
+     * @param ownedTopicPartitions  The partitions provided by the client in the request.
+     * @param target                The partitions that they client should have.
+     *
+     * @return A boolean indicating whether the owned partitions are a subset of not.
+     */
+    private boolean isSubset(
+        List<ConsumerGroupHeartbeatRequestData.TopicPartitions> ownedTopicPartitions,
+        Map<Uuid, Set<Integer>> target
+    ) {
+        if (ownedTopicPartitions == null) return false;
+
+        for (ConsumerGroupHeartbeatRequestData.TopicPartitions topicPartitions : ownedTopicPartitions) {
+            Set<Integer> partitions = target.get(topicPartitions.topicId());
+            if (partitions == null) return false;
+            for (Integer partitionId : topicPartitions.partitions()) {
+                if (!partitions.contains(partitionId)) return false;
+            }
+        }
+
+        return true;
+    }
+
+    /**
+     * Checks whether the consumer group can accept a new member or not based on the
+     * max group side defined.
+     *
+     * @param group     The consumer group.
+     * @param memberId  The member id.
+     *
+     * @throws GroupMaxSizeReachedException if the maximum capacity has been reached.
+     */
+    private void throwIfConsumerGroupIsFull(
+        ConsumerGroup group,
+        String memberId
+    ) throws GroupMaxSizeReachedException {
+        // If the consumer group has reached its maximum capacity, the member is rejected if it is not
+        // already a member of the consumer group.
+        if (group.numMembers() >= consumerGroupMaxSize && (memberId.isEmpty() || !group.hasMember(memberId))) {
+            throw new GroupMaxSizeReachedException("The consumer group has reached its maximum capacity of "
+                + consumerGroupMaxSize + " members.");
+        }
+    }
+
+    /**
+     * Validates the member epoch provided in the heartbeat request.
+     *
+     * @param member                The consumer group member.
+     * @param memberEpoch           The member epoch.
+     * @param ownedTopicPartitions  The owned partitions.
+     *
+     * @throws NotCoordinatorException if the provided epoch is ahead of the epoch known
+     *                                 by this coordinator. This suggests that the member
+     *                                 got a higher epoch from another coordinator.
+     * @throws FencedMemberEpochException if the provided epoch is behind the epoch known
+     *                                    by this coordinator.
+     */
+    private void throwIfMemberEpochIsInvalid(
+        ConsumerGroupMember member,
+        int memberEpoch,
+        List<ConsumerGroupHeartbeatRequestData.TopicPartitions> ownedTopicPartitions
+    ) {
+        if (memberEpoch > member.memberEpoch()) {
+            // The member has likely got a bump from another coordinator and this coordinator
+            // is stale. Return NOT_COORDINATOR to force the member to refresh its coordinator.
+            throw new NotCoordinatorException("The consumer group member has got a larger member "
+                + "epoch (" + memberEpoch + ") than the one known by this group coordinator ("
+                + member.memberEpoch() + ").");
+        } else if (memberEpoch < member.memberEpoch()) {
+            // If the member comes with the previous epoch and has a subset of the current assignment partitions,
+            // we accept it because the response with the bumped epoch may have been lost.
+            if (memberEpoch != member.previousMemberEpoch() || !isSubset(ownedTopicPartitions, member.assigned())) {
+                throw new FencedMemberEpochException("The consumer group member has an old member "
+                    + "epoch. The member must abandon all its partitions and rejoin.");
+            }
+        }
+    }
+
+    private ConsumerGroupHeartbeatResponseData.Assignment createResponseAssignment(
+        ConsumerGroupMember member
+    ) {
+        ConsumerGroupHeartbeatResponseData.Assignment assignment = new ConsumerGroupHeartbeatResponseData.Assignment()
+            .setAssignedTopicPartitions(fromAssignmentMap(member.assigned()));
+
+        if (member.state() == ConsumerGroupMember.MemberState.ASSIGNING) {
+            assignment.setPendingTopicPartitions(fromAssignmentMap(member.assigning()));
+        }
+
+        return assignment;
+    }
+
+    private List<ConsumerGroupHeartbeatResponseData.TopicPartitions> fromAssignmentMap(
+        Map<Uuid, Set<Integer>> assignment
+    ) {
+        return assignment.entrySet().stream()
+            .map(keyValue -> new ConsumerGroupHeartbeatResponseData.TopicPartitions()
+                .setTopicId(keyValue.getKey())
+                .setPartitions(new ArrayList<>(keyValue.getValue())))
+            .collect(Collectors.toList());
+    }
+
+    private OptionalInt ofSentinel(int value) {
+        return value != -1 ? OptionalInt.of(value) : OptionalInt.empty();
+    }
+
+    /**
+     * Handles a regular heartbeat from a consumer group member.
+     *
+     * @param groupId               The group id from the request.
+     * @param memberId              The member id from the request.
+     * @param memberEpoch           The member epoch from the request.
+     * @param instanceId            The instance id from the request or null.
+     * @param rackId                The rack id from the request or null.
+     * @param rebalanceTimeoutMs    The rebalance timeout from the request or -1.
+     * @param clientId              The client id.
+     * @param clientHost            The client host.
+     * @param subscribedTopicNames  The list of subscribed topic names from the request
+     *                              of null.
+     * @param subscribedTopicRegex  The regular expression based subscription from the
+     *                              request or null.
+     * @param assignorName          The assignor name from the request or null.
+     * @param ownedTopicPartitions  The list of owned partitions from the request or null.
+     *
+     * @return A Result containing the ConsumerGroupHeartbeat response and
+     *         a list of records to update the state machine.
+     */
+    private Result<ConsumerGroupHeartbeatResponseData> consumerGroupHeartbeat(
+        String groupId,
+        String memberId,
+        int memberEpoch,
+        String instanceId,
+        String rackId,
+        int rebalanceTimeoutMs,
+        String clientId,
+        String clientHost,
+        List<String> subscribedTopicNames,
+        String subscribedTopicRegex,
+        String assignorName,
+        List<ConsumerGroupHeartbeatRequestData.TopicPartitions> ownedTopicPartitions
+    ) {
+        List<Record> records = new ArrayList<>();
+        boolean createIfNotExists = memberEpoch == 0;
+
+        ConsumerGroup group = getOrMaybeCreateConsumerGroup(groupId, createIfNotExists);
+        throwIfConsumerGroupIsFull(group, memberId);
+
+        if (memberId.isEmpty()) memberId = Uuid.randomUuid().toString();
+        ConsumerGroupMember member = group.getOrMaybeCreateMember(memberId, createIfNotExists);
+        throwIfMemberEpochIsInvalid(member, memberEpoch, ownedTopicPartitions);
+
+        if (memberEpoch == 0) {
+            log.info("[GroupId " + groupId + "] Member " + memberId + " re-joins the consumer group.");
+        }
+
+        // Update the subscription part of the member if we received new values. If the member has
+        // changed, we write it to the log. If the subscribed topics have changed, we also recompute
+        // the subscription metadata.
+        int groupEpoch = group.groupEpoch();
+        Map<String, TopicMetadata> subscriptionMetadata = group.subscriptionMetadata();
+        ConsumerGroupMember updatedMember = new ConsumerGroupMember.Builder(member)
+            .maybeUpdateInstanceId(Optional.ofNullable(instanceId))
+            .maybeUpdateRackId(Optional.ofNullable(rackId))
+            .maybeUpdateRebalanceTimeoutMs(ofSentinel(rebalanceTimeoutMs))
+            .maybeUpdateServerAssignorName(Optional.ofNullable(assignorName))
+            .maybeUpdateSubscribedTopicNames(Optional.ofNullable(subscribedTopicNames))
+            .maybeUpdateSubscribedTopicRegex(Optional.ofNullable(subscribedTopicRegex))
+            .setClientId(clientId)
+            .setClientHost(clientHost)
+            .build();
+
+        if (!updatedMember.equals(member)) {
+            records.add(newMemberSubscriptionRecord(groupId, updatedMember));
+
+            if (!updatedMember.subscribedTopicNames().equals(member.subscribedTopicNames())) {
+                log.info("[GroupId " + groupId + "] Member " + memberId + " updated its subscribed topics to: " +
+                    updatedMember.subscribedTopicNames());
+
+                subscriptionMetadata = group.computeSubscriptionMetadata(
+                    updatedMember.memberId(),
+                    updatedMember.subscribedTopicNames(),
+                    topicsImage
+                );
+
+                if (!subscriptionMetadata.equals(group.subscriptionMetadata())) {
+                    log.info("[GroupId " + groupId + "] Computed new subscription metadata: "
+                        + subscriptionMetadata + ".");
+                    records.add(newGroupSubscriptionMetadataRecord(groupId, subscriptionMetadata));
+                }
+
+                groupEpoch += 1;
+                records.add(newGroupEpochRecord(groupId, groupEpoch));
+
+                log.info("[GroupId " + groupId + "] Bumped group epoch to " + groupEpoch + ".");

Review Comment:
   nit: maybe this line and the one above could be merged (to avoid interleaving logs)?



##########
group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupMetadataManager.java:
##########
@@ -0,0 +1,860 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.kafka.coordinator.group;
+
+import org.apache.kafka.common.Uuid;
+import org.apache.kafka.common.errors.FencedMemberEpochException;
+import org.apache.kafka.common.errors.GroupIdNotFoundException;
+import org.apache.kafka.common.errors.GroupMaxSizeReachedException;
+import org.apache.kafka.common.errors.InvalidRequestException;
+import org.apache.kafka.common.errors.NotCoordinatorException;
+import org.apache.kafka.common.errors.UnsupportedAssignorException;
+import org.apache.kafka.common.message.ConsumerGroupHeartbeatRequestData;
+import org.apache.kafka.common.message.ConsumerGroupHeartbeatResponseData;
+import org.apache.kafka.common.requests.RequestContext;
+import org.apache.kafka.common.utils.LogContext;
+import org.apache.kafka.coordinator.group.assignor.PartitionAssignor;
+import org.apache.kafka.coordinator.group.consumer.ConsumerGroup;
+import org.apache.kafka.coordinator.group.consumer.ConsumerGroupMember;
+import org.apache.kafka.coordinator.group.consumer.ConsumerGroupMemberAssignment;
+import org.apache.kafka.coordinator.group.consumer.CurrentAssignmentBuilder;
+import org.apache.kafka.coordinator.group.consumer.TargetAssignmentBuilder;
+import org.apache.kafka.coordinator.group.consumer.TopicMetadata;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupCurrentMemberAssignmentKey;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupCurrentMemberAssignmentValue;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupMemberMetadataKey;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupMemberMetadataValue;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupMetadataKey;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupMetadataValue;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupPartitionMetadataKey;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupPartitionMetadataValue;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupTargetAssignmentMemberKey;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupTargetAssignmentMemberValue;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupTargetAssignmentMetadataKey;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupTargetAssignmentMetadataValue;
+import org.apache.kafka.image.TopicsImage;
+import org.apache.kafka.timeline.SnapshotRegistry;
+import org.apache.kafka.timeline.TimelineHashMap;
+import org.apache.kafka.timeline.TimelineHashSet;
+import org.slf4j.Logger;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.OptionalInt;
+import java.util.Set;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+
+import static org.apache.kafka.coordinator.group.RecordHelpers.newCurrentAssignmentRecord;
+import static org.apache.kafka.coordinator.group.RecordHelpers.newCurrentAssignmentTombstoneRecord;
+import static org.apache.kafka.coordinator.group.RecordHelpers.newGroupEpochRecord;
+import static org.apache.kafka.coordinator.group.RecordHelpers.newGroupSubscriptionMetadataRecord;
+import static org.apache.kafka.coordinator.group.RecordHelpers.newMemberSubscriptionRecord;
+import static org.apache.kafka.coordinator.group.RecordHelpers.newMemberSubscriptionTombstoneRecord;
+import static org.apache.kafka.coordinator.group.RecordHelpers.newTargetAssignmentTombstoneRecord;
+
+/**
+ * The GroupMetadataManager manages the metadata of all generic and consumer groups. It holds
+ * the hard and the soft state of the groups. This class has two kinds of methods:
+ * 1) The request handlers which handle the requests and generate a response and records to
+ *    mutate the hard state. Those records will be written by the runtime and applied to the
+ *    hard stay via the replay methods.
+ * 2) The replay methods which apply records to the hard state. Those are used in the request
+ *    handling as well as during the initial loading of the records from the partitions.
+ */
+public class GroupMetadataManager {
+
+    public static class Builder {
+        private LogContext logContext = null;
+        private SnapshotRegistry snapshotRegistry = null;
+        private List<PartitionAssignor> assignors = null;
+        private TopicsImage topicsImage = null;
+        private int consumerGroupMaxSize = Integer.MAX_VALUE;
+        private int consumerGroupHeartbeatIntervalMs = 5000;
+
+        Builder withLogContext(LogContext logContext) {
+            this.logContext = logContext;
+            return this;
+        }
+
+        Builder withSnapshotRegistry(SnapshotRegistry snapshotRegistry) {
+            this.snapshotRegistry = snapshotRegistry;
+            return this;
+        }
+
+        Builder withAssignors(List<PartitionAssignor> assignors) {
+            this.assignors = assignors;
+            return this;
+        }
+
+        Builder withConsumerGroupMaxSize(int consumerGroupMaxSize) {
+            this.consumerGroupMaxSize = consumerGroupMaxSize;
+            return this;
+        }
+
+        Builder withConsumerGroupHeartbeatInterval(int consumerGroupHeartbeatIntervalMs) {
+            this.consumerGroupHeartbeatIntervalMs = consumerGroupHeartbeatIntervalMs;
+            return this;
+        }
+
+        Builder withTopicsImage(TopicsImage topicsImage) {
+            this.topicsImage = topicsImage;
+            return this;
+        }
+
+        GroupMetadataManager build() {
+            if (logContext == null) logContext = new LogContext();
+            if (snapshotRegistry == null) snapshotRegistry = new SnapshotRegistry(logContext);
+            if (topicsImage == null) topicsImage = TopicsImage.EMPTY;
+
+            if (assignors == null || assignors.isEmpty()) {
+                throw new IllegalStateException("Assignors must be set before building.");
+            }
+
+            return new GroupMetadataManager(
+                snapshotRegistry,
+                logContext,
+                assignors,
+                topicsImage,
+                consumerGroupMaxSize,
+                consumerGroupHeartbeatIntervalMs
+            );
+        }
+    }
+
+    /**
+     * The logger.
+     */
+    private final Logger log;
+
+    /**
+     * The snapshot registry.
+     */
+    private final SnapshotRegistry snapshotRegistry;
+
+    /**
+     * The list of supported assignors.
+     */
+    private final Map<String, PartitionAssignor> assignors;
+
+    /**
+     * The default assignor used.
+     */
+    private final PartitionAssignor defaultAssignor;
+
+    /**
+     * The generic and consumer groups keyed by their name.
+     */
+    private final TimelineHashMap<String, Group> groups;
+
+    /**
+     * The generic and consumer groups keyed by their subscribed topics.
+     */
+    private final TimelineHashMap<String, TimelineHashSet<Group>> groupsByTopicName;
+
+    /**
+     * The maximum number of members allowed in a single consumer group.
+     */
+    private final int consumerGroupMaxSize;
+
+    /**
+     * The heartbeat interval for consumer groups.
+     */
+    private final int consumerGroupHeartbeatIntervalMs;
+
+    /**
+     * The topics metadata (or image).
+     */
+    private TopicsImage topicsImage;
+
+    private GroupMetadataManager(
+        SnapshotRegistry snapshotRegistry,
+        LogContext logContext,
+        List<PartitionAssignor> assignors,
+        TopicsImage topicsImage,
+        int consumerGroupMaxSize,
+        int consumerGroupHeartbeatIntervalMs
+    ) {
+        this.log = logContext.logger(GroupMetadataManager.class);
+        this.snapshotRegistry = snapshotRegistry;
+        this.topicsImage = topicsImage;
+        this.assignors = assignors.stream().collect(Collectors.toMap(PartitionAssignor::name, Function.identity()));
+        this.defaultAssignor = assignors.get(0);
+        this.groups = new TimelineHashMap<>(snapshotRegistry, 0);
+        this.groupsByTopicName = new TimelineHashMap<>(snapshotRegistry, 0);
+        this.consumerGroupMaxSize = consumerGroupMaxSize;
+        this.consumerGroupHeartbeatIntervalMs = consumerGroupHeartbeatIntervalMs;
+    }
+
+    /**
+     * Gets or maybe creates a consumer group.
+     *
+     * @param groupId           The group id.
+     * @param createIfNotExists A boolean indicating whether the group should be
+     *                          created if it does not exist.
+     *
+     * @return A ConsumerGroup.
+     * @throws GroupIdNotFoundException if the group does not exist and createIfNotExists is false or
+     *                                  if the group is not a consumer group.
+     */
+    // Package private for testing.
+    ConsumerGroup getOrMaybeCreateConsumerGroup(
+        String groupId,
+        boolean createIfNotExists
+    ) throws GroupIdNotFoundException {
+        Group group = groups.get(groupId);
+
+        if (group == null && !createIfNotExists) {
+            throw new GroupIdNotFoundException(String.format("Consumer group %s not found.", groupId));
+        }
+
+        if (group == null) {
+            ConsumerGroup consumerGroup = new ConsumerGroup(snapshotRegistry, groupId);
+            groups.put(groupId, consumerGroup);
+            return consumerGroup;
+        } else {
+            if (group.type() == Group.GroupType.CONSUMER) {
+                return (ConsumerGroup) group;
+            } else {
+                // We don't support upgrading/downgrading between protocols at the moment so
+                // we throw an exception if a group exists with the wrong type.
+                throw new GroupIdNotFoundException(String.format("Group %s is not a consumer group.", groupId));
+            }
+        }
+    }
+
+    /**
+     * Removes the group.
+     *
+     * @param groupId The group id.
+     *
+     * @return The Group removed.
+     */
+    private Group removeGroup(
+        String groupId
+    ) {
+        return groups.remove(groupId);
+    }
+
+    /**
+     * Validates the request.
+     *
+     * @param request The request to validate.
+     *
+     * @throws InvalidRequestException if the request is not valid.
+     * @throws UnsupportedAssignorException if the assignor is not supported.
+     */
+    private void throwIfConsumerGroupHeartbeatRequestIsInvalid(
+        ConsumerGroupHeartbeatRequestData request
+    ) throws InvalidRequestException, UnsupportedAssignorException {
+        if (request.groupId().isEmpty()) {
+            throw new InvalidRequestException("GroupId can't be empty.");
+        }
+
+        if (request.memberEpoch() > 0 || request.memberEpoch() == -1) {
+            if (request.memberId().isEmpty()) {
+                throw new InvalidRequestException("MemberId can't be empty.");
+            }
+            if (request.instanceId() != null) {
+                throw new InvalidRequestException("InstanceId should only be provided in first request.");
+            }
+            if (request.rackId() != null) {
+                throw new InvalidRequestException("RackId should only be provided in first request.");
+            }
+        } else if (request.memberEpoch() == 0) {
+            if (request.rebalanceTimeoutMs() == -1) {
+                throw new InvalidRequestException("RebalanceTimeoutMs must in first request.");
+            }
+            if (request.topicPartitions() == null || !request.topicPartitions().isEmpty()) {
+                throw new InvalidRequestException("TopicPartitions must be empty when (re-)joining.");
+            }
+            if (request.subscribedTopicNames() == null || request.subscribedTopicNames().isEmpty()) {
+                throw new InvalidRequestException("SubscribedTopicNames must be set in first request.");
+            }
+            if (request.serverAssignor() != null && !assignors.containsKey(request.serverAssignor())) {
+                throw new UnsupportedAssignorException("ServerAssignor " + request.serverAssignor()
+                    + " is not supported. Supported assignors: " + String.join(", ", assignors.keySet())
+                    + ".");
+            }
+        } else {
+            throw new InvalidRequestException("MemberEpoch is invalid.");
+        }
+
+        if (request.subscribedTopicRegex() != null) {
+            throw new InvalidRequestException("SubscribedTopicRegex is not supported yet.");
+        }
+
+        if (request.clientAssignors() != null) {
+            // TODO We need to remove them from the request.
+            throw new InvalidRequestException("Client side assignors are not supported yet.");
+        }
+    }
+
+    /**
+     * Verifies that the partitions currently owned by the member (the ones set in the
+     * request) matches the ones that the member should own. It matches if the client
+     * has a least of subset of them.
+     *
+     * @param ownedTopicPartitions  The partitions provided by the client in the request.
+     * @param target                The partitions that they client should have.
+     *
+     * @return A boolean indicating whether the owned partitions are a subset of not.
+     */
+    private boolean isSubset(
+        List<ConsumerGroupHeartbeatRequestData.TopicPartitions> ownedTopicPartitions,
+        Map<Uuid, Set<Integer>> target
+    ) {
+        if (ownedTopicPartitions == null) return false;
+
+        for (ConsumerGroupHeartbeatRequestData.TopicPartitions topicPartitions : ownedTopicPartitions) {
+            Set<Integer> partitions = target.get(topicPartitions.topicId());
+            if (partitions == null) return false;
+            for (Integer partitionId : topicPartitions.partitions()) {
+                if (!partitions.contains(partitionId)) return false;
+            }
+        }
+
+        return true;
+    }
+
+    /**
+     * Checks whether the consumer group can accept a new member or not based on the
+     * max group side defined.
+     *
+     * @param group     The consumer group.
+     * @param memberId  The member id.
+     *
+     * @throws GroupMaxSizeReachedException if the maximum capacity has been reached.
+     */
+    private void throwIfConsumerGroupIsFull(
+        ConsumerGroup group,
+        String memberId
+    ) throws GroupMaxSizeReachedException {
+        // If the consumer group has reached its maximum capacity, the member is rejected if it is not
+        // already a member of the consumer group.
+        if (group.numMembers() >= consumerGroupMaxSize && (memberId.isEmpty() || !group.hasMember(memberId))) {
+            throw new GroupMaxSizeReachedException("The consumer group has reached its maximum capacity of "
+                + consumerGroupMaxSize + " members.");
+        }
+    }
+
+    /**
+     * Validates the member epoch provided in the heartbeat request.
+     *
+     * @param member                The consumer group member.
+     * @param memberEpoch           The member epoch.
+     * @param ownedTopicPartitions  The owned partitions.
+     *
+     * @throws NotCoordinatorException if the provided epoch is ahead of the epoch known
+     *                                 by this coordinator. This suggests that the member
+     *                                 got a higher epoch from another coordinator.
+     * @throws FencedMemberEpochException if the provided epoch is behind the epoch known
+     *                                    by this coordinator.
+     */
+    private void throwIfMemberEpochIsInvalid(
+        ConsumerGroupMember member,
+        int memberEpoch,
+        List<ConsumerGroupHeartbeatRequestData.TopicPartitions> ownedTopicPartitions
+    ) {
+        if (memberEpoch > member.memberEpoch()) {
+            // The member has likely got a bump from another coordinator and this coordinator
+            // is stale. Return NOT_COORDINATOR to force the member to refresh its coordinator.
+            throw new NotCoordinatorException("The consumer group member has got a larger member "
+                + "epoch (" + memberEpoch + ") than the one known by this group coordinator ("
+                + member.memberEpoch() + ").");
+        } else if (memberEpoch < member.memberEpoch()) {
+            // If the member comes with the previous epoch and has a subset of the current assignment partitions,
+            // we accept it because the response with the bumped epoch may have been lost.
+            if (memberEpoch != member.previousMemberEpoch() || !isSubset(ownedTopicPartitions, member.assigned())) {
+                throw new FencedMemberEpochException("The consumer group member has an old member "
+                    + "epoch. The member must abandon all its partitions and rejoin.");
+            }
+        }
+    }
+
+    private ConsumerGroupHeartbeatResponseData.Assignment createResponseAssignment(
+        ConsumerGroupMember member
+    ) {
+        ConsumerGroupHeartbeatResponseData.Assignment assignment = new ConsumerGroupHeartbeatResponseData.Assignment()
+            .setAssignedTopicPartitions(fromAssignmentMap(member.assigned()));
+
+        if (member.state() == ConsumerGroupMember.MemberState.ASSIGNING) {
+            assignment.setPendingTopicPartitions(fromAssignmentMap(member.assigning()));
+        }
+
+        return assignment;
+    }
+
+    private List<ConsumerGroupHeartbeatResponseData.TopicPartitions> fromAssignmentMap(
+        Map<Uuid, Set<Integer>> assignment
+    ) {
+        return assignment.entrySet().stream()
+            .map(keyValue -> new ConsumerGroupHeartbeatResponseData.TopicPartitions()
+                .setTopicId(keyValue.getKey())
+                .setPartitions(new ArrayList<>(keyValue.getValue())))
+            .collect(Collectors.toList());
+    }
+
+    private OptionalInt ofSentinel(int value) {
+        return value != -1 ? OptionalInt.of(value) : OptionalInt.empty();
+    }
+
+    /**
+     * Handles a regular heartbeat from a consumer group member.
+     *
+     * @param groupId               The group id from the request.
+     * @param memberId              The member id from the request.
+     * @param memberEpoch           The member epoch from the request.
+     * @param instanceId            The instance id from the request or null.
+     * @param rackId                The rack id from the request or null.
+     * @param rebalanceTimeoutMs    The rebalance timeout from the request or -1.
+     * @param clientId              The client id.
+     * @param clientHost            The client host.
+     * @param subscribedTopicNames  The list of subscribed topic names from the request
+     *                              of null.
+     * @param subscribedTopicRegex  The regular expression based subscription from the
+     *                              request or null.
+     * @param assignorName          The assignor name from the request or null.
+     * @param ownedTopicPartitions  The list of owned partitions from the request or null.
+     *
+     * @return A Result containing the ConsumerGroupHeartbeat response and
+     *         a list of records to update the state machine.
+     */
+    private Result<ConsumerGroupHeartbeatResponseData> consumerGroupHeartbeat(
+        String groupId,
+        String memberId,
+        int memberEpoch,
+        String instanceId,
+        String rackId,
+        int rebalanceTimeoutMs,
+        String clientId,
+        String clientHost,
+        List<String> subscribedTopicNames,
+        String subscribedTopicRegex,
+        String assignorName,
+        List<ConsumerGroupHeartbeatRequestData.TopicPartitions> ownedTopicPartitions
+    ) {
+        List<Record> records = new ArrayList<>();
+        boolean createIfNotExists = memberEpoch == 0;
+
+        ConsumerGroup group = getOrMaybeCreateConsumerGroup(groupId, createIfNotExists);
+        throwIfConsumerGroupIsFull(group, memberId);
+
+        if (memberId.isEmpty()) memberId = Uuid.randomUuid().toString();
+        ConsumerGroupMember member = group.getOrMaybeCreateMember(memberId, createIfNotExists);
+        throwIfMemberEpochIsInvalid(member, memberEpoch, ownedTopicPartitions);
+
+        if (memberEpoch == 0) {
+            log.info("[GroupId " + groupId + "] Member " + memberId + " re-joins the consumer group.");

Review Comment:
   Is this log provided when a new member joins the group? (or is it always re-joins?)



##########
group-coordinator/src/main/java/org/apache/kafka/coordinator/group/consumer/ConsumerGroupMember.java:
##########
@@ -0,0 +1,555 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.kafka.coordinator.group.consumer;
+
+import org.apache.kafka.common.Uuid;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupCurrentMemberAssignmentValue;
+import org.apache.kafka.coordinator.group.generated.ConsumerGroupMemberMetadataValue;
+
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.OptionalInt;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+/**
+ * ConsumerGroupMember contains all the information related to a member
+ * within a consumer group. This class is immutable.
+ */
+public class ConsumerGroupMember {
+    /**
+     * A builder allowing to create a new member or update an
+     * existing one.
+     */
+    public static class Builder {
+        private final String memberId;
+        private int memberEpoch = 0;
+        private int previousMemberEpoch = -1;
+        private int nextMemberEpoch = 0;
+        private String instanceId = null;
+        private String rackId = null;
+        private int rebalanceTimeoutMs = -1;
+        private String clientId = "";
+        private String clientHost = "";
+        private List<String> subscribedTopicNames = Collections.emptyList();
+        private String subscribedTopicRegex = "";
+        private String serverAssignorName = null;
+        private List<ClientAssignor> clientAssignors = Collections.emptyList();
+        private Map<Uuid, Set<Integer>> assigned = Collections.emptyMap();
+        private Map<Uuid, Set<Integer>> revoking = Collections.emptyMap();
+        private Map<Uuid, Set<Integer>> assigning = Collections.emptyMap();
+
+        public Builder(String memberId) {
+            this.memberId = Objects.requireNonNull(memberId);
+        }
+
+        public Builder(ConsumerGroupMember member) {
+            Objects.requireNonNull(member);
+
+            this.memberId = member.memberId;
+            this.memberEpoch = member.memberEpoch;
+            this.previousMemberEpoch = member.previousMemberEpoch;
+            this.nextMemberEpoch = member.nextMemberEpoch;
+            this.instanceId = member.instanceId;
+            this.rackId = member.rackId;
+            this.rebalanceTimeoutMs = member.rebalanceTimeoutMs;
+            this.clientId = member.clientId;
+            this.clientHost = member.clientHost;
+            this.subscribedTopicNames = member.subscribedTopicNames;
+            this.subscribedTopicRegex = member.subscribedTopicRegex;
+            this.serverAssignorName = member.serverAssignorName;
+            this.clientAssignors = member.clientAssignors;
+            this.assigned = member.assigned;
+            this.revoking = member.revoking;
+            this.assigning = member.assigning;
+        }
+
+        public Builder setMemberEpoch(int memberEpoch) {
+            this.memberEpoch = memberEpoch;
+            return this;
+        }
+
+        public Builder setPreviousMemberEpoch(int previousMemberEpoch) {
+            this.previousMemberEpoch = previousMemberEpoch;
+            return this;
+        }
+
+        public Builder setNextMemberEpoch(int nextMemberEpoch) {
+            this.nextMemberEpoch = nextMemberEpoch;
+            return this;
+        }
+
+        public Builder setInstanceId(String instanceId) {
+            this.instanceId = instanceId;
+            return this;
+        }
+
+        public Builder maybeUpdateInstanceId(Optional<String> instanceId) {
+            this.instanceId = instanceId.orElse(this.instanceId);
+            return this;
+        }
+
+        public Builder setRackId(String rackId) {
+            this.rackId = rackId;
+            return this;
+        }
+
+        public Builder maybeUpdateRackId(Optional<String> rackId) {
+            this.rackId = rackId.orElse(this.rackId);
+            return this;
+        }
+
+        public Builder setRebalanceTimeoutMs(int rebalanceTimeoutMs) {
+            this.rebalanceTimeoutMs = rebalanceTimeoutMs;
+            return this;
+        }
+
+        public Builder maybeUpdateRebalanceTimeoutMs(OptionalInt rebalanceTimeoutMs) {
+            this.rebalanceTimeoutMs = rebalanceTimeoutMs.orElse(this.rebalanceTimeoutMs);
+            return this;
+        }
+
+        public Builder setClientId(String clientId) {
+            this.clientId = clientId;
+            return this;
+        }
+
+        public Builder setClientHost(String clientHost) {
+            this.clientHost = clientHost;
+            return this;
+        }
+
+        public Builder setSubscribedTopicNames(List<String> subscribedTopicNames) {
+            this.subscribedTopicNames = subscribedTopicNames;
+            this.subscribedTopicNames.sort(Comparator.naturalOrder());
+            return this;
+        }
+
+        public Builder maybeUpdateSubscribedTopicNames(Optional<List<String>> subscribedTopicNames) {
+            this.subscribedTopicNames = subscribedTopicNames.orElse(this.subscribedTopicNames);
+            this.subscribedTopicNames.sort(Comparator.naturalOrder());
+            return this;
+        }
+
+        public Builder setSubscribedTopicRegex(String subscribedTopicRegex) {
+            this.subscribedTopicRegex = subscribedTopicRegex;
+            return this;
+        }
+
+        public Builder maybeUpdateSubscribedTopicRegex(Optional<String> subscribedTopicRegex) {
+            this.subscribedTopicRegex = subscribedTopicRegex.orElse(this.subscribedTopicRegex);
+            return this;
+        }
+
+        public Builder setServerAssignorName(String serverAssignorName) {
+            this.serverAssignorName = serverAssignorName;
+            return this;
+        }
+
+        public Builder maybeUpdateServerAssignorName(Optional<String> serverAssignorName) {
+            this.serverAssignorName = serverAssignorName.orElse(this.serverAssignorName);
+            return this;
+        }
+
+        public Builder setClientAssignors(List<ClientAssignor> clientAssignors) {
+            this.clientAssignors = clientAssignors;
+            return this;
+        }
+
+        public Builder maybeUpdateClientAssignors(Optional<List<ClientAssignor>> clientAssignors) {
+            this.clientAssignors = clientAssignors.orElse(this.clientAssignors);
+            return this;
+        }
+
+        public Builder setAssigned(Map<Uuid, Set<Integer>> assigned) {
+            this.assigned = assigned;
+            return this;
+        }
+
+        public Builder setRevoking(Map<Uuid, Set<Integer>> revoking) {
+            this.revoking = revoking;
+            return this;
+        }
+
+        public Builder setAssigning(Map<Uuid, Set<Integer>> assigning) {
+            this.assigning = assigning;
+            return this;
+        }
+
+        public Builder mergeWith(ConsumerGroupMemberMetadataValue record) {
+            setInstanceId(record.instanceId());
+            setRackId(record.rackId());
+            setClientId(record.clientId());
+            setClientHost(record.clientHost());
+            setSubscribedTopicNames(record.subscribedTopicNames());
+            setSubscribedTopicRegex(record.subscribedTopicRegex());
+            setRebalanceTimeoutMs(record.rebalanceTimeoutMs());
+            setServerAssignorName(record.serverAssignor());
+            setClientAssignors(record.assignors().stream()
+                .map(ClientAssignor::fromRecord)
+                .collect(Collectors.toList()));
+            return this;
+        }
+
+        public Builder mergeWith(ConsumerGroupCurrentMemberAssignmentValue record) {
+            setMemberEpoch(record.memberEpoch());
+            setPreviousMemberEpoch(record.previousMemberEpoch());
+            setNextMemberEpoch(record.targetMemberEpoch());
+            setAssigned(assignmentFromTopicPartitions(record.assigned()));
+            setRevoking(assignmentFromTopicPartitions(record.revoking()));
+            setAssigning(assignmentFromTopicPartitions(record.assigning()));
+            return this;
+        }
+
+        private Map<Uuid, Set<Integer>> assignmentFromTopicPartitions(
+            List<ConsumerGroupCurrentMemberAssignmentValue.TopicPartitions> topicPartitionsList
+        ) {
+            return topicPartitionsList.stream().collect(Collectors.toMap(
+                ConsumerGroupCurrentMemberAssignmentValue.TopicPartitions::topicId,
+                topicPartitions -> Collections.unmodifiableSet(new HashSet<>(topicPartitions.partitions()))));
+        }
+
+        public ConsumerGroupMember build() {
+            MemberState state;
+            if (!revoking.isEmpty()) {
+                state = MemberState.REVOKING;
+            } else if (!assigning.isEmpty()) {
+                state = MemberState.ASSIGNING;
+            } else {
+                state = MemberState.STABLE;
+            }
+
+            return new ConsumerGroupMember(
+                memberId,
+                memberEpoch,
+                previousMemberEpoch,
+                nextMemberEpoch,
+                instanceId,
+                rackId,
+                rebalanceTimeoutMs,
+                clientId,
+                clientHost,
+                subscribedTopicNames,
+                subscribedTopicRegex,
+                serverAssignorName,
+                clientAssignors,
+                state,
+                assigned,
+                revoking,
+                assigning
+            );
+        }
+    }
+
+    public enum MemberState {
+        REVOKING("revoking"),
+        ASSIGNING("assigning"),
+        STABLE("stable");
+
+        private final String name;
+
+        MemberState(String name) {
+            this.name = name;
+        }
+
+        @Override
+        public String toString() {
+            return name;
+        }
+    }
+
+    /**
+     * The member id.
+     */
+    private final String memberId;
+
+    /**
+     * The current member epoch.
+     */
+    private final int memberEpoch;
+
+    /**
+     * The previous member epoch.
+     */
+    private final int previousMemberEpoch;
+
+    /**
+     * The next member epoch. This corresponds to the target
+     * assignment epoch used to compute the current assigned,
+     * revoking and assigning partitions.
+     */
+    private final int nextMemberEpoch;
+
+    /**
+     * The instance id provided by the member.
+     */
+    private final String instanceId;
+
+    /**
+     * The rack id provided by the member.
+     */
+    private final String rackId;
+
+    /**
+     * The rebalance timeout provided by the member.
+     */
+    private final int rebalanceTimeoutMs;
+
+    /**
+     * The client id reported by the member.
+     */
+    private final String clientId;
+
+    /**
+     * The host reported by the member.
+     */
+    private final String clientHost;
+
+    /**
+     * The list of subscriptions (topic names) configured by the member.
+     */
+    private final List<String> subscribedTopicNames;
+
+    /**
+     * The subscription pattern configured by the member,
+     */
+    private final String subscribedTopicRegex;
+
+    /**
+     * The server side assignor selected by the member.
+     */
+    private final String serverAssignorName;
+
+    /**
+     * The states of the client side assignors of the member.
+     */
+    private final List<ClientAssignor> clientAssignors;
+
+    /**
+     * The member state.
+     */
+    private final MemberState state;
+
+    /**
+     * The partitions assigned to this member.
+     */
+    private final Map<Uuid, Set<Integer>> assigned;
+
+    /**
+     * The partitions being revoked by this member.
+     */
+    private final Map<Uuid, Set<Integer>> revoking;
+
+    /**
+     * The partitions waiting to be assigned to this
+     * member. They will be assigned when they are
+     * released by their previous owners.
+     */
+    private final Map<Uuid, Set<Integer>> assigning;
+
+    private ConsumerGroupMember(
+        String memberId,
+        int memberEpoch,
+        int previousMemberEpoch,
+        int nextMemberEpoch,
+        String instanceId,
+        String rackId,
+        int rebalanceTimeoutMs,
+        String clientId,
+        String clientHost,
+        List<String> subscribedTopicNames,
+        String subscribedTopicRegex,
+        String serverAssignorName,
+        List<ClientAssignor> clientAssignors,
+        MemberState state,
+        Map<Uuid, Set<Integer>> assigned,
+        Map<Uuid, Set<Integer>> revoking,
+        Map<Uuid, Set<Integer>> assigning
+    ) {
+        this.memberId = memberId;
+        this.memberEpoch = memberEpoch;
+        this.previousMemberEpoch = previousMemberEpoch;
+        this.nextMemberEpoch = nextMemberEpoch;
+        this.instanceId = instanceId;
+        this.rackId = rackId;
+        this.rebalanceTimeoutMs = rebalanceTimeoutMs;
+        this.clientId = clientId;
+        this.clientHost = clientHost;
+        this.subscribedTopicNames = subscribedTopicNames;
+        this.subscribedTopicRegex = subscribedTopicRegex;
+        this.serverAssignorName = serverAssignorName;
+        this.clientAssignors = clientAssignors;
+        this.state = state;
+        this.assigned = assigned;
+        this.revoking = revoking;
+        this.assigning = assigning;
+    }
+
+    public String memberId() {
+        return memberId;
+    }
+
+    public int memberEpoch() {
+        return memberEpoch;
+    }
+
+    public int previousMemberEpoch() {
+        return previousMemberEpoch;
+    }
+
+    public int nextMemberEpoch() {
+        return nextMemberEpoch;
+    }
+
+    public String instanceId() {
+        return instanceId;
+    }
+
+    public String rackId() {
+        return rackId;
+    }
+
+    public int rebalanceTimeoutMs() {
+        return rebalanceTimeoutMs;
+    }
+
+    public String clientId() {
+        return clientId;
+    }
+
+    public String clientHost() {
+        return clientHost;
+    }
+
+    public List<String> subscribedTopicNames() {
+        return subscribedTopicNames;
+    }
+
+    public String subscribedTopicRegex() {
+        return subscribedTopicRegex;
+    }
+
+    public Optional<String> serverAssignorName() {
+        return Optional.ofNullable(serverAssignorName);
+    }
+
+    public List<ClientAssignor> clientAssignors() {
+        return clientAssignors;
+    }
+
+    public MemberState state() {
+        return state;
+    }
+
+    public Map<Uuid, Set<Integer>> assigned() {
+        return assigned;
+    }
+
+    public Map<Uuid, Set<Integer>> revoking() {
+        return revoking;
+    }
+
+    public Map<Uuid, Set<Integer>> assigning() {
+        return assigning;
+    }
+
+    public String currentAssignmentSummary() {
+        return "CurrentAssignment(" +
+            ", memberEpoch=" + memberEpoch +
+            ", previousMemberEpoch=" + previousMemberEpoch +
+            ", nextMemberEpoch=" + nextMemberEpoch +
+            ", state=" + state +
+            ", assigned=" + assigned +
+            ", revoking=" + revoking +
+            ", assigning=" + assigning +
+            ')';
+    }
+
+    @Override
+    public boolean equals(Object o) {
+        if (this == o) return true;
+        if (o == null || getClass() != o.getClass()) return false;
+
+        ConsumerGroupMember that = (ConsumerGroupMember) o;
+
+        if (memberEpoch != that.memberEpoch) return false;
+        if (previousMemberEpoch != that.previousMemberEpoch) return false;
+        if (nextMemberEpoch != that.nextMemberEpoch) return false;
+        if (rebalanceTimeoutMs != that.rebalanceTimeoutMs) return false;
+        if (!Objects.equals(memberId, that.memberId)) return false;
+        if (!Objects.equals(instanceId, that.instanceId)) return false;
+        if (!Objects.equals(rackId, that.rackId)) return false;
+        if (!Objects.equals(clientId, that.clientId)) return false;
+        if (!Objects.equals(clientHost, that.clientHost)) return false;
+        if (!Objects.equals(subscribedTopicNames, that.subscribedTopicNames)) return false;
+        if (!Objects.equals(subscribedTopicRegex, that.subscribedTopicRegex)) return false;
+        if (!Objects.equals(serverAssignorName, that.serverAssignorName)) return false;
+        if (!Objects.equals(clientAssignors, that.clientAssignors)) return false;
+        if (!Objects.equals(assigned, that.assigned)) return false;
+        if (!Objects.equals(revoking, that.revoking)) return false;
+        return Objects.equals(assigning, that.assigning);
+    }
+
+    @Override
+    public int hashCode() {
+        int result = memberId != null ? memberId.hashCode() : 0;

Review Comment:
   nit: maybe `Objects.hashCode()` could be used?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org