You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@kafka.apache.org by wc...@apache.org on 2023/11/01 19:54:02 UTC

(kafka) branch trunk updated: KAFKA-15627: KIP-951's Leader discovery optimisations on the client (#14685)

This is an automated email from the ASF dual-hosted git repository.

wcarlson pushed a commit to branch trunk
in repository https://gitbox.apache.org/repos/asf/kafka.git


The following commit(s) were added to refs/heads/trunk by this push:
     new a9565a799f3 KAFKA-15627: KIP-951's Leader discovery optimisations on the client (#14685)
a9565a799f3 is described below

commit a9565a799f3f87eb1d932b114dde7373748551ac
Author: Mayank Shekhar Narula <42...@users.noreply.github.com>
AuthorDate: Wed Nov 1 19:53:55 2023 +0000

    KAFKA-15627: KIP-951's Leader discovery optimisations on the client (#14685)
    
    This implements the leader discovery optimisations for the client on [KIP-951](https://cwiki.apache.org/confluence/display/KAFKA/KIP-951%3A+Leader+discovery+optimisations+for+the+client).
    
    Optimisation1: On discovering a new leader, produce-batch should skip any retry-backoff. This was implemented in [KAFKA-15415](https://issues.apache.org/jira/browse/KAFKA-15415)
    Optimisation2: FetchResponse/ProduceResponse would return new leader info. This information is then used to update the Metadata cached.
    This PR focuses on optimisation2 from above. Additionally it fixes a bug that got introduced to MetadataCache.java, details inline in a comment.
    
    Reviewers: Walker Carlson <wc...@apache.org>, Andrew Schofield <an...@uk.ibm.com>, Kirk True <kt...@confluent.io>
---
 .../java/org/apache/kafka/clients/Metadata.java    | 108 ++++++++++-
 .../org/apache/kafka/clients/MetadataCache.java    |  10 +-
 .../kafka/clients/consumer/KafkaConsumer.java      |   3 +-
 .../clients/consumer/internals/AbstractFetch.java  |  35 +++-
 .../consumer/internals/FetchRequestManager.java    |  20 +-
 .../kafka/clients/consumer/internals/Fetcher.java  |   6 +-
 .../consumer/internals/RequestManagers.java        |   3 +-
 .../producer/internals/RecordAccumulator.java      |  18 +-
 .../kafka/clients/producer/internals/Sender.java   |  48 ++++-
 .../kafka/common/requests/FetchResponse.java       |  36 +++-
 .../kafka/common/requests/ProduceResponse.java     |  25 ++-
 .../apache/kafka/clients/MetadataCacheTest.java    |  66 +++++++
 .../org/apache/kafka/clients/MetadataTest.java     | 162 ++++++++++++++++
 .../kafka/clients/consumer/KafkaConsumerTest.java  |   3 +-
 .../consumer/internals/ConsumerTestBuilder.java    |   3 +-
 .../internals/FetchRequestManagerTest.java         |   2 +-
 .../clients/consumer/internals/FetcherTest.java    | 207 +++++++++++++++++++-
 .../consumer/internals/OffsetFetcherTest.java      |   3 +-
 .../clients/producer/internals/SenderTest.java     | 211 +++++++++++++++++++++
 19 files changed, 915 insertions(+), 54 deletions(-)

diff --git a/clients/src/main/java/org/apache/kafka/clients/Metadata.java b/clients/src/main/java/org/apache/kafka/clients/Metadata.java
index 052f2081d18..c0ebcb704f7 100644
--- a/clients/src/main/java/org/apache/kafka/clients/Metadata.java
+++ b/clients/src/main/java/org/apache/kafka/clients/Metadata.java
@@ -16,6 +16,8 @@
  */
 package org.apache.kafka.clients;
 
+import java.util.Map.Entry;
+import java.util.stream.Collectors;
 import org.apache.kafka.common.Cluster;
 import org.apache.kafka.common.ClusterResourceListener;
 import org.apache.kafka.common.KafkaException;
@@ -29,6 +31,7 @@ import org.apache.kafka.common.internals.ClusterResourceListeners;
 import org.apache.kafka.common.protocol.Errors;
 import org.apache.kafka.common.requests.MetadataRequest;
 import org.apache.kafka.common.requests.MetadataResponse;
+import org.apache.kafka.common.requests.MetadataResponse.PartitionMetadata;
 import org.apache.kafka.common.utils.ExponentialBackoff;
 import org.apache.kafka.common.utils.LogContext;
 import org.slf4j.Logger;
@@ -208,7 +211,7 @@ public class Metadata implements Closeable {
 
     /**
      * Request an update for the partition metadata iff we have seen a newer leader epoch. This is called by the client
-     * any time it handles a response from the broker that includes leader epoch, except for UpdateMetadata which
+     * any time it handles a response from the broker that includes leader epoch, except for update via Metadata RPC which
      * follows a different code path ({@link #update}).
      *
      * @param topicPartition
@@ -350,6 +353,91 @@ public class Metadata implements Closeable {
         log.debug("Updated cluster metadata updateVersion {} to {}", this.updateVersion, this.cache);
     }
 
+    /**
+     * Updates the partition-leadership info in the metadata. Update is done by merging existing metadata with the input leader information and nodes.
+     * This is called whenever partition-leadership updates are returned in a response from broker(ex - ProduceResponse & FetchResponse).
+     * Note that the updates via Metadata RPC are handled separately in ({@link #update}).
+     * Both partitionLeader and leaderNodes override the existing metadata. Non-overlapping metadata is kept as it is.
+     * @param partitionLeaders map of new leadership information for partitions.
+     * @param leaderNodes a list of nodes for leaders in the above map.
+     * @return a set of partitions, for which leaders were updated.
+     */
+    public synchronized Set<TopicPartition> updatePartitionLeadership(Map<TopicPartition, LeaderIdAndEpoch> partitionLeaders, List<Node> leaderNodes) {
+        Map<Integer, Node> newNodes = leaderNodes.stream().collect(Collectors.toMap(Node::id, node -> node));
+        // Insert non-overlapping nodes from existing-nodes into new-nodes.
+        this.cache.cluster().nodes().stream().forEach(node -> newNodes.putIfAbsent(node.id(), node));
+
+        // Create partition-metadata for all updated partitions. Exclude updates for partitions -
+        // 1. for which the corresponding partition has newer leader in existing metadata.
+        // 2. for which corresponding leader's node is missing in the new-nodes.
+        // 3. for which the existing metadata doesn't know about the partition.
+        List<PartitionMetadata> updatePartitionMetadata = new ArrayList<>();
+        for (Entry<TopicPartition, Metadata.LeaderIdAndEpoch> partitionLeader: partitionLeaders.entrySet()) {
+            TopicPartition partition = partitionLeader.getKey();
+            Metadata.LeaderAndEpoch currentLeader = currentLeader(partition);
+            Metadata.LeaderIdAndEpoch newLeader = partitionLeader.getValue();
+            if (!newLeader.epoch.isPresent() || !newLeader.leaderId.isPresent()) {
+                log.debug("For {}, incoming leader information is incomplete {}", partition, newLeader);
+                continue;
+            }
+            if (currentLeader.epoch.isPresent() && newLeader.epoch.get() <= currentLeader.epoch.get()) {
+                log.debug("For {}, incoming leader({}) is not-newer than the one in the existing metadata {}, so ignoring.", partition, newLeader, currentLeader);
+                continue;
+            }
+            if (!newNodes.containsKey(newLeader.leaderId.get())) {
+                log.debug("For {}, incoming leader({}), the corresponding node information for node-id {} is missing, so ignoring.", partition, newLeader, newLeader.leaderId.get());
+                continue;
+            }
+            if (!this.cache.partitionMetadata(partition).isPresent()) {
+                log.debug("For {}, incoming leader({}), partition metadata is no longer cached, ignoring.", partition, newLeader);
+                continue;
+            }
+
+            MetadataResponse.PartitionMetadata existingMetadata = this.cache.partitionMetadata(partition).get();
+            MetadataResponse.PartitionMetadata updatedMetadata = new MetadataResponse.PartitionMetadata(
+                existingMetadata.error,
+                partition,
+                newLeader.leaderId,
+                newLeader.epoch,
+                existingMetadata.replicaIds,
+                existingMetadata.inSyncReplicaIds,
+                existingMetadata.offlineReplicaIds
+            );
+            updatePartitionMetadata.add(updatedMetadata);
+
+            lastSeenLeaderEpochs.put(partition, newLeader.epoch.get());
+        }
+
+        if (updatePartitionMetadata.isEmpty()) {
+            log.debug("No relevant metadata updates.");
+            return new HashSet<>();
+        }
+
+        Set<String> updatedTopics = updatePartitionMetadata.stream().map(MetadataResponse.PartitionMetadata::topic).collect(Collectors.toSet());
+
+        // Get topic-ids for updated topics from existing topic-ids.
+        Map<String, Uuid> existingTopicIds = this.cache.topicIds();
+        Map<String, Uuid> topicIdsForUpdatedTopics = updatedTopics.stream()
+            .filter(e -> existingTopicIds.containsKey(e))
+            .collect(Collectors.toMap(e -> e, e -> existingTopicIds.get(e)));
+
+        if (log.isDebugEnabled()) {
+            updatePartitionMetadata.forEach(
+                partMetadata -> log.debug("For {} updating leader information, updated metadata is {}.", partMetadata.topicPartition, partMetadata)
+            );
+        }
+
+        this.cache = cache.mergeWith(cache.clusterResource().clusterId(), newNodes,
+                    updatePartitionMetadata, Collections.emptySet(), Collections.emptySet(),
+                    Collections.emptySet(), cache.cluster().controller(), topicIdsForUpdatedTopics,
+                    (topic, isInternal) -> !updatedTopics.contains(topic));
+        clusterResourceListeners.onUpdate(cache.clusterResource());
+
+        return updatePartitionMetadata.stream()
+            .map(metadata -> metadata.topicPartition)
+            .collect(Collectors.toSet());
+    }
+
     private void maybeSetMetadataError(Cluster cluster) {
         clearRecoverableErrors();
         checkInvalidTopics(cluster);
@@ -706,4 +794,22 @@ public class Metadata implements Closeable {
                     '}';
         }
     }
+
+    public static class LeaderIdAndEpoch {
+        public final Optional<Integer> leaderId;
+        public final Optional<Integer> epoch;
+
+        public LeaderIdAndEpoch(Optional<Integer> leaderId, Optional<Integer> epoch) {
+            this.leaderId = Objects.requireNonNull(leaderId);
+            this.epoch = Objects.requireNonNull(epoch);
+        }
+
+        @Override
+        public String toString() {
+            return "LeaderIdAndEpoch{" +
+                "leaderId=" + leaderId.map(Number::toString).orElse("absent") +
+                ", epoch=" + epoch.map(Number::toString).orElse("absent") +
+                '}';
+        }
+    }
 }
diff --git a/clients/src/main/java/org/apache/kafka/clients/MetadataCache.java b/clients/src/main/java/org/apache/kafka/clients/MetadataCache.java
index d7b6bfd344e..38a039a0a38 100644
--- a/clients/src/main/java/org/apache/kafka/clients/MetadataCache.java
+++ b/clients/src/main/java/org/apache/kafka/clients/MetadataCache.java
@@ -129,8 +129,8 @@ public class MetadataCache {
      * @param addUnauthorizedTopics unauthorized topics to add
      * @param addInternalTopics internal topics to add
      * @param newController the new controller node
-     * @param topicIds the mapping from topic name to topic ID from the MetadataResponse
-     * @param retainTopic returns whether a topic's metadata should be retained
+     * @param addTopicIds the mapping from topic name to topic ID, for topics in addPartitions
+     * @param retainTopic returns whether a pre-existing topic's metadata should be retained
      * @return the merged metadata cache
      */
     MetadataCache mergeWith(String newClusterId,
@@ -140,7 +140,7 @@ public class MetadataCache {
                             Set<String> addInvalidTopics,
                             Set<String> addInternalTopics,
                             Node newController,
-                            Map<String, Uuid> topicIds,
+                            Map<String, Uuid> addTopicIds,
                             BiPredicate<String, Boolean> retainTopic) {
 
         Predicate<String> shouldRetainTopic = topic -> retainTopic.test(topic, internalTopics.contains(topic));
@@ -150,13 +150,13 @@ public class MetadataCache {
         // We want the most recent topic ID. We start with the previous ID stored for retained topics and then
         // update with newest information from the MetadataResponse. We always take the latest state, removing existing
         // topic IDs if the latest state contains the topic name but not a topic ID.
-        Map<String, Uuid> newTopicIds = topicIds.entrySet().stream()
+        Map<String, Uuid> newTopicIds = this.topicIds.entrySet().stream()
                 .filter(entry -> shouldRetainTopic.test(entry.getKey()))
                 .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
 
         for (PartitionMetadata partition : addPartitions) {
             newMetadataByPartition.put(partition.topicPartition, partition);
-            Uuid id = topicIds.get(partition.topic());
+            Uuid id = addTopicIds.get(partition.topic());
             if (id != null)
                 newTopicIds.put(partition.topic(), id);
             else
diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/KafkaConsumer.java b/clients/src/main/java/org/apache/kafka/clients/consumer/KafkaConsumer.java
index 141ac66c5b7..bd795e033ab 100644
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/KafkaConsumer.java
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/KafkaConsumer.java
@@ -759,7 +759,8 @@ public class KafkaConsumer<K, V> implements Consumer<K, V> {
                     fetchConfig,
                     this.deserializers,
                     fetchMetricsManager,
-                    this.time);
+                    this.time,
+                    apiVersions);
             this.offsetFetcher = new OffsetFetcher(logContext,
                     client,
                     metadata,
diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/AbstractFetch.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/AbstractFetch.java
index ffca2cee35d..07c82907fef 100644
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/AbstractFetch.java
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/AbstractFetch.java
@@ -16,10 +16,14 @@
  */
 package org.apache.kafka.clients.consumer.internals;
 
+import java.util.List;
+import java.util.stream.Collectors;
+import org.apache.kafka.clients.ApiVersions;
 import org.apache.kafka.clients.ClientResponse;
 import org.apache.kafka.clients.FetchSessionHandler;
 import org.apache.kafka.clients.KafkaClient;
 import org.apache.kafka.clients.NetworkClientUtils;
+import org.apache.kafka.clients.Metadata;
 import org.apache.kafka.common.Cluster;
 import org.apache.kafka.common.Node;
 import org.apache.kafka.common.TopicPartition;
@@ -47,7 +51,6 @@ import java.util.Map;
 import java.util.Optional;
 import java.util.Set;
 import java.util.function.Predicate;
-import java.util.stream.Collectors;
 
 import static org.apache.kafka.clients.consumer.internals.FetchUtils.requestMetadataUpdate;
 
@@ -70,13 +73,16 @@ public abstract class AbstractFetch implements Closeable {
 
     private final Map<Integer, FetchSessionHandler> sessionHandlers;
 
+    private final ApiVersions apiVersions;
+
     public AbstractFetch(final LogContext logContext,
                          final ConsumerMetadata metadata,
                          final SubscriptionState subscriptions,
                          final FetchConfig fetchConfig,
                          final FetchBuffer fetchBuffer,
                          final FetchMetricsManager metricsManager,
-                         final Time time) {
+                         final Time time,
+                         final ApiVersions apiVersions) {
         this.log = logContext.logger(AbstractFetch.class);
         this.logContext = logContext;
         this.metadata = metadata;
@@ -88,6 +94,7 @@ public abstract class AbstractFetch implements Closeable {
         this.nodesWithPendingFetchRequests = new HashSet<>();
         this.metricsManager = metricsManager;
         this.time = time;
+        this.apiVersions = apiVersions;
     }
 
     /**
@@ -159,6 +166,7 @@ public abstract class AbstractFetch implements Closeable {
             final Set<TopicPartition> partitions = new HashSet<>(responseData.keySet());
             final FetchMetricsAggregator metricAggregator = new FetchMetricsAggregator(metricsManager, partitions);
 
+            Map<TopicPartition, Metadata.LeaderIdAndEpoch> partitionsWithUpdatedLeaderInfo = new HashMap<>();
             for (Map.Entry<TopicPartition, FetchResponseData.PartitionData> entry : responseData.entrySet()) {
                 TopicPartition partition = entry.getKey();
                 FetchRequest.PartitionData requestData = data.sessionPartitions().get(partition);
@@ -186,6 +194,15 @@ public abstract class AbstractFetch implements Closeable {
                 log.debug("Fetch {} at offset {} for partition {} returned fetch data {}",
                         fetchConfig.isolationLevel, fetchOffset, partition, partitionData);
 
+                Errors partitionError = Errors.forCode(partitionData.errorCode());
+                if (partitionError == Errors.NOT_LEADER_OR_FOLLOWER || partitionError == Errors.FENCED_LEADER_EPOCH) {
+                    log.debug("For {}, received error {}, with leaderIdAndEpoch {}", partition, partitionError, partitionData.currentLeader());
+                    if (partitionData.currentLeader().leaderId() != -1 && partitionData.currentLeader().leaderEpoch() != -1) {
+                        partitionsWithUpdatedLeaderInfo.put(partition, new Metadata.LeaderIdAndEpoch(
+                            Optional.of(partitionData.currentLeader().leaderId()), Optional.of(partitionData.currentLeader().leaderEpoch())));
+                    }
+                }
+
                 CompletedFetch completedFetch = new CompletedFetch(
                         logContext,
                         subscriptions,
@@ -198,6 +215,20 @@ public abstract class AbstractFetch implements Closeable {
                 fetchBuffer.add(completedFetch);
             }
 
+            if (!partitionsWithUpdatedLeaderInfo.isEmpty()) {
+                List<Node> leaderNodes = response.data().nodeEndpoints().stream()
+                    .map(e -> new Node(e.nodeId(), e.host(), e.port(), e.rack()))
+                    .filter(e -> !e.equals(Node.noNode()))
+                    .collect(Collectors.toList());
+                Set<TopicPartition> updatedPartitions = metadata.updatePartitionLeadership(partitionsWithUpdatedLeaderInfo, leaderNodes);
+                updatedPartitions.forEach(
+                    tp -> {
+                        log.debug("For {}, as the leader was updated, position will be validated.", tp);
+                        subscriptions.maybeValidatePositionForCurrentLeader(apiVersions, tp, metadata.currentLeader(tp));
+                    }
+                );
+            }
+
             metricsManager.recordLatency(resp.requestLatencyMs());
         } finally {
             removePendingFetchRequest(fetchTarget, data.metadata().sessionId());
diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/FetchRequestManager.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/FetchRequestManager.java
index 3af0c1441f9..d99fa77f0f9 100644
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/FetchRequestManager.java
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/FetchRequestManager.java
@@ -16,6 +16,14 @@
  */
 package org.apache.kafka.clients.consumer.internals;
 
+import java.util.List;
+import java.util.Map;
+import java.util.function.BiConsumer;
+import java.util.function.Predicate;
+import java.util.stream.Collectors;
+import java.util.Optional;
+
+import org.apache.kafka.clients.ApiVersions;
 import org.apache.kafka.clients.ClientResponse;
 import org.apache.kafka.clients.FetchSessionHandler;
 import org.apache.kafka.clients.consumer.internals.NetworkClientDelegate.PollResult;
@@ -25,13 +33,6 @@ import org.apache.kafka.common.requests.FetchRequest;
 import org.apache.kafka.common.utils.LogContext;
 import org.apache.kafka.common.utils.Time;
 
-import java.util.List;
-import java.util.Map;
-import java.util.Optional;
-import java.util.function.BiConsumer;
-import java.util.function.Predicate;
-import java.util.stream.Collectors;
-
 /**
  * {@code FetchRequestManager} is responsible for generating {@link FetchRequest} that represent the
  * {@link SubscriptionState#fetchablePartitions(Predicate)} based on the user's topic subscription/partition
@@ -48,8 +49,9 @@ public class FetchRequestManager extends AbstractFetch implements RequestManager
                         final FetchConfig fetchConfig,
                         final FetchBuffer fetchBuffer,
                         final FetchMetricsManager metricsManager,
-                        final NetworkClientDelegate networkClientDelegate) {
-        super(logContext, metadata, subscriptions, fetchConfig, fetchBuffer, metricsManager, time);
+                        final NetworkClientDelegate networkClientDelegate,
+                        final ApiVersions apiVersions) {
+        super(logContext, metadata, subscriptions, fetchConfig, fetchBuffer, metricsManager, time, apiVersions);
         this.networkClientDelegate = networkClientDelegate;
     }
 
diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/Fetcher.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/Fetcher.java
index 05df99373e1..51b2532e48b 100644
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/Fetcher.java
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/Fetcher.java
@@ -17,6 +17,7 @@
 package org.apache.kafka.clients.consumer.internals;
 
 import org.apache.kafka.clients.ClientRequest;
+import org.apache.kafka.clients.ApiVersions;
 import org.apache.kafka.clients.ClientResponse;
 import org.apache.kafka.clients.FetchSessionHandler;
 import org.apache.kafka.clients.NetworkClient;
@@ -67,8 +68,9 @@ public class Fetcher<K, V> extends AbstractFetch {
                    FetchConfig fetchConfig,
                    Deserializers<K, V> deserializers,
                    FetchMetricsManager metricsManager,
-                   Time time) {
-        super(logContext, metadata, subscriptions, fetchConfig, new FetchBuffer(logContext), metricsManager, time);
+                   Time time,
+                   ApiVersions apiVersions) {
+        super(logContext, metadata, subscriptions, fetchConfig, new FetchBuffer(logContext), metricsManager, time, apiVersions);
         this.log = logContext.logger(Fetcher.class);
         this.client = client;
         this.fetchCollector = new FetchCollector<>(logContext,
diff --git a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/RequestManagers.java b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/RequestManagers.java
index b600a528164..8f9efe35e39 100644
--- a/clients/src/main/java/org/apache/kafka/clients/consumer/internals/RequestManagers.java
+++ b/clients/src/main/java/org/apache/kafka/clients/consumer/internals/RequestManagers.java
@@ -143,7 +143,8 @@ public class RequestManagers implements Closeable {
                         fetchConfig,
                         fetchBuffer,
                         fetchMetricsManager,
-                        networkClientDelegate);
+                        networkClientDelegate,
+                        apiVersions);
                 final TopicMetadataRequestManager topic = new TopicMetadataRequestManager(
                         logContext,
                         config);
diff --git a/clients/src/main/java/org/apache/kafka/clients/producer/internals/RecordAccumulator.java b/clients/src/main/java/org/apache/kafka/clients/producer/internals/RecordAccumulator.java
index 45332dff391..887e789edfc 100644
--- a/clients/src/main/java/org/apache/kafka/clients/producer/internals/RecordAccumulator.java
+++ b/clients/src/main/java/org/apache/kafka/clients/producer/internals/RecordAccumulator.java
@@ -807,12 +807,18 @@ public class RecordAccumulator {
     private boolean shouldBackoff(boolean hasLeaderChanged, final ProducerBatch batch, final long waitedTimeMs) {
         boolean shouldWaitMore = batch.attempts() > 0 && waitedTimeMs < retryBackoff.backoff(batch.attempts() - 1);
         boolean shouldBackoff = !hasLeaderChanged && shouldWaitMore;
-        if (shouldBackoff) {
-            log.trace(
-                "For {}, will backoff", batch);
-        } else {
-            log.trace(
-                "For {}, will not backoff, shouldWaitMore {}, hasLeaderChanged {}", batch, shouldWaitMore, hasLeaderChanged);
+        if (log.isTraceEnabled()) {
+            if (shouldBackoff) {
+                log.trace(
+                    "For {}, will backoff", batch);
+            } else {
+                log.trace(
+                    "For {}, will not backoff, shouldWaitMore {}, hasLeaderChanged {}", batch,
+                    shouldWaitMore, hasLeaderChanged);
+            }
+        } else if (log.isDebugEnabled() && hasLeaderChanged) {
+            // Add less-verbose log at DEBUG.
+            log.debug("For {}, leader has changed, hence skipping backoff.", batch);
         }
         return shouldBackoff;
     }
diff --git a/clients/src/main/java/org/apache/kafka/clients/producer/internals/Sender.java b/clients/src/main/java/org/apache/kafka/clients/producer/internals/Sender.java
index 1214df496f5..57889b2591e 100644
--- a/clients/src/main/java/org/apache/kafka/clients/producer/internals/Sender.java
+++ b/clients/src/main/java/org/apache/kafka/clients/producer/internals/Sender.java
@@ -16,6 +16,10 @@
  */
 package org.apache.kafka.clients.producer.internals;
 
+import static org.apache.kafka.common.requests.ProduceResponse.INVALID_OFFSET;
+
+import java.util.Optional;
+import java.util.Set;
 import org.apache.kafka.clients.ApiVersions;
 import org.apache.kafka.clients.ClientRequest;
 import org.apache.kafka.clients.ClientResponse;
@@ -30,7 +34,9 @@ import org.apache.kafka.common.Node;
 import org.apache.kafka.common.TopicPartition;
 import org.apache.kafka.common.errors.AuthenticationException;
 import org.apache.kafka.common.errors.ClusterAuthorizationException;
+import org.apache.kafka.common.errors.FencedLeaderEpochException;
 import org.apache.kafka.common.errors.InvalidMetadataException;
+import org.apache.kafka.common.errors.NotLeaderOrFollowerException;
 import org.apache.kafka.common.errors.RetriableException;
 import org.apache.kafka.common.errors.TimeoutException;
 import org.apache.kafka.common.errors.TopicAuthorizationException;
@@ -582,18 +588,18 @@ public class Sender implements Runnable {
                 requestHeader, response.destination());
             for (ProducerBatch batch : batches.values())
                 completeBatch(batch, new ProduceResponse.PartitionResponse(Errors.REQUEST_TIMED_OUT, String.format("Disconnected from node %s due to timeout", response.destination())),
-                        correlationId, now);
+                        correlationId, now, null);
         } else if (response.wasDisconnected()) {
             log.trace("Cancelled request with header {} due to node {} being disconnected",
                 requestHeader, response.destination());
             for (ProducerBatch batch : batches.values())
                 completeBatch(batch, new ProduceResponse.PartitionResponse(Errors.NETWORK_EXCEPTION, String.format("Disconnected from node %s", response.destination())),
-                        correlationId, now);
+                        correlationId, now, null);
         } else if (response.versionMismatch() != null) {
             log.warn("Cancelled request {} due to a version mismatch with node {}",
                     response, response.destination(), response.versionMismatch());
             for (ProducerBatch batch : batches.values())
-                completeBatch(batch, new ProduceResponse.PartitionResponse(Errors.UNSUPPORTED_VERSION), correlationId, now);
+                completeBatch(batch, new ProduceResponse.PartitionResponse(Errors.UNSUPPORTED_VERSION), correlationId, now, null);
         } else {
             log.trace("Received produce response from node {} with correlation id {}", response.destination(), correlationId);
             // if we have a response, parse it
@@ -601,26 +607,45 @@ public class Sender implements Runnable {
                 // Sender should exercise PartitionProduceResponse rather than ProduceResponse.PartitionResponse
                 // https://issues.apache.org/jira/browse/KAFKA-10696
                 ProduceResponse produceResponse = (ProduceResponse) response.responseBody();
+                // This will be set by completeBatch.
+                Map<TopicPartition, Metadata.LeaderIdAndEpoch> partitionsWithUpdatedLeaderInfo = new HashMap<>();
                 produceResponse.data().responses().forEach(r -> r.partitionResponses().forEach(p -> {
                     TopicPartition tp = new TopicPartition(r.name(), p.index());
                     ProduceResponse.PartitionResponse partResp = new ProduceResponse.PartitionResponse(
                             Errors.forCode(p.errorCode()),
                             p.baseOffset(),
+                            INVALID_OFFSET,
                             p.logAppendTimeMs(),
                             p.logStartOffset(),
                             p.recordErrors()
                                 .stream()
                                 .map(e -> new ProduceResponse.RecordError(e.batchIndex(), e.batchIndexErrorMessage()))
                                 .collect(Collectors.toList()),
-                            p.errorMessage());
+                            p.errorMessage(),
+                            p.currentLeader());
                     ProducerBatch batch = batches.get(tp);
-                    completeBatch(batch, partResp, correlationId, now);
+                    completeBatch(batch, partResp, correlationId, now, partitionsWithUpdatedLeaderInfo);
                 }));
+
+                if (!partitionsWithUpdatedLeaderInfo.isEmpty()) {
+                    List<Node> leaderNodes = produceResponse.data().nodeEndpoints().stream()
+                        .map(e -> new Node(e.nodeId(), e.host(), e.port(), e.rack()))
+                        .filter(e -> !e.equals(Node.noNode()))
+                        .collect(
+                            Collectors.toList());
+                    Set<TopicPartition> updatedPartitions = metadata.updatePartitionLeadership(partitionsWithUpdatedLeaderInfo, leaderNodes);
+                    if (log.isTraceEnabled()) {
+                        updatedPartitions.forEach(
+                            part -> log.debug("For {} leader was updated.", part)
+                        );
+                    }
+                }
+
                 this.sensors.recordLatency(response.destination(), response.requestLatencyMs());
             } else {
                 // this is the acks = 0 case, just complete all requests
                 for (ProducerBatch batch : batches.values()) {
-                    completeBatch(batch, new ProduceResponse.PartitionResponse(Errors.NONE), correlationId, now);
+                    completeBatch(batch, new ProduceResponse.PartitionResponse(Errors.NONE), correlationId, now, null);
                 }
             }
         }
@@ -633,9 +658,10 @@ public class Sender implements Runnable {
      * @param response The produce response
      * @param correlationId The correlation id for the request
      * @param now The current POSIX timestamp in milliseconds
+     * @param partitionsWithUpdatedLeaderInfo This will be populated with partitions that have updated leader info.
      */
     private void completeBatch(ProducerBatch batch, ProduceResponse.PartitionResponse response, long correlationId,
-                               long now) {
+                               long now, Map<TopicPartition, Metadata.LeaderIdAndEpoch> partitionsWithUpdatedLeaderInfo) {
         Errors error = response.error;
 
         if (error == Errors.MESSAGE_TOO_LARGE && batch.recordCount > 1 && !batch.isDone() &&
@@ -685,6 +711,14 @@ public class Sender implements Runnable {
                             "to request metadata update now", batch.topicPartition,
                             error.exception(response.errorMessage).toString());
                 }
+                if (error.exception() instanceof NotLeaderOrFollowerException || error.exception() instanceof FencedLeaderEpochException) {
+                    log.debug("For {}, received error {}, with leaderIdAndEpoch {}", batch.topicPartition, error, response.currentLeader);
+                    if (partitionsWithUpdatedLeaderInfo != null
+                        && (response.currentLeader.leaderId() != -1 && response.currentLeader.leaderEpoch() != -1)) {
+                        partitionsWithUpdatedLeaderInfo.put(batch.topicPartition, new Metadata.LeaderIdAndEpoch(
+                            Optional.of(response.currentLeader.leaderId()), Optional.of(response.currentLeader.leaderEpoch())));
+                    }
+                }
                 metadata.requestUpdate(false);
             }
         } else {
diff --git a/clients/src/main/java/org/apache/kafka/common/requests/FetchResponse.java b/clients/src/main/java/org/apache/kafka/common/requests/FetchResponse.java
index cd177945830..919c0f9f77a 100644
--- a/clients/src/main/java/org/apache/kafka/common/requests/FetchResponse.java
+++ b/clients/src/main/java/org/apache/kafka/common/requests/FetchResponse.java
@@ -16,6 +16,7 @@
  */
 package org.apache.kafka.common.requests;
 
+import org.apache.kafka.common.Node;
 import org.apache.kafka.common.TopicPartition;
 import org.apache.kafka.common.TopicIdPartition;
 import org.apache.kafka.common.Uuid;
@@ -29,6 +30,7 @@ import org.apache.kafka.common.record.Records;
 
 import java.nio.ByteBuffer;
 import java.util.ArrayList;
+import java.util.Collections;
 import java.util.HashMap;
 import java.util.Iterator;
 import java.util.LinkedHashMap;
@@ -170,7 +172,7 @@ public class FetchResponse extends AbstractResponse {
                              FetchResponseData.PartitionData>> partIterator) {
         // Since the throttleTimeMs and metadata field sizes are constant and fixed, we can
         // use arbitrary values here without affecting the result.
-        FetchResponseData data = toMessage(Errors.NONE, 0, INVALID_SESSION_ID, partIterator);
+        FetchResponseData data = toMessage(Errors.NONE, 0, INVALID_SESSION_ID, partIterator, Collections.emptyList());
         ObjectSerializationCache cache = new ObjectSerializationCache();
         return 4 + data.size(cache, version);
     }
@@ -238,7 +240,16 @@ public class FetchResponse extends AbstractResponse {
                                    int throttleTimeMs,
                                    int sessionId,
                                    LinkedHashMap<TopicIdPartition, FetchResponseData.PartitionData> responseData) {
-        return new FetchResponse(toMessage(error, throttleTimeMs, sessionId, responseData.entrySet().iterator()));
+        return new FetchResponse(toMessage(error, throttleTimeMs, sessionId, responseData.entrySet().iterator(), Collections.emptyList()));
+    }
+
+    // TODO: remove as a part of KAFKA-12410
+    public static FetchResponse of(Errors error,
+                                   int throttleTimeMs,
+                                   int sessionId,
+                                   LinkedHashMap<TopicIdPartition, FetchResponseData.PartitionData> responseData,
+                                   List<Node> nodeEndpoints) {
+        return new FetchResponse(toMessage(error, throttleTimeMs, sessionId, responseData.entrySet().iterator(), nodeEndpoints));
     }
 
     private static boolean matchingTopic(FetchResponseData.FetchableTopicResponse previousTopic, TopicIdPartition currentTopic) {
@@ -254,7 +265,8 @@ public class FetchResponse extends AbstractResponse {
     private static FetchResponseData toMessage(Errors error,
                                                int throttleTimeMs,
                                                int sessionId,
-                                               Iterator<Map.Entry<TopicIdPartition, FetchResponseData.PartitionData>> partIterator) {
+                                               Iterator<Map.Entry<TopicIdPartition, FetchResponseData.PartitionData>> partIterator,
+                                               List<Node> nodeEndpoints) {
         List<FetchResponseData.FetchableTopicResponse> topicResponseList = new ArrayList<>();
         while (partIterator.hasNext()) {
             Map.Entry<TopicIdPartition, FetchResponseData.PartitionData> entry = partIterator.next();
@@ -276,11 +288,17 @@ public class FetchResponse extends AbstractResponse {
                     .setPartitions(partitionResponses));
             }
         }
-
-        return new FetchResponseData()
-            .setThrottleTimeMs(throttleTimeMs)
-            .setErrorCode(error.code())
-            .setSessionId(sessionId)
-            .setResponses(topicResponseList);
+        FetchResponseData data = new FetchResponseData();
+        // KafkaApis should only pass in node endpoints on error, otherwise this should be an empty list
+        nodeEndpoints.forEach(endpoint -> data.nodeEndpoints().add(
+                new FetchResponseData.NodeEndpoint()
+                        .setNodeId(endpoint.id())
+                        .setHost(endpoint.host())
+                        .setPort(endpoint.port())
+                        .setRack(endpoint.rack())));
+        return data.setThrottleTimeMs(throttleTimeMs)
+                .setErrorCode(error.code())
+                .setSessionId(sessionId)
+                .setResponses(topicResponseList);
     }
 }
\ No newline at end of file
diff --git a/clients/src/main/java/org/apache/kafka/common/requests/ProduceResponse.java b/clients/src/main/java/org/apache/kafka/common/requests/ProduceResponse.java
index 6bb17128df7..a8c2a801e4c 100644
--- a/clients/src/main/java/org/apache/kafka/common/requests/ProduceResponse.java
+++ b/clients/src/main/java/org/apache/kafka/common/requests/ProduceResponse.java
@@ -18,6 +18,7 @@ package org.apache.kafka.common.requests;
 
 import org.apache.kafka.common.TopicPartition;
 import org.apache.kafka.common.message.ProduceResponseData;
+import org.apache.kafka.common.message.ProduceResponseData.LeaderIdAndEpoch;
 import org.apache.kafka.common.protocol.ApiKeys;
 import org.apache.kafka.common.protocol.ByteBufferAccessor;
 import org.apache.kafka.common.protocol.Errors;
@@ -65,6 +66,8 @@ public class ProduceResponse extends AbstractResponse {
 
     /**
      * Constructor for Version 0
+     * This is deprecated in favor of using the ProduceResponseData constructor, KafkaApis should switch to that
+     * in KAFKA-10730
      * @param responses Produced data grouped by topic-partition
      */
     @Deprecated
@@ -73,7 +76,8 @@ public class ProduceResponse extends AbstractResponse {
     }
 
     /**
-     * Constructor for the latest version
+     * This is deprecated in favor of using the ProduceResponseData constructor, KafkaApis should switch to that
+     * in KAFKA-10730
      * @param responses Produced data grouped by topic-partition
      * @param throttleTimeMs Time in milliseconds the response was throttled
      */
@@ -98,6 +102,7 @@ public class ProduceResponse extends AbstractResponse {
                     .setLogAppendTimeMs(response.logAppendTime)
                     .setErrorMessage(response.errorMessage)
                     .setErrorCode(response.error.code())
+                    .setCurrentLeader(response.currentLeader != null ? response.currentLeader : new LeaderIdAndEpoch())
                     .setRecordErrors(response.recordErrors
                         .stream()
                         .map(e -> new ProduceResponseData.BatchIndexAndErrorMessage()
@@ -138,6 +143,7 @@ public class ProduceResponse extends AbstractResponse {
         public long logStartOffset;
         public List<RecordError> recordErrors;
         public String errorMessage;
+        public ProduceResponseData.LeaderIdAndEpoch currentLeader;
 
         public PartitionResponse(Errors error) {
             this(error, INVALID_OFFSET, RecordBatch.NO_TIMESTAMP, INVALID_OFFSET);
@@ -156,7 +162,11 @@ public class ProduceResponse extends AbstractResponse {
         }
 
         public PartitionResponse(Errors error, long baseOffset, long logAppendTime, long logStartOffset, List<RecordError> recordErrors, String errorMessage) {
-            this(error, baseOffset, INVALID_OFFSET, logAppendTime, logStartOffset, recordErrors, errorMessage);
+            this(error, baseOffset, INVALID_OFFSET, logAppendTime, logStartOffset, recordErrors, errorMessage, new ProduceResponseData.LeaderIdAndEpoch());
+        }
+
+        public PartitionResponse(Errors error, long baseOffset, long lastOffset, long logAppendTime, long logStartOffset, List<RecordError> recordErrors, String errorMessage) {
+            this(error, baseOffset, lastOffset, logAppendTime, logStartOffset, recordErrors, errorMessage, new ProduceResponseData.LeaderIdAndEpoch());
         }
 
         public PartitionResponse(
@@ -166,7 +176,8 @@ public class ProduceResponse extends AbstractResponse {
             long logAppendTime,
             long logStartOffset,
             List<RecordError> recordErrors,
-            String errorMessage
+            String errorMessage,
+            ProduceResponseData.LeaderIdAndEpoch currentLeader
         ) {
             this.error = error;
             this.baseOffset = baseOffset;
@@ -175,6 +186,7 @@ public class ProduceResponse extends AbstractResponse {
             this.logStartOffset = logStartOffset;
             this.recordErrors = recordErrors;
             this.errorMessage = errorMessage;
+            this.currentLeader = currentLeader;
         }
 
         @Override
@@ -188,12 +200,13 @@ public class ProduceResponse extends AbstractResponse {
                     logStartOffset == that.logStartOffset &&
                     error == that.error &&
                     Objects.equals(recordErrors, that.recordErrors) &&
-                    Objects.equals(errorMessage, that.errorMessage);
+                    Objects.equals(errorMessage, that.errorMessage) &&
+                    Objects.equals(currentLeader, that.currentLeader);
         }
 
         @Override
         public int hashCode() {
-            return Objects.hash(error, baseOffset, lastOffset, logAppendTime, logStartOffset, recordErrors, errorMessage);
+            return Objects.hash(error, baseOffset, lastOffset, logAppendTime, logStartOffset, recordErrors, errorMessage, currentLeader);
         }
 
         @Override
@@ -212,6 +225,8 @@ public class ProduceResponse extends AbstractResponse {
             b.append(logStartOffset);
             b.append(", recordErrors: ");
             b.append(recordErrors);
+            b.append(", currentLeader: ");
+            b.append(currentLeader);
             b.append(", errorMessage: ");
             if (errorMessage != null) {
                 b.append(errorMessage);
diff --git a/clients/src/test/java/org/apache/kafka/clients/MetadataCacheTest.java b/clients/src/test/java/org/apache/kafka/clients/MetadataCacheTest.java
index 387643c3c5f..9c50ef31161 100644
--- a/clients/src/test/java/org/apache/kafka/clients/MetadataCacheTest.java
+++ b/clients/src/test/java/org/apache/kafka/clients/MetadataCacheTest.java
@@ -20,6 +20,7 @@ import org.apache.kafka.common.Cluster;
 import org.apache.kafka.common.Node;
 import org.apache.kafka.common.PartitionInfo;
 import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.Uuid;
 import org.apache.kafka.common.protocol.Errors;
 import org.apache.kafka.common.requests.MetadataResponse;
 import org.junit.jupiter.api.Test;
@@ -83,4 +84,69 @@ public class MetadataCacheTest {
         assertEquals(nodesById.get(7), replicas.get(7));
     }
 
+    @Test
+    public void testMergeWithThatPreExistingPartitionIsRetainedPostMerge() {
+        // Set up a Metadata Cache with 1 topic partition belong topic1.
+        String topic1 = "topic1";
+        TopicPartition topic1Partition = new TopicPartition(topic1, 1);
+        MetadataResponse.PartitionMetadata partitionMetadata1 = new MetadataResponse.PartitionMetadata(
+            Errors.NONE,
+            topic1Partition,
+            Optional.of(5),
+            Optional.of(10),
+            Arrays.asList(5, 6, 7),
+            Arrays.asList(5, 6, 7),
+            Collections.emptyList());
+
+        Map<Integer, Node> nodesById = new HashMap<>();
+        nodesById.put(6, new Node(6, "localhost", 2077));
+        nodesById.put(7, new Node(7, "localhost", 2078));
+        nodesById.put(8, new Node(8, "localhost", 2079));
+
+        Map<String, Uuid> topicsIds = new HashMap<>();
+        Uuid topic1Id = Uuid.randomUuid();
+        topicsIds.put(topic1Partition.topic(), topic1Id);
+
+        MetadataCache cache = new MetadataCache("clusterId",
+            nodesById,
+            Collections.singleton(partitionMetadata1),
+            Collections.emptySet(),
+            Collections.emptySet(),
+            Collections.emptySet(),
+            null,
+            topicsIds);
+
+        Cluster cluster = cache.cluster();
+        assertEquals(1, cluster.topics().size());
+        assertEquals(topic1Id, cluster.topicId(topic1));
+        assertEquals(topic1, cluster.topicName(topic1Id));
+
+        // Merge the metadata cache with a new partition topic2Partition.
+        String topic2 = "topic2";
+        TopicPartition topic2Partition = new TopicPartition(topic2, 2);
+        MetadataResponse.PartitionMetadata partitionMetadata2 = new MetadataResponse.PartitionMetadata(
+            Errors.NONE,
+            topic2Partition,
+            Optional.of(5),
+            Optional.of(10),
+            Arrays.asList(5, 6, 7),
+            Arrays.asList(5, 6, 7),
+            Collections.emptyList());
+        topicsIds = new HashMap<>();
+        Uuid topic2Id = Uuid.randomUuid();
+        topicsIds.put(topic2Partition.topic(), topic2Id);
+        cache = cache.mergeWith("clusterId", nodesById, Collections.singleton(partitionMetadata2),
+            Collections.emptySet(), Collections.emptySet(), Collections.emptySet(), null, topicsIds, (topic, retain) -> true);
+        cluster = cache.cluster();
+
+        // Verify topic1Partition is retained & topic2Partition is added.
+        assertEquals(2, cluster.topics().size());
+
+        assertEquals(topic1Id, cluster.topicId(topic1));
+        assertEquals(topic1, cluster.topicName(topic1Id));
+
+        assertEquals(topic2Id, cluster.topicId(topic2));
+        assertEquals(topic2, cluster.topicName(topic2Id));
+    }
+
 }
diff --git a/clients/src/test/java/org/apache/kafka/clients/MetadataTest.java b/clients/src/test/java/org/apache/kafka/clients/MetadataTest.java
index 9cf6455f403..8f99b45c1bf 100644
--- a/clients/src/test/java/org/apache/kafka/clients/MetadataTest.java
+++ b/clients/src/test/java/org/apache/kafka/clients/MetadataTest.java
@@ -16,7 +16,10 @@
  */
 package org.apache.kafka.clients;
 
+import java.util.ArrayList;
+import java.util.stream.Collectors;
 import org.apache.kafka.common.Cluster;
+import org.apache.kafka.common.ClusterResourceListener;
 import org.apache.kafka.common.Node;
 import org.apache.kafka.common.TopicPartition;
 import org.apache.kafka.common.Uuid;
@@ -34,7 +37,9 @@ import org.apache.kafka.common.protocol.Errors;
 import org.apache.kafka.common.protocol.MessageUtil;
 import org.apache.kafka.common.requests.MetadataRequest;
 import org.apache.kafka.common.requests.MetadataResponse;
+import org.apache.kafka.common.requests.MetadataResponse.PartitionMetadata;
 import org.apache.kafka.common.requests.RequestTestUtils;
+import org.apache.kafka.common.requests.RequestTestUtils.PartitionMetadataSupplier;
 import org.apache.kafka.common.utils.LogContext;
 import org.apache.kafka.common.utils.MockTime;
 import org.apache.kafka.common.utils.Time;
@@ -54,6 +59,7 @@ import java.util.Objects;
 import java.util.Optional;
 import java.util.Set;
 import java.util.concurrent.atomic.AtomicReference;
+import org.mockito.Mockito;
 
 import static org.apache.kafka.test.TestUtils.assertOptional;
 import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -62,6 +68,10 @@ import static org.junit.jupiter.api.Assertions.assertNotNull;
 import static org.junit.jupiter.api.Assertions.assertNull;
 import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
 
 public class MetadataTest {
 
@@ -1057,4 +1067,156 @@ public class MetadataTest {
         assertEquals(Uuid.ZERO_UUID, cluster.topicId("validTopic1"));
     }
 
+    @Test
+    public void testUpdatePartitionLeadership() {
+        Time time = new MockTime();
+
+        // Setup metadata with initial set of 2 partitions, 1 each across topics, with 5 nodes.
+        // Also setup, 1 invalid topic, 1 unauthorized topic, 1 internal topic.
+        int numNodes = 5;
+        metadata = new Metadata(refreshBackoffMs, refreshBackoffMaxMs, metadataExpireMs, new LogContext(), new ClusterResourceListeners());
+        ClusterResourceListener mockListener = Mockito.mock(ClusterResourceListener.class);
+        metadata.addClusterUpdateListener(mockListener);
+
+        String topic1 = "topic1";
+        TopicPartition partition1 = new TopicPartition(topic1, 0);
+        PartitionMetadata part1Metadata = new PartitionMetadata(Errors.NONE, partition1, Optional.of(1), Optional.of(100), Arrays.asList(1, 2), Arrays.asList(1, 2), Arrays.asList(3));
+        Uuid topic1Id = Uuid.randomUuid();
+
+        String topic2 = "topic2";
+        TopicPartition partition2 = new TopicPartition(topic2, 0);
+        PartitionMetadata part2Metadata = new PartitionMetadata(Errors.NONE, partition2, Optional.of(2), Optional.of(200), Arrays.asList(2, 3), Arrays.asList(2, 3), Arrays.asList(1));
+        Uuid topic2Id = Uuid.randomUuid();
+
+        Set<String> internalTopics = Collections.singleton(Topic.GROUP_METADATA_TOPIC_NAME);
+        TopicPartition internalPart = new TopicPartition(Topic.GROUP_METADATA_TOPIC_NAME, 0);
+        Uuid internalTopicId = Uuid.randomUuid();
+        PartitionMetadata internalTopicMetadata = new PartitionMetadata(Errors.NONE, internalPart, Optional.of(2), Optional.of(200), Arrays.asList(2, 3), Arrays.asList(2, 3), Arrays.asList(1));
+
+        Map<String, Uuid> topicIds = new HashMap<>();
+        topicIds.put(topic1, topic1Id);
+        topicIds.put(topic2, topic2Id);
+        topicIds.put(internalTopics.iterator().next(), internalTopicId);
+
+        Map<String, Integer> topicPartitionCounts = new HashMap<>();
+        topicPartitionCounts.put(topic1, 1);
+        topicPartitionCounts.put(topic2, 1);
+        topicPartitionCounts.put(internalTopics.iterator().next(), 1);
+        PartitionMetadataSupplier metadataSupplier = (error, partition, leaderId, leaderEpoch, replicas, isr, offlineReplicas) -> {
+            if (partition.equals(partition1))
+                return part1Metadata;
+            else if (partition.equals(partition2))
+                return part2Metadata;
+            else if (partition.equals(internalPart))
+                return internalTopicMetadata;
+            throw new RuntimeException("Unexpected partition " + partition);
+        };
+
+        Map<String, Errors> errorCounts = new HashMap<>();
+        Set<String> invalidTopics = Collections.singleton("topic3");
+        errorCounts.put(invalidTopics.iterator().next(), Errors.INVALID_TOPIC_EXCEPTION);
+        Set<String> unauthorizedTopics = Collections.singleton("topic4");
+        errorCounts.put(unauthorizedTopics.iterator().next(), Errors.TOPIC_AUTHORIZATION_FAILED);
+
+        metadata.requestUpdate(true);
+        Metadata.MetadataRequestAndVersion versionAndBuilder = metadata.newMetadataRequestAndVersion(time.milliseconds());
+        assertFalse(versionAndBuilder.isPartialUpdate);
+        String clusterId = "kakfa-cluster";
+        metadata.update(versionAndBuilder.requestVersion,
+            RequestTestUtils.metadataUpdateWith(clusterId, numNodes, errorCounts, topicPartitionCounts, tp -> null, metadataSupplier, ApiKeys.METADATA.latestVersion(), topicIds),
+            false, time.milliseconds());
+        List<Node> nodes = new ArrayList<>();
+        nodes.addAll(metadata.fetch().nodes());
+        Node controller = metadata.fetch().controller();
+        assertEquals(numNodes, nodes.size());
+        assertFalse(metadata.updateRequested());
+        validateForUpdatePartitionLeadership(metadata, part1Metadata, part2Metadata, internalTopicMetadata, nodes, clusterId, unauthorizedTopics, invalidTopics, internalTopics, controller, topicIds);
+        // Since cluster metadata was updated, listener should be called.
+        verify(mockListener, times(1)).onUpdate(any());
+        Mockito.reset(mockListener);
+
+        // TEST1 updatePartially with updates should that should be ignored, leaving existing metadata unchanged.
+        Map<TopicPartition, Metadata.LeaderIdAndEpoch> updates = new HashMap<>();
+        // New leader info is empty/invalid.
+        updates.put(new TopicPartition(topic1, 999), new Metadata.LeaderIdAndEpoch(Optional.empty(), Optional.empty()));
+        // Leader's node is unknown
+        updates.put(partition2, new  Metadata.LeaderIdAndEpoch(Optional.of(99999), Optional.of(99999)));
+        // Partition missing from existing metadata
+        updates.put(new TopicPartition("topic_missing_from_existing_metadata", 1), new  Metadata.LeaderIdAndEpoch(Optional.of(0), Optional.of(99999)));
+        // New leader info is stale.
+        updates.put(partition1, new  Metadata.LeaderIdAndEpoch(part1Metadata.leaderId, Optional.of(part1Metadata.leaderEpoch.get() - 1)));
+        Set<TopicPartition> updatedTps = metadata.updatePartitionLeadership(updates, nodes);
+        assertTrue(updatedTps.isEmpty());
+        // Validate metadata is unchanged for partition1 & partition2
+        validateForUpdatePartitionLeadership(metadata, part1Metadata, part2Metadata, internalTopicMetadata, nodes, clusterId, unauthorizedTopics, invalidTopics, internalTopics, controller, topicIds);
+        // Since cluster metadata is unchanged, listener shouldn't be called.
+        verify(mockListener, never()).onUpdate(any());
+        Mockito.reset(mockListener);
+
+
+        //TEST2 updatePartitionLeadership with leadership-updates, where some updates should be ignored as in TEST1, update to partition1's leadership are to be applied, and no update to partition2(so remains at it is).
+        // Following updates to Nodes should happen, rest all nodes should remain unchanged.
+        // 1. New Node with id=999 is added.
+        // 2. Existing node with id=0 has host, port changed, so is updated.
+        Integer part1NewLeaderId = part1Metadata.leaderId.get() + 1;
+        Integer part1NewLeaderEpoch = part1Metadata.leaderEpoch.get() + 1;
+        updates.put(partition1, new Metadata.LeaderIdAndEpoch(Optional.of(part1NewLeaderId), Optional.of(part1NewLeaderEpoch)));
+        PartitionMetadata updatedPart1Metadata = new PartitionMetadata(part1Metadata.error, part1Metadata.topicPartition, Optional.of(part1NewLeaderId), Optional.of(part1NewLeaderEpoch), part1Metadata.replicaIds, part1Metadata.inSyncReplicaIds, part1Metadata.offlineReplicaIds);
+
+        Node newNode = new Node(999, "testhost", 99999, "testrack");
+        nodes.add(newNode);
+        int index = nodes.stream().filter(node -> node.id() == 0).findFirst().map(nodes::indexOf).orElse(-1);
+        Node existingNode = nodes.get(index);
+        Node updatedNode = new Node(existingNode.id(), "newhost", existingNode.port(), "newrack");
+        nodes.remove(index);
+        nodes.add(updatedNode);
+
+        updatedTps = metadata.updatePartitionLeadership(updates, nodes);
+
+        assertEquals(1, updatedTps.size());
+        assertEquals(part1Metadata.topicPartition, updatedTps.toArray()[0]);
+        // Validate metadata is changed for partition1, hosts are updated, everything else remains unchanged.
+        validateForUpdatePartitionLeadership(metadata, updatedPart1Metadata, part2Metadata, internalTopicMetadata, nodes, clusterId, unauthorizedTopics, invalidTopics, internalTopics, controller, topicIds);
+        // Since cluster metadata was updated, listener should be called.
+        verify(mockListener, times(1)).onUpdate(any());
+        Mockito.reset(mockListener);
+    }
+
+    /**
+     * For testUpdatePartially, validates that updatedMetadata is matching expected part1Metadata, part2Metadata, interalPartMetadata, nodes & more.
+     */
+    void validateForUpdatePartitionLeadership(Metadata updatedMetadata, PartitionMetadata part1Metadata, PartitionMetadata part2Metadata, PartitionMetadata internalPartMetadata,
+        List<Node> expectedNodes, String expectedClusterId, Set<String> expectedUnauthorisedTopics, Set<String> expectedInvalidTopics, Set<String> expectedInternalTopics,
+        Node expectedController, Map<String, Uuid> expectedTopicIds) {
+        Cluster updatedCluster = updatedMetadata.fetch();
+        assertEquals(updatedCluster.clusterResource().clusterId(), expectedClusterId);
+        assertEquals(new HashSet<>(expectedNodes), new HashSet<>(updatedCluster.nodes()));
+        assertEquals(3, updatedCluster.topics().size());
+        assertEquals(expectedInternalTopics, updatedCluster.internalTopics());
+        assertEquals(expectedInvalidTopics, updatedCluster.invalidTopics());
+        assertEquals(expectedUnauthorisedTopics, updatedCluster.unauthorizedTopics());
+        assertEquals(expectedController, updatedCluster.controller());
+        assertEquals(expectedTopicIds, updatedMetadata.topicIds());
+
+        Map<Integer, Node> nodeMap = expectedNodes.stream().collect(Collectors.toMap(e -> e.id(), e -> e));
+        for (PartitionMetadata partitionMetadata: Arrays.asList(part1Metadata, part2Metadata, internalPartMetadata)) {
+            TopicPartition tp = new TopicPartition(partitionMetadata.topic(), partitionMetadata.partition());
+
+            Metadata.LeaderAndEpoch expectedLeaderInfo = new Metadata.LeaderAndEpoch(Optional.of(nodeMap.get(partitionMetadata.leaderId.get())), partitionMetadata.leaderEpoch);
+            assertEquals(expectedLeaderInfo, updatedMetadata.currentLeader(tp));
+
+            // Compare the partition-metadata.
+            Optional<PartitionMetadata> optionalUpdatedMetadata = updatedMetadata.partitionMetadataIfCurrent(tp);
+            assertTrue(optionalUpdatedMetadata.isPresent());
+            PartitionMetadata updatedPartMetadata = optionalUpdatedMetadata.get();
+            assertEquals(partitionMetadata.topicPartition, updatedPartMetadata.topicPartition);
+            assertEquals(partitionMetadata.error, updatedPartMetadata.error);
+            assertEquals(partitionMetadata.leaderId, updatedPartMetadata.leaderId);
+            assertEquals(partitionMetadata.leaderEpoch, updatedPartMetadata.leaderEpoch);
+            assertEquals(partitionMetadata.replicaIds, updatedPartMetadata.replicaIds);
+            assertEquals(partitionMetadata.inSyncReplicaIds, updatedPartMetadata.inSyncReplicaIds);
+            assertEquals(partitionMetadata.offlineReplicaIds, partitionMetadata.offlineReplicaIds);
+        }
+    }
+
 }
diff --git a/clients/src/test/java/org/apache/kafka/clients/consumer/KafkaConsumerTest.java b/clients/src/test/java/org/apache/kafka/clients/consumer/KafkaConsumerTest.java
index 6a46b453191..b4c3dba56fb 100644
--- a/clients/src/test/java/org/apache/kafka/clients/consumer/KafkaConsumerTest.java
+++ b/clients/src/test/java/org/apache/kafka/clients/consumer/KafkaConsumerTest.java
@@ -2691,7 +2691,8 @@ public class KafkaConsumerTest {
                 fetchConfig,
                 new Deserializers<>(keyDeserializer, deserializer),
                 metricsManager,
-                time);
+                time,
+                new ApiVersions());
         OffsetFetcher offsetFetcher = new OffsetFetcher(loggerFactory,
                 consumerClient,
                 metadata,
diff --git a/clients/src/test/java/org/apache/kafka/clients/consumer/internals/ConsumerTestBuilder.java b/clients/src/test/java/org/apache/kafka/clients/consumer/internals/ConsumerTestBuilder.java
index 894f8305d02..b36f1958f7d 100644
--- a/clients/src/test/java/org/apache/kafka/clients/consumer/internals/ConsumerTestBuilder.java
+++ b/clients/src/test/java/org/apache/kafka/clients/consumer/internals/ConsumerTestBuilder.java
@@ -227,7 +227,8 @@ public class ConsumerTestBuilder implements Closeable {
                 fetchConfig,
                 fetchBuffer,
                 metricsManager,
-                networkClientDelegate));
+                networkClientDelegate,
+                apiVersions));
         this.topicMetadataRequestManager = spy(new TopicMetadataRequestManager(logContext,
                 config));
         this.requestManagers = new RequestManagers(logContext,
diff --git a/clients/src/test/java/org/apache/kafka/clients/consumer/internals/FetchRequestManagerTest.java b/clients/src/test/java/org/apache/kafka/clients/consumer/internals/FetchRequestManagerTest.java
index 88de3355472..e98ec1a3aad 100644
--- a/clients/src/test/java/org/apache/kafka/clients/consumer/internals/FetchRequestManagerTest.java
+++ b/clients/src/test/java/org/apache/kafka/clients/consumer/internals/FetchRequestManagerTest.java
@@ -3387,7 +3387,7 @@ public class FetchRequestManagerTest {
                                            FetchMetricsManager metricsManager,
                                            NetworkClientDelegate networkClientDelegate,
                                            FetchCollector<K, V> fetchCollector) {
-            super(logContext, time, metadata, subscriptions, fetchConfig, fetchBuffer, metricsManager, networkClientDelegate);
+            super(logContext, time, metadata, subscriptions, fetchConfig, fetchBuffer, metricsManager, networkClientDelegate, null);
             this.fetchCollector = fetchCollector;
         }
 
diff --git a/clients/src/test/java/org/apache/kafka/clients/consumer/internals/FetcherTest.java b/clients/src/test/java/org/apache/kafka/clients/consumer/internals/FetcherTest.java
index 81551b95239..978b0b6345e 100644
--- a/clients/src/test/java/org/apache/kafka/clients/consumer/internals/FetcherTest.java
+++ b/clients/src/test/java/org/apache/kafka/clients/consumer/internals/FetcherTest.java
@@ -92,6 +92,7 @@ import org.junit.jupiter.api.Test;
 import org.junit.jupiter.params.ParameterizedTest;
 import org.junit.jupiter.params.provider.Arguments;
 import org.junit.jupiter.params.provider.MethodSource;
+import org.junit.jupiter.params.provider.EnumSource;
 import org.mockito.ArgumentCaptor;
 
 import java.io.DataOutputStream;
@@ -2787,7 +2788,8 @@ public class FetcherTest {
                 fetchConfig,
                 deserializers,
                 metricsManager,
-                time) {
+                time,
+                apiVersions) {
             @Override
             protected FetchSessionHandler sessionHandler(int node) {
                 final FetchSessionHandler handler = super.sessionHandler(node);
@@ -3396,6 +3398,206 @@ public class FetcherTest {
         assertThrows(KafkaException.class, this::fetchRecords);
     }
 
+    /**
+     * Test the scenario that FetchResponse returns with an error indicating leadership change for the partition, but it
+     * does not contain new leader info(defined in KIP-951).
+     */
+    @ParameterizedTest
+    @EnumSource(value = Errors.class, names = {"FENCED_LEADER_EPOCH", "NOT_LEADER_OR_FOLLOWER"})
+    public void testWhenFetchResponseReturnsWithALeaderShipChangeErrorButNoNewLeaderInformation(Errors error) {
+        // The test runs with 2 partitions where 1 partition is fetched without errors, and 2nd partitions faces errors due to leadership changes.
+
+        buildFetcher(new MetricConfig(), OffsetResetStrategy.EARLIEST, new BytesDeserializer(),
+            new BytesDeserializer(),
+            Integer.MAX_VALUE, IsolationLevel.READ_UNCOMMITTED,
+            Duration.ofMinutes(5).toMillis());
+
+        // Setup so that fetcher is subscribed to tp0 & tp1, and metadata setup with tp0.
+        // assignFromUser(singleton(tp0));
+        subscriptions.assignFromUser(new HashSet<>(Arrays.asList(tp0, tp1)));
+        client.updateMetadata(
+            RequestTestUtils.metadataUpdateWithIds(2, singletonMap(topicName, 4),
+                tp -> validLeaderEpoch, topicIds, false));
+        Node tp0Leader = metadata.fetch().leaderFor(tp0);
+        Node tp1Leader = metadata.fetch().leaderFor(tp1);
+        Node nodeId0 = metadata.fetch().nodeById(0);
+        Cluster startingClusterMetadata = metadata.fetch();
+        subscriptions.seek(tp0, 0);
+        subscriptions.seek(tp1, 0);
+
+        // Setup preferred read replica to node=1 by doing a fetch for both partitions.
+        assertEquals(2, sendFetches());
+        assertFalse(fetcher.hasCompletedFetches());
+        client.prepareResponseFrom(fullFetchResponse(tidp0, this.records, Errors.NONE, 100L,
+            FetchResponse.INVALID_LAST_STABLE_OFFSET, 0, Optional.of(nodeId0.id())), tp0Leader);
+        client.prepareResponseFrom(fullFetchResponse(tidp1, this.records, Errors.NONE, 100L,
+            FetchResponse.INVALID_LAST_STABLE_OFFSET, 0, Optional.of(nodeId0.id())), tp1Leader);
+        consumerClient.poll(time.timer(0));
+        assertTrue(fetcher.hasCompletedFetches());
+
+        Map<TopicPartition, List<ConsumerRecord<byte[], byte[]>>> partitionRecords = fetchRecords();
+        assertTrue(partitionRecords.containsKey(tp0));
+        assertTrue(partitionRecords.containsKey(tp1));
+
+        // Verify that preferred read replica is set for both tp0 & tp1.
+        Node selected = fetcher.selectReadReplica(tp0, Node.noNode(), time.milliseconds());
+        assertEquals(nodeId0.id(), selected.id());
+        selected = fetcher.selectReadReplica(tp1, Node.noNode(), time.milliseconds());
+        assertEquals(nodeId0.id(), selected.id());
+
+        // Next fetch returns an error(due to leadership change) but new leader info is missing, for tp0.
+        // For tp1 fetch returns with no error.
+        assertEquals(1, sendFetches());
+        assertFalse(fetcher.hasCompletedFetches());
+        // Verify that metadata-update isn't requested
+        assertFalse(metadata.updateRequested());
+
+        LinkedHashMap<TopicIdPartition, FetchResponseData.PartitionData> partitions = new LinkedHashMap<>();
+        partitions.put(tidp0,
+                new FetchResponseData.PartitionData()
+                    .setPartitionIndex(tidp0.topicPartition().partition())
+                    .setErrorCode(error.code()));
+        partitions.put(tidp1,
+                new FetchResponseData.PartitionData()
+                    .setPartitionIndex(tidp1.topicPartition().partition())
+                    .setErrorCode(Errors.NONE.code())
+                    .setHighWatermark(100L)
+                    .setLastStableOffset(FetchResponse.INVALID_LAST_STABLE_OFFSET)
+                    .setLogStartOffset(0)
+                    .setRecords(nextRecords));
+        client.prepareResponseFrom(FetchResponse.of(Errors.NONE, 0, INVALID_SESSION_ID, partitions), nodeId0);
+        consumerClient.poll(time.timer(0));
+        partitionRecords = fetchRecords();
+        assertFalse(partitionRecords.containsKey(tp0));
+        assertTrue(partitionRecords.containsKey(tp1));
+
+        // Validate metadata is unchanged, as response has missing new leader info.
+        assertEquals(startingClusterMetadata, metadata.fetch());
+
+        // Validate metadata-update is requested due to the error for tp0.
+        assertTrue(metadata.updateRequested());
+
+        // Validate preferred-read-replica is cleared for tp0 due to the error.
+        assertEquals(Optional.empty(),
+            subscriptions.preferredReadReplica(tp0, time.milliseconds()));
+        // Validate preferred-read-replica is still set for tp1
+        assertEquals(Optional.of(nodeId0.id()),
+            subscriptions.preferredReadReplica(tp1, time.milliseconds()));
+
+        // Validate subscription is still valid & fetch-able for both tp0 & tp1. And tp0 points to original leader.
+        assertTrue(subscriptions.isFetchable(tp0));
+        Metadata.LeaderAndEpoch currentLeader = subscriptions.position(tp0).currentLeader;
+        assertEquals(tp0Leader.id(), currentLeader.leader.get().id());
+        assertEquals(validLeaderEpoch, currentLeader.epoch.get());
+        assertTrue(subscriptions.isFetchable(tp1));
+    }
+
+    /**
+     * Test the scenario that FetchResponse returns with an error indicating leadership change for the partition, along with
+     * new leader info(defined in KIP-951).
+     */
+    @ParameterizedTest
+    @EnumSource(value = Errors.class, names = {"FENCED_LEADER_EPOCH", "NOT_LEADER_OR_FOLLOWER"})
+    public void testWhenFetchResponseReturnsWithALeaderShipChangeErrorAndNewLeaderInformation(Errors error) {
+        // The test runs with 2 partitions where 1 partition is fetched without errors, and 2nd partitions faces errors due to leadership changes.
+
+        buildFetcher(new MetricConfig(), OffsetResetStrategy.EARLIEST, new BytesDeserializer(),
+            new BytesDeserializer(),
+            Integer.MAX_VALUE, IsolationLevel.READ_UNCOMMITTED,
+            Duration.ofMinutes(5).toMillis());
+
+        // Setup so that fetcher is subscribed to tp0 & tp1, and metadata setup with tp0.
+        // assignFromUser(singleton(tp0));
+        subscriptions.assignFromUser(new HashSet<>(Arrays.asList(tp0, tp1)));
+        client.updateMetadata(
+            RequestTestUtils.metadataUpdateWithIds(2, singletonMap(topicName, 4),
+                tp -> validLeaderEpoch, topicIds, false));
+        Node tp0Leader = metadata.fetch().leaderFor(tp0);
+        Node tp1Leader = metadata.fetch().leaderFor(tp1);
+        Node nodeId0 = metadata.fetch().nodeById(0);
+        Cluster startingClusterMetadata = metadata.fetch();
+        subscriptions.seek(tp0, 0);
+        subscriptions.seek(tp1, 0);
+
+        // Setup preferred read replica to node=1 by doing a fetch for both partitions.
+        assertEquals(2, sendFetches());
+        assertFalse(fetcher.hasCompletedFetches());
+        client.prepareResponseFrom(fullFetchResponse(tidp0, this.records, Errors.NONE, 100L,
+            FetchResponse.INVALID_LAST_STABLE_OFFSET, 0, Optional.of(nodeId0.id())), tp0Leader);
+        client.prepareResponseFrom(fullFetchResponse(tidp1, this.records, Errors.NONE, 100L,
+            FetchResponse.INVALID_LAST_STABLE_OFFSET, 0, Optional.of(nodeId0.id())), tp1Leader);
+        consumerClient.poll(time.timer(0));
+        assertTrue(fetcher.hasCompletedFetches());
+
+        Map<TopicPartition, List<ConsumerRecord<byte[], byte[]>>> partitionRecords = fetchRecords();
+        assertTrue(partitionRecords.containsKey(tp0));
+        assertTrue(partitionRecords.containsKey(tp1));
+
+        // Verify that preferred read replica is set for both tp0 & tp1.
+        Node selected = fetcher.selectReadReplica(tp0, Node.noNode(), time.milliseconds());
+        assertEquals(nodeId0.id(), selected.id());
+        selected = fetcher.selectReadReplica(tp1, Node.noNode(), time.milliseconds());
+        assertEquals(nodeId0.id(), selected.id());
+
+        // Next fetch returns an error(due to leadership change) and new leader info is returned. The new leader is a new node, id = 999.
+        // For tp1 fetch returns with no error.
+        assertEquals(1, sendFetches());
+        assertFalse(fetcher.hasCompletedFetches());
+        // Verify that metadata-update isn't requested
+        assertFalse(metadata.updateRequested());
+
+        LinkedHashMap<TopicIdPartition, FetchResponseData.PartitionData> partitions = new LinkedHashMap<>();
+        Node newNode = new Node(999, "newnode", 999, "newrack");
+        FetchResponseData.PartitionData tp0Data = new FetchResponseData.PartitionData()
+            .setPartitionIndex(tidp0.topicPartition().partition())
+            .setErrorCode(error.code());
+        tp0Data.currentLeader().setLeaderId(newNode.id());
+        int tp0NewLeaderEpoch = validLeaderEpoch + 100;
+        tp0Data.currentLeader().setLeaderEpoch(tp0NewLeaderEpoch);
+        partitions.put(tidp0, tp0Data);
+        partitions.put(tidp1,
+            new FetchResponseData.PartitionData()
+                .setPartitionIndex(tidp1.topicPartition().partition())
+                .setErrorCode(Errors.NONE.code())
+                .setHighWatermark(100L)
+                .setLastStableOffset(FetchResponse.INVALID_LAST_STABLE_OFFSET)
+                .setLogStartOffset(0)
+                .setRecords(nextRecords));
+        client.prepareResponseFrom(FetchResponse.of(Errors.NONE, 0, INVALID_SESSION_ID, partitions, singletonList(newNode)), nodeId0);
+        consumerClient.poll(time.timer(0));
+        partitionRecords = fetchRecords();
+        assertFalse(partitionRecords.containsKey(tp0));
+        assertTrue(partitionRecords.containsKey(tp1));
+
+        // Validate metadata is changed, as previous FetchResponse had new leader info for tp0.
+        assertNotEquals(startingClusterMetadata, metadata.fetch());
+        // Validate new-node(id=999) is part of the metadata
+        assertEquals(newNode, metadata.fetch().nodeById(999));
+        // Validate metadata returns the new leader info for tp0.
+        Metadata.LeaderAndEpoch currentLeaderTp0 = metadata.currentLeader(tp0);
+        assertEquals(Optional.of(newNode), currentLeaderTp0.leader);
+        assertEquals(Optional.of(tp0NewLeaderEpoch), currentLeaderTp0.epoch);
+
+        // Validate metadata-update is requested due to the error for tp0.
+        assertTrue(metadata.updateRequested());
+
+        // Validate preferred-read-replica is cleared for tp0.
+        assertEquals(Optional.empty(),
+            subscriptions.preferredReadReplica(tp0, time.milliseconds()));
+        // Validate preferred-read-replica is still set for tp1
+        assertEquals(Optional.of(nodeId0.id()),
+            subscriptions.preferredReadReplica(tp1, time.milliseconds()));
+
+        // Validate subscription is valid & fetch-able, and points to the new leader.
+        assertTrue(subscriptions.isFetchable(tp0));
+        Metadata.LeaderAndEpoch currentLeader = subscriptions.position(tp0).currentLeader;
+        assertEquals(newNode.id(), currentLeader.leader.get().id());
+        assertEquals(tp0NewLeaderEpoch, currentLeader.epoch.get());
+
+        // Validate subscription is still valid & fetch-able for tp1.
+        assertTrue(subscriptions.isFetchable(tp1));
+    }
+
     private OffsetsForLeaderEpochResponse prepareOffsetsForLeaderEpochResponse(
         TopicPartition topicPartition,
         Errors error,
@@ -3589,7 +3791,8 @@ public class FetcherTest {
                 fetchConfig,
                 new Deserializers<>(keyDeserializer, valueDeserializer),
                 metricsManager,
-                time));
+                time,
+                apiVersions));
         offsetFetcher = new OffsetFetcher(logContext,
                 consumerClient,
                 metadata,
diff --git a/clients/src/test/java/org/apache/kafka/clients/consumer/internals/OffsetFetcherTest.java b/clients/src/test/java/org/apache/kafka/clients/consumer/internals/OffsetFetcherTest.java
index a118b20297a..a92c4ede8a8 100644
--- a/clients/src/test/java/org/apache/kafka/clients/consumer/internals/OffsetFetcherTest.java
+++ b/clients/src/test/java/org/apache/kafka/clients/consumer/internals/OffsetFetcherTest.java
@@ -1263,7 +1263,8 @@ public class OffsetFetcherTest {
                 fetchConfig,
                 new Deserializers<>(new ByteArrayDeserializer(), new ByteArrayDeserializer()),
                 new FetchMetricsManager(metrics, metricsRegistry),
-                time);
+                time,
+                apiVersions);
 
         assignFromUser(singleton(tp0));
 
diff --git a/clients/src/test/java/org/apache/kafka/clients/producer/internals/SenderTest.java b/clients/src/test/java/org/apache/kafka/clients/producer/internals/SenderTest.java
index 92ef4d18917..a524f2f78dc 100644
--- a/clients/src/test/java/org/apache/kafka/clients/producer/internals/SenderTest.java
+++ b/clients/src/test/java/org/apache/kafka/clients/producer/internals/SenderTest.java
@@ -19,6 +19,7 @@ package org.apache.kafka.clients.producer.internals;
 import org.apache.kafka.clients.ApiVersions;
 import org.apache.kafka.clients.ClientRequest;
 import org.apache.kafka.clients.ClientResponse;
+import org.apache.kafka.clients.Metadata;
 import org.apache.kafka.clients.MockClient;
 import org.apache.kafka.clients.NetworkClient;
 import org.apache.kafka.clients.NodeApiVersions;
@@ -112,6 +113,7 @@ import java.util.concurrent.atomic.AtomicReference;
 import static org.apache.kafka.clients.producer.internals.ProducerTestUtils.runUntil;
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
 import static org.junit.jupiter.api.Assertions.assertNotNull;
 import static org.junit.jupiter.api.Assertions.assertNull;
 import static org.junit.jupiter.api.Assertions.assertSame;
@@ -144,6 +146,8 @@ public class SenderTest {
 
     private TopicPartition tp0 = new TopicPartition("test", 0);
     private TopicPartition tp1 = new TopicPartition("test", 1);
+
+    private TopicPartition tp2 = new TopicPartition("test", 2);
     private MockTime time = new MockTime();
     private int batchSize = 16 * 1024;
     private ProducerMetadata metadata = new ProducerMetadata(0, 0, Long.MAX_VALUE, TOPIC_IDLE_MS,
@@ -3234,6 +3238,190 @@ public class SenderTest {
         }
     }
 
+    /**
+     * Test the scenario that FetchResponse returns NOT_LEADER_OR_FOLLOWER, indicating change in leadership, but it
+     * does not contain new leader info(defined in KIP-951).
+     */
+    @Test
+    public void testWhenProduceResponseReturnsWithALeaderShipChangeErrorButNoNewLeaderInformation()
+        throws InterruptedException {
+        // Setup 3 partitions, tp0 & tp1 return with NOT_LEADER_OR_FOLLOWER, tp2 doesn't return an error.
+        Metrics m = new Metrics();
+        SenderMetricsRegistry senderMetrics = new SenderMetricsRegistry(m);
+        try {
+            // SETUP
+            String metricGrpName = "producer-metrics-test-stats-1";
+            long totalSize = 1024 * 1024;
+            BufferPool pool = new BufferPool(totalSize, batchSize, metrics, time,
+                metricGrpName);
+            long retryBackoffMaxMs = 100L;
+            // lingerMs is 0 to send batch as soon as any records are available on it.
+            this.accumulator = new RecordAccumulator(logContext, batchSize,
+                CompressionType.NONE, 0, 10L, retryBackoffMaxMs,
+                DELIVERY_TIMEOUT_MS, metrics, metricGrpName, time, apiVersions, null, pool);
+            Sender sender = new Sender(logContext, client, metadata, this.accumulator, false,
+                MAX_REQUEST_SIZE, ACKS_ALL,
+                10, senderMetrics, time, REQUEST_TIMEOUT, RETRY_BACKOFF_MS, null,
+                apiVersions);
+            // Update metadata with leader-epochs.
+            int tp0LeaderEpoch = 100;
+            int tp1LeaderEpoch = 200;
+            int tp2LeaderEpoch = 300;
+            this.client.updateMetadata(
+                RequestTestUtils.metadataUpdateWith(1, Collections.singletonMap("test", 3),
+                    tp -> {
+                        if (tp0.equals(tp)) {
+                            return tp0LeaderEpoch;
+                        }  else if (tp1.equals(tp)) {
+                            return tp1LeaderEpoch;
+                        } else if (tp2.equals(tp)) {
+                            return tp2LeaderEpoch;
+                        } else {
+                            throw new RuntimeException("unexpected tp " + tp);
+                        }
+                    }));
+            Cluster startingMetadataCluster = metadata.fetch();
+
+            // Produce to tp0/1/2, where NO_LEADER_OR_FOLLOWER without new leader info is returned for tp0/1, and tp2 is returned without errors.
+            Future<RecordMetadata> futureIsProducedTp0 = appendToAccumulator(tp0, 0L, "key", "value");
+            Future<RecordMetadata> futureIsProducedTp1 = appendToAccumulator(tp1, 0L, "key", "value");
+            Future<RecordMetadata> futureIsProducedTp2 = appendToAccumulator(tp2, 0L, "key", "value");
+            sender.runOnce(); // connect
+            sender.runOnce(); // send produce request
+            assertEquals(1, sender.inFlightBatches(tp0).size());
+            assertEquals(1, sender.inFlightBatches(tp1).size());
+            assertEquals(1, sender.inFlightBatches(tp2).size());
+            assertTrue(client.hasInFlightRequests());
+            Map<TopicPartition, OffsetAndError> responses = new LinkedHashMap<>();
+            responses.put(tp0, new OffsetAndError(-1, Errors.NOT_LEADER_OR_FOLLOWER));
+            responses.put(tp1, new OffsetAndError(-1, Errors.NOT_LEADER_OR_FOLLOWER));
+            responses.put(tp2, new OffsetAndError(100, Errors.NONE));
+            client.respond(produceResponse(responses));
+            sender.runOnce(); // receive produce response, batch scheduled for retry
+            assertTrue(!futureIsProducedTp0.isDone(), "Produce request to tp0 should be unfinished.");
+            assertTrue(!futureIsProducedTp1.isDone(), "Produce request to tp1 should be unfinished.");
+            assertTrue(futureIsProducedTp2.isDone(), "Produce request to tp0 should be done.");
+
+            // Validate metadata is unchanged as new leader info wasn't received.
+            assertEquals(startingMetadataCluster, metadata.fetch());
+
+            // Validate metadata-refresh is requested as NOT_LEADER_OR_FOLLOWER received earlier
+            assertTrue(metadata.updateRequested());
+
+            // TEST that a subsequent retry waits the backoff period as the new leader info is yet not available.
+            sender.runOnce(); //send produce request
+            assertEquals(0, sender.inFlightBatches(tp0).size());
+            assertEquals(0, sender.inFlightBatches(tp1).size());
+            assertFalse(client.hasInFlightRequests());
+        } finally {
+            m.close();
+        }
+    }
+
+    /**
+     * Test the scenario that FetchResponse returns NOT_LEADER_OR_FOLLOWER, indicating change in leadership, along with
+     * new leader info(defined in KIP-951).
+     */
+    @Test
+    public void testWhenProduceResponseReturnsWithALeaderShipChangeErrorAndNewLeaderInformation()
+        throws InterruptedException {
+        // Setup 3 partitions, tp0 & tp1 return with NOT_LEADER_OR_FOLLOWER, tp2 doesn't return an error.
+        Metrics m = new Metrics();
+        SenderMetricsRegistry senderMetrics = new SenderMetricsRegistry(m);
+        try {
+            // SETUP
+            String metricGrpName = "producer-metrics-test-stats-1";
+            long totalSize = 1024 * 1024;
+            BufferPool pool = new BufferPool(totalSize, batchSize, metrics, time,
+                metricGrpName);
+            long retryBackoffMaxMs = 100L;
+            // lingerMs is 0 to send batch as soon as any records are available on it.
+            this.accumulator = new RecordAccumulator(logContext, batchSize,
+                CompressionType.NONE, 0, 10L, retryBackoffMaxMs,
+                DELIVERY_TIMEOUT_MS, metrics, metricGrpName, time, apiVersions, null, pool);
+            Sender sender = new Sender(logContext, client, metadata, this.accumulator, false,
+                MAX_REQUEST_SIZE, ACKS_ALL,
+                10, senderMetrics, time, REQUEST_TIMEOUT, RETRY_BACKOFF_MS, null,
+                apiVersions);
+            // Update metadata with leader-epochs.
+            int tp0LeaderEpoch = 100;
+            int tp1LeaderEpoch = 200;
+            int tp2LeaderEpoch = 300;
+            this.client.updateMetadata(
+                RequestTestUtils.metadataUpdateWith(1, Collections.singletonMap("test", 3),
+                    tp -> {
+                        if (tp0.equals(tp)) {
+                            return tp0LeaderEpoch;
+                        }  else if (tp1.equals(tp)) {
+                            return tp1LeaderEpoch;
+                        } else if (tp2.equals(tp)) {
+                            return tp2LeaderEpoch;
+                        } else {
+                            throw new RuntimeException("unexpected tp " + tp);
+                        }
+                    }));
+            Cluster startingMetadataCluster = metadata.fetch();
+
+            // Produce to tp0/1/2, where NO_LEADER_OR_FOLLOWER with new leader info is returned for tp0/1, and tp2 is returned without errors.
+            Future<RecordMetadata> futureIsProducedTp0 = appendToAccumulator(tp0, 0L, "key", "value");
+            Future<RecordMetadata> futureIsProducedTp1 = appendToAccumulator(tp1, 0L, "key", "value");
+            Future<RecordMetadata> futureIsProducedTp2 = appendToAccumulator(tp2, 0L, "key", "value");
+            sender.runOnce(); // connect
+            sender.runOnce(); // send produce request
+            assertEquals(1, sender.inFlightBatches(tp0).size());
+            assertEquals(1, sender.inFlightBatches(tp1).size());
+            assertEquals(1, sender.inFlightBatches(tp2).size());
+            assertTrue(client.hasInFlightRequests());
+
+            Node newNodeForTp0 = new Node(9990, "newhost9990", 9990, "newrack9990");
+            Node newNodeForTp1 = new Node(9991, "newhost9991", 9991, "newrack9991");
+            List<Node> newNodes = Arrays.asList(newNodeForTp0, newNodeForTp1);
+
+            Map<TopicPartition, OffsetAndError> responses = new LinkedHashMap<>();
+            responses.put(tp0, new OffsetAndError(-1, Errors.NOT_LEADER_OR_FOLLOWER));
+            responses.put(tp1, new OffsetAndError(-1, Errors.NOT_LEADER_OR_FOLLOWER));
+            responses.put(tp2, new OffsetAndError(100, Errors.NONE));
+
+            Map<TopicPartition, ProduceResponseData.LeaderIdAndEpoch> partitionLeaderInfo = new HashMap<>();
+            ProduceResponseData.LeaderIdAndEpoch tp0LeaderInfo = new ProduceResponseData.LeaderIdAndEpoch();
+            tp0LeaderInfo.setLeaderEpoch(tp0LeaderEpoch + 1);
+            tp0LeaderInfo.setLeaderId(newNodeForTp0.id());
+            partitionLeaderInfo.put(tp0, tp0LeaderInfo);
+            ProduceResponseData.LeaderIdAndEpoch tp1LeaderInfo = new ProduceResponseData.LeaderIdAndEpoch();
+            tp1LeaderInfo.setLeaderEpoch(tp1LeaderEpoch + 1);
+            tp1LeaderInfo.setLeaderId(newNodeForTp1.id());
+            partitionLeaderInfo.put(tp1, tp1LeaderInfo);
+
+            client.respond(produceResponse(responses, partitionLeaderInfo, newNodes));
+            sender.runOnce(); // receive produce response, batch scheduled for retry
+            assertTrue(!futureIsProducedTp0.isDone(), "Produce request to tp0 should be unfinished.");
+            assertTrue(!futureIsProducedTp1.isDone(), "Produce request to tp1 should be unfinished.");
+            assertTrue(futureIsProducedTp2.isDone(), "Produce request to tp0 should be done.");
+
+            // Validate metadata is unchanged as new leader info wasn't received.
+            assertNotEquals(startingMetadataCluster, metadata.fetch());
+            // Validate metadata cached has updated leader info for tp0/1.
+            Metadata.LeaderAndEpoch tp0NewLeaderInfo = metadata.currentLeader(tp0);
+            assertEquals(newNodeForTp0, tp0NewLeaderInfo.leader.get());
+            assertEquals(tp0LeaderEpoch + 1, tp0NewLeaderInfo.epoch.get());
+            Metadata.LeaderAndEpoch tp1NewLeaderInfo = metadata.currentLeader(tp1);
+            assertEquals(newNodeForTp1, tp1NewLeaderInfo.leader.get());
+            assertEquals(tp1LeaderEpoch + 1, tp1NewLeaderInfo.epoch.get());
+
+            // Validate metadata-refresh is requested as NOT_LEADER_OR_FOLLOWER received earlier
+            assertTrue(metadata.updateRequested());
+
+            // TEST that a subsequent retry skips the backoff as a new leader information is available.
+            sender.runOnce(); //send produce request
+            assertEquals(1, sender.inFlightBatches(tp0).size());
+            assertEquals(1, sender.inFlightBatches(tp1).size());
+            assertTrue(client.hasInFlightRequests());
+        } finally {
+            m.close();
+        }
+    }
+
+
     private void verifyErrorMessage(ProduceResponse response, String expectedMessage) throws Exception {
         Future<RecordMetadata> future = appendToAccumulator(tp0, 0L, "key", "value");
         sender.runOnce(); // connect
@@ -3362,6 +3550,13 @@ public class SenderTest {
     }
 
     private ProduceResponse produceResponse(Map<TopicPartition, OffsetAndError> responses) {
+        return produceResponse(responses, null, null);
+    }
+
+    /**
+     * It creates response with new leader info and new nodes, as stated in KIP-951
+     */
+    private ProduceResponse produceResponse(Map<TopicPartition, OffsetAndError> responses, Map<TopicPartition, ProduceResponseData.LeaderIdAndEpoch> partitionLeaderInfo, List<Node> nodes) {
         ProduceResponseData data = new ProduceResponseData();
 
         for (Map.Entry<TopicPartition, OffsetAndError> entry : responses.entrySet()) {
@@ -3380,11 +3575,27 @@ public class SenderTest {
                     .setErrorCode(offsetAndError.error.code())
                     .setRecordErrors(offsetAndError.recordErrors);
 
+            if (partitionLeaderInfo != null && partitionLeaderInfo.containsKey(topicPartition)) {
+                partitionData.setCurrentLeader(partitionLeaderInfo.get(topicPartition));
+            }
+
             topicData.partitionResponses().add(partitionData);
         }
 
+        if (nodes != null) {
+            nodes.stream().map(n -> {
+                ProduceResponseData.NodeEndpoint nodeEndPt = new ProduceResponseData.NodeEndpoint();
+                nodeEndPt.setNodeId(n.id());
+                nodeEndPt.setPort(n.port());
+                nodeEndPt.setHost(n.host());
+                nodeEndPt.setRack(n.rack());
+                return nodeEndPt;
+            }).forEach(nodeEndpoint -> data.nodeEndpoints().add(nodeEndpoint));
+        }
+
         return new ProduceResponse(data);
     }
+
     private ProduceResponse produceResponse(TopicPartition tp, long offset, Errors error, int throttleTimeMs) {
         return produceResponse(tp, offset, error, throttleTimeMs, -1L, null);
     }