@Override
    public Optional<ReplicaView> select(TopicPartition topicPartition,
                                        ClientMetadata clientMetadata,
                                        PartitionView partitionView) {
        if (clientMetadata.rackId() != null && !clientMetadata.rackId().isEmpty()) {
            Set<ReplicaView> sameRackReplicas = partitionView.replicas().stream()
                    .filter(replicaInfo -> clientMetadata.rackId().equals(replicaInfo.endpoint().rack()))
                    .collect(Collectors.toSet());
            if (sameRackReplicas.isEmpty()) {
                return Optional.of(partitionView.leader());
            } else {
                if (sameRackReplicas.contains(partitionView.leader())) {
                    // Use the leader if it's in this rack
                    return Optional.of(partitionView.leader());
                } else {
                    // Otherwise, get the most caught-up replica
                    return sameRackReplicas.stream().max(ReplicaView.comparator());
                }
            }
        } else {
            return Optional.of(partitionView.leader());
        }
    }
Returns a replica whose rack id is equal to the rack id specified in the client request metadata. If no such replica
is found, returns the leader.
clients/src/main/java/org/apache/kafka/common/replica/RackAwareReplicaSelector.java