MirrorMaker 2: replicating between Kafka clusters

MirrorMaker 2 copies topics from one Kafka cluster to another, together with their configs and the offsets of consumer groups, so that applications can fail over to a second cluster. This page explains how it is built on Kafka Connect, then runs it between two real clusters inside each program to show what gets copied, how offsets are translated and where the traps are.

Share

Contents

How MirrorMaker 2 works

Some systems need their data in more than one Kafka cluster: a standby cluster in another region for disaster recovery, a central cluster that aggregates regional ones, or a migration from an old cluster to a new one. MirrorMaker 2 (MM2), added in Kafka 2.4 by KIP-382, does this. It replaced the original MirrorMaker, which only consumed and re-produced records and was removed in Kafka 4.0.

MM2 is a set of three Kafka Connect source connectors. Each replication flow, written source->target, runs them on the target side:

  • MirrorSourceConnector: consumes the selected topics from the source cluster and produces them to the target, partition by partition. It also creates the target topics, copies their configs and, optionally, their ACLs. Every so often it writes an offset sync, a pair of source and target offsets, to a topic named mm2-offset-syncs.<target>.internal.
  • MirrorCheckpointConnector: reads the committed offsets of the selected consumer groups on the source, translates them with the offset syncs, and writes checkpoints to <source>.checkpoints.internal on the target. It can also write the translated offsets into the target's consumer groups.
  • MirrorHeartbeatConnector: writes a heartbeat record every second to a heartbeats topic. Heartbeats are replicated like any topic, so a cluster can tell which clusters feed it, and how many hops away they are.

Offsets cannot simply be copied, because the target partition's offsets differ from the source's: the target topic may have been created later, records may have been deleted, and transaction markers take up offsets on the source but are not copied. That is why MM2 needs offset syncs and translation.

Ways to run MirrorMaker 2
ModeStarted withBest for
Dedicatedconnect-mirror-maker.sh mm2.propertiesMost deployments: one config file describes all clusters and flows
On a Connect clusterThe three connectors created through the Connect REST APITeams that already operate Connect and want its REST API and monitoring

Each program on this page starts two single-node KRaft brokers in the JVM, called primary and backup, with EmbeddedKafkaKraftBroker from spring-kafka-test; real clusters have 3 or more brokers each. It then runs MM2 4.2.2 in dedicated mode in the same JVM through the MirrorMaker class that connect-mirror-maker.sh starts. The startMirrorMaker helper cuts the refresh and sync intervals from minutes to one second and sets every replication factor to 1. Both brokers have auto.create.topics.enable=false, as production clusters should. In a first version with it left on, records for partitions 1 and 2 of a three-partition topic did not arrive within 70 seconds.

Replicating a topic

The first program copies one topic with three partitions, a header on every record and two topic configs. It then looks at what arrived on the backup cluster and what MM2 created on both clusters:

Java
import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.lang.management.ManagementFactory;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import org.apache.kafka.clients.admin.Admin;
import org.apache.kafka.clients.admin.Config;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.config.ConfigResource;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.apache.kafka.connect.mirror.MirrorMaker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;

public class MirrorTopic {

    public static void main(String[] args) throws Exception {
        EmbeddedKafkaBroker primary = startBroker();
        EmbeddedKafkaBroker backup = startBroker();
        Map<String, Integer> sourcePartition = new HashMap<>();
        try (Admin admin = admin(primary)) {
            admin.createTopics(List.of(new NewTopic("orders", 3, (short) 1).configs(Map.of(
                    "retention.ms", "86400000",
                    "message.timestamp.type", "LogAppendTime")))).all().get();
        }
        try (KafkaProducer<String, String> producer = new KafkaProducer<>(
                Map.of("bootstrap.servers", primary.getBrokersAsString()),
                new StringSerializer(), new StringSerializer())) {
            for (int i = 1; i <= 6; i++) {
                var record = new ProducerRecord<>("orders", "order-" + i, "item " + i);
                record.headers().add("trace", ("t-" + i).getBytes(StandardCharsets.UTF_8));
                sourcePartition.put("order-" + i, producer.send(record).get().partition());
            }
        }

        MirrorMaker mm = startMirrorMaker(primary, backup, Map.of(
                "primary->backup.enabled", "true",
                "primary->backup.topics", "orders"));
        try (KafkaConsumer<String, String> consumer = new KafkaConsumer<>(Map.of(
                "bootstrap.servers", backup.getBrokersAsString(), "group.id", "reader",
                "auto.offset.reset", "earliest"),
                new StringDeserializer(), new StringDeserializer())) {
            consumer.subscribe(List.of("primary.orders"));
            List<ConsumerRecord<String, String>> copies = new ArrayList<>();
            while (copies.size() < 6) {
                consumer.poll(Duration.ofMillis(500)).forEach(copies::add);
            }
            copies.sort((a, b) -> a.partition() != b.partition()
                    ? a.partition() - b.partition() : Long.compare(a.offset(), b.offset()));
            for (ConsumerRecord<String, String> r : copies) {
                System.out.println(r.topic() + "-" + r.partition() + " offset " + r.offset()
                        + " " + r.key() + "=" + r.value() + " trace="
                        + new String(r.headers().lastHeader("trace").value(),
                                StandardCharsets.UTF_8)
                        + " same partition as source: "
                        + (sourcePartition.get(r.key()) == r.partition()));
            }
        }

        try (Admin admin = admin(backup)) {
            TreeSet<String> topics = new TreeSet<>();
            while (!topics.contains("primary.heartbeats")) { // copied after the next refresh
                Thread.sleep(200);
                topics = new TreeSet<>(admin.listTopics().names().get());
            }
            System.out.println("topics on backup:  " + topics);
            var resource = new ConfigResource(ConfigResource.Type.TOPIC, "primary.orders");
            Config config = admin.describeConfigs(List.of(resource)).all().get().get(resource);
            for (String key : List.of("retention.ms", "message.timestamp.type")) {
                System.out.println("primary.orders " + key + " = " + config.get(key).value()
                        + " (" + config.get(key).source() + ")");
            }
        }
        try (Admin admin = admin(primary)) {
            System.out.println("topics on primary: " + new TreeSet<>(admin.listTopics()
                    .names().get()));
        }

        MBeanServer jmx = ManagementFactory.getPlatformMBeanServer();
        for (int p = 0; p < 3; p++) {
            ObjectName name = new ObjectName("kafka.connect.mirror:type=MirrorSourceConnector,"
                    + "source=primary,target=backup,topic=primary.orders,partition=" + p);
            System.out.println("JMX record-count, partition " + p + ": "
                    + jmx.getAttribute(name, "record-count"));
        }
        mm.stop();
        primary.destroy();
        backup.destroy();
    }

    static Admin admin(EmbeddedKafkaBroker broker) {
        return Admin.create(Map.<String, Object>of("bootstrap.servers",
                broker.getBrokersAsString()));
    }

    // Runs MirrorMaker 2 in dedicated mode inside this JVM, as connect-mirror-maker.sh does.
    // The intervals are cut from minutes to one second, and every internal topic gets one
    // replica, because each cluster here has a single broker.
    static MirrorMaker startMirrorMaker(EmbeddedKafkaBroker primary, EmbeddedKafkaBroker backup,
            Map<String, String> flows) {
        Map<String, String> props = new HashMap<>(flows);
        props.put("clusters", "primary, backup");
        props.put("primary.bootstrap.servers", primary.getBrokersAsString());
        props.put("backup.bootstrap.servers", backup.getBrokersAsString());
        props.put("replication.factor", "1");
        for (String topic : List.of("checkpoints.topic", "heartbeats.topic", "offset-syncs.topic",
                "config.storage", "offset.storage", "status.storage")) {
            props.put(topic + ".replication.factor", "1");
        }
        for (String task : List.of("refresh.topics", "refresh.groups", "emit.checkpoints",
                "sync.group.offsets", "emit.heartbeats", "sync.topic.configs")) {
            props.put(task + ".interval.seconds", "1");
        }
        props.put("sync.topic.acls.enabled", "false"); // these brokers have no authorizer
        props.putIfAbsent("offset.flush.interval.ms", "1000");
        MirrorMaker mm = new MirrorMaker(props);
        mm.start();
        return mm;
    }

    // Starts a one-node KRaft broker inside this JVM, from spring-kafka-test
    static EmbeddedKafkaBroker startBroker() {
        // logging is off: MirrorMaker logs normal shutdown steps at ERROR. Logback's
        // Logger is named in full because org.slf4j.Logger, imported, has no setLevel
        ((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
                .setLevel(Level.OFF);
        PrintStream stdout = System.out;
        System.setOut(new PrintStream(OutputStream.nullOutputStream()));
        try {
            // production clusters turn automatic topic creation off; so do these
            EmbeddedKafkaBroker broker = new EmbeddedKafkaKraftBroker(1, 1).brokerProperties(
                    Map.of("auto.create.topics.enable", "false"));
            broker.afterPropertiesSet();
            return broker;
        } finally {
            System.setOut(stdout);
        }
    }
}
Output
primary.orders-0 offset 0 order-2=item 2 trace=t-2 same partition as source: true
primary.orders-0 offset 1 order-3=item 3 trace=t-3 same partition as source: true
primary.orders-0 offset 2 order-6=item 6 trace=t-6 same partition as source: true
primary.orders-1 offset 0 order-1=item 1 trace=t-1 same partition as source: true
primary.orders-2 offset 0 order-4=item 4 trace=t-4 same partition as source: true
primary.orders-2 offset 1 order-5=item 5 trace=t-5 same partition as source: true
topics on backup:  [heartbeats, mm2-configs.primary.internal, mm2-offsets.primary.internal, mm2-status.primary.internal, primary.checkpoints.internal, primary.heartbeats, primary.orders]
primary.orders retention.ms = 86400000 (DYNAMIC_TOPIC_CONFIG)
primary.orders message.timestamp.type = CreateTime (DEFAULT_CONFIG)
topics on primary: [heartbeats, mm2-configs.backup.internal, mm2-offset-syncs.backup.internal, mm2-offsets.backup.internal, mm2-status.backup.internal, orders]
JMX record-count, partition 0: 3.0
JMX record-count, partition 1: 1.0
JMX record-count, partition 2: 2.0
  • The topic arrived as primary.orders. DefaultReplicationPolicy prefixes remote topics with the source cluster's alias and a dot, so the backup can hold its own orders next to the copy.
  • Every record kept its key, value and header, and landed in the same partition number as on the source. Offsets in each target partition start at 0 here because the copy started with the topic.
  • retention.ms was copied as a topic override. message.timestamp.type was not: it is in the default config.properties.exclude list, together with min.insync.replicas, unclean.leader.election.enable and the replication throttles, which depend on the target cluster.
  • The backup gained heartbeats, primary.checkpoints.internal and three mm2-*.primary.internal topics, the Connect worker's config, offset and status topics for this flow. primary.heartbeats, the primary's heartbeats replicated like any topic, arrives after the next topic refresh, so the program waits for it.
  • The primary gained mm2-offset-syncs.backup.internal, because offset syncs are stored on the source by default, and the internal topics of the backup->primary herder. MM2 starts a herder for every pair of clusters, even for a disabled flow, so that heartbeats are emitted both ways.
  • The connector's JMX metric record-count per partition matches the 3, 1 and 2 records copied. The same MBeans hold replication-latency-ms and byte-rate.

Offset translation and consumer failover

Copying records is half of disaster recovery. The other half is letting consumers continue on the backup where they stopped on the primary. Two groups read the same ten records here: billing stopped after 4, audit read all 10. MM2 then translates their offsets, the primary is "lost", and both groups read from the backup. The program runs this twice, first with MM2's defaults and then with offset.lag.max=0:

Java
import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.kafka.clients.admin.Admin;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.consumer.OffsetAndMetadata;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.apache.kafka.connect.mirror.MirrorMaker;
import org.apache.kafka.connect.mirror.RemoteClusterUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;

public class ConsumerFailover {

    public static void main(String[] args) throws Exception {
        failover(Map.of());
        failover(Map.of("offset.lag.max", "0"));
    }

    static void failover(Map<String, String> extra) throws Exception {
        System.out.println("MirrorMaker settings " + extra + ":");
        EmbeddedKafkaBroker primary = startBroker();
        EmbeddedKafkaBroker backup = startBroker();
        try (Admin admin = admin(primary)) {
            admin.createTopics(List.of(new NewTopic("orders", 1, (short) 1))).all().get();
        }
        try (KafkaProducer<String, String> producer = new KafkaProducer<>(
                Map.of("bootstrap.servers", primary.getBrokersAsString()),
                new StringSerializer(), new StringSerializer())) {
            for (int i = 0; i < 10; i++) {
                producer.send(new ProducerRecord<>("orders", "order-" + i)).get();
            }
        }
        System.out.println("  on primary, billing read " + read(primary, "billing", "orders", 4)
                + " and audit read " + read(primary, "audit", "orders", 10) + " records");

        Map<String, String> flows = new HashMap<>(extra);
        flows.putAll(Map.of(
                "primary->backup.enabled", "true",
                "primary->backup.topics", "orders",
                "primary->backup.groups", "billing, audit",
                "primary->backup.sync.group.offsets.enabled", "true"));
        MirrorMaker mm = startMirrorMaker(primary, backup, flows);
        try (Admin admin = admin(backup)) {
            for (String group : List.of("billing", "audit")) {
                Map<TopicPartition, OffsetAndMetadata> synced = Map.of();
                while (synced.isEmpty()) {
                    Thread.sleep(500);
                    synced = admin.listConsumerGroupOffsets(group)
                            .partitionsToOffsetAndMetadata().get();
                }
                Map<TopicPartition, OffsetAndMetadata> translated =
                        RemoteClusterUtils.translateOffsets(
                                Map.of("bootstrap.servers", backup.getBrokersAsString()),
                                "primary", group, Duration.ofSeconds(10));
                System.out.println("  " + group + ": translated " + offsets(translated)
                        + ", synced to backup " + offsets(synced));
            }
        }
        mm.stop(); // the primary cluster is "lost": consumers move to the backup

        System.out.println("  after failover, billing read " + read(backup, "billing",
                "primary.orders", -1) + " and audit read " + read(backup, "audit",
                "primary.orders", -1) + " records on backup");
        primary.destroy();
        backup.destroy();
    }

    // Reads count records (-1: until none arrive for 2 s after joining), commits, returns
    // "N (offsets a-b)"
    static String read(EmbeddedKafkaBroker broker, String group, String topic, int count) {
        try (KafkaConsumer<String, String> consumer = new KafkaConsumer<>(Map.of(
                "bootstrap.servers", broker.getBrokersAsString(), "group.id", group,
                "auto.offset.reset", "earliest", "enable.auto.commit", "false"),
                new StringDeserializer(), new StringDeserializer())) {
            consumer.subscribe(List.of(topic));
            List<Long> seen = new ArrayList<>();
            long idleSince = System.currentTimeMillis() + 8000; // time to join the group
            while (count < 0 ? System.currentTimeMillis() - idleSince < 2000
                    : seen.size() < count) {
                for (ConsumerRecord<String, String> r : consumer.poll(Duration.ofMillis(200))) {
                    if (count < 0 || seen.size() < count) {
                        seen.add(r.offset());
                        consumer.commitSync(Map.of(new TopicPartition(r.topic(), r.partition()),
                                new OffsetAndMetadata(r.offset() + 1)));
                    }
                    idleSince = System.currentTimeMillis();
                }
            }
            return seen.isEmpty() ? "0" : seen.size() + " (offsets " + seen.get(0) + "-"
                    + seen.get(seen.size() - 1) + ")";
        }
    }

    static String offsets(Map<TopicPartition, OffsetAndMetadata> map) {
        Map<String, Long> out = new HashMap<>();
        map.forEach((tp, om) -> out.put(tp.toString(), om.offset()));
        return out.toString();
    }

    static Admin admin(EmbeddedKafkaBroker broker) {
        return Admin.create(Map.<String, Object>of("bootstrap.servers",
                broker.getBrokersAsString()));
    }

    // Runs MirrorMaker 2 in dedicated mode inside this JVM, as connect-mirror-maker.sh does.
    // The intervals are cut from minutes to one second, and every internal topic gets one
    // replica, because each cluster here has a single broker.
    static MirrorMaker startMirrorMaker(EmbeddedKafkaBroker primary, EmbeddedKafkaBroker backup,
            Map<String, String> flows) {
        Map<String, String> props = new HashMap<>(flows);
        props.put("clusters", "primary, backup");
        props.put("primary.bootstrap.servers", primary.getBrokersAsString());
        props.put("backup.bootstrap.servers", backup.getBrokersAsString());
        props.put("replication.factor", "1");
        for (String topic : List.of("checkpoints.topic", "heartbeats.topic", "offset-syncs.topic",
                "config.storage", "offset.storage", "status.storage")) {
            props.put(topic + ".replication.factor", "1");
        }
        for (String task : List.of("refresh.topics", "refresh.groups", "emit.checkpoints",
                "sync.group.offsets", "emit.heartbeats", "sync.topic.configs")) {
            props.put(task + ".interval.seconds", "1");
        }
        props.put("sync.topic.acls.enabled", "false"); // these brokers have no authorizer
        props.putIfAbsent("offset.flush.interval.ms", "1000");
        MirrorMaker mm = new MirrorMaker(props);
        mm.start();
        return mm;
    }

    // Starts a one-node KRaft broker inside this JVM, from spring-kafka-test
    static EmbeddedKafkaBroker startBroker() {
        // logging is off: MirrorMaker logs normal shutdown steps at ERROR. Logback's
        // Logger is named in full because org.slf4j.Logger, imported, has no setLevel
        ((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
                .setLevel(Level.OFF);
        PrintStream stdout = System.out;
        System.setOut(new PrintStream(OutputStream.nullOutputStream()));
        try {
            // production clusters turn automatic topic creation off; so do these
            EmbeddedKafkaBroker broker = new EmbeddedKafkaKraftBroker(1, 1).brokerProperties(
                    Map.of("auto.create.topics.enable", "false"));
            broker.afterPropertiesSet();
            return broker;
        } finally {
            System.setOut(stdout);
        }
    }
}
Output
MirrorMaker settings {}:
  on primary, billing read 4 (offsets 0-3) and audit read 10 (offsets 0-9) records
  billing: translated {primary.orders-0=1}, synced to backup {primary.orders-0=1}
  audit: translated {primary.orders-0=1}, synced to backup {primary.orders-0=1}
  after failover, billing read 9 (offsets 1-9) and audit read 9 (offsets 1-9) records on backup
MirrorMaker settings {offset.lag.max=0}:
  on primary, billing read 4 (offsets 0-3) and audit read 10 (offsets 0-9) records
  billing: translated {primary.orders-0=4}, synced to backup {primary.orders-0=4}
  audit: translated {primary.orders-0=10}, synced to backup {primary.orders-0=10}
  after failover, billing read 6 (offsets 4-9) and audit read 0 records on backup
  • With the defaults, both groups were translated to offset 1, although they had committed 4 and 10. After failover, billing read offsets 1 to 9, so records 1 to 3 were processed twice, and audit read 9 records it had already handled.
  • With offset.lag.max=0, the translations were exact: 4 and 10. billing continued with offsets 4 to 9 and audit read nothing.
  • In both runs RemoteClusterUtils.translateOffsets, which reads the checkpoints, and the offsets written into the backup's groups by sync.group.offsets.enabled=true agree.

The reason is how syncs work. The source connector emits an offset sync only when the distance from the last sync exceeds offset.lag.max, 100 records by default, and a few other conditions hold. A committed offset between two syncs can only be translated to the target offset after the earlier sync, plus one: MM2 cannot know exactly where it falls, and rounding down never skips records. With only the first record synced, every offset became 1. Lowering offset.lag.max gives more exact translations at the cost of more writes to the offset-syncs topic. Either way, failover with MM2 is at-least-once: consumers must tolerate duplicates.

The target groups are only written while they have no active members, so a consumer group cannot run on both clusters at once. sync.group.offsets.enabled is false by default; without it, applications call RemoteClusterUtils.translateOffsets themselves at failover time and seek to the result.

Active-active replication

When applications in two regions write locally, each cluster replicates to the other. With the default policy this is safe, because the topic name records where the data came from. Both clusters have their own orders here, and both flows are enabled with the default topic filter, .*:

Java
import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.regex.Pattern;
import org.apache.kafka.clients.admin.Admin;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.apache.kafka.connect.mirror.MirrorClient;
import org.apache.kafka.connect.mirror.MirrorMaker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;

public class ActiveActive {

    public static void main(String[] args) throws Exception {
        EmbeddedKafkaBroker primary = startBroker();
        EmbeddedKafkaBroker backup = startBroker();
        produce(primary, "p-1", "p-2");
        produce(backup, "b-1");

        MirrorMaker mm = startMirrorMaker(primary, backup, Map.of(
                "primary->backup.enabled", "true",
                "backup->primary.enabled", "true"));
        show("primary", primary, 3);
        show("backup ", backup, 3);
        Thread.sleep(3000); // several more topic refreshes: nothing is copied back again
        for (EmbeddedKafkaBroker broker : List.of(primary, backup)) {
            try (Admin admin = admin(broker)) {
                TreeSet<String> topics = new TreeSet<>(admin.listTopics().names().get());
                long internal = topics.stream().filter(t -> t.startsWith("mm2-")).count();
                topics.removeIf(t -> t.startsWith("mm2-"));
                System.out.println("topics: " + topics + " and " + internal + " mm2-* topics");
            }
        }

        try (MirrorClient client = new MirrorClient(
                Map.of("bootstrap.servers", backup.getBrokersAsString()))) {
            System.out.println("MirrorClient on backup:");
            System.out.println("  remoteTopics     " + new TreeSet<>(client.remoteTopics()));
            System.out.println("  upstreamClusters " + client.upstreamClusters());
            System.out.println("  hops to primary  " + client.replicationHops("primary"));
            System.out.println("  source of primary.orders: "
                    + client.replicationPolicy().topicSource("primary.orders")
                    + ", upstream name: "
                    + client.replicationPolicy().upstreamTopic("primary.orders"));
        }
        mm.stop();
        primary.destroy();
        backup.destroy();
    }

    static void produce(EmbeddedKafkaBroker broker, String... values) throws Exception {
        try (Admin admin = admin(broker)) {
            admin.createTopics(List.of(new NewTopic("orders", 1, (short) 1))).all().get();
        }
        try (KafkaProducer<String, String> producer = new KafkaProducer<>(
                Map.of("bootstrap.servers", broker.getBrokersAsString()),
                new StringSerializer(), new StringSerializer())) {
            for (String v : values) {
                producer.send(new ProducerRecord<>("orders", v)).get();
            }
        }
    }

    // Lists every non-internal topic with its values, once the given number has arrived
    static void show(String name, EmbeddedKafkaBroker broker, int expected) throws Exception {
        Map<String, List<String>> topics = new TreeMap<>();
        try (KafkaConsumer<String, String> consumer = new KafkaConsumer<>(Map.of(
                "bootstrap.servers", broker.getBrokersAsString(), "group.id", "viewer",
                "auto.offset.reset", "earliest", "metadata.max.age.ms", "1000"),
                new StringDeserializer(), new StringDeserializer())) {
            consumer.subscribe(Pattern.compile("(.*\\.)?orders"));
            int seen = 0;
            while (seen < expected) {
                for (ConsumerRecord<String, String> r : consumer.poll(Duration.ofMillis(500))) {
                    topics.computeIfAbsent(r.topic(), t -> new ArrayList<>())
                            .add(r.value());
                    seen++;
                }
            }
        }
        System.out.println(name + " holds " + topics);
    }

    static Admin admin(EmbeddedKafkaBroker broker) {
        return Admin.create(Map.<String, Object>of("bootstrap.servers",
                broker.getBrokersAsString()));
    }

    // Runs MirrorMaker 2 in dedicated mode inside this JVM, as connect-mirror-maker.sh does.
    // The intervals are cut from minutes to one second, and every internal topic gets one
    // replica, because each cluster here has a single broker.
    static MirrorMaker startMirrorMaker(EmbeddedKafkaBroker primary, EmbeddedKafkaBroker backup,
            Map<String, String> flows) {
        Map<String, String> props = new HashMap<>(flows);
        props.put("clusters", "primary, backup");
        props.put("primary.bootstrap.servers", primary.getBrokersAsString());
        props.put("backup.bootstrap.servers", backup.getBrokersAsString());
        props.put("replication.factor", "1");
        for (String topic : List.of("checkpoints.topic", "heartbeats.topic", "offset-syncs.topic",
                "config.storage", "offset.storage", "status.storage")) {
            props.put(topic + ".replication.factor", "1");
        }
        for (String task : List.of("refresh.topics", "refresh.groups", "emit.checkpoints",
                "sync.group.offsets", "emit.heartbeats", "sync.topic.configs")) {
            props.put(task + ".interval.seconds", "1");
        }
        props.put("sync.topic.acls.enabled", "false"); // these brokers have no authorizer
        props.putIfAbsent("offset.flush.interval.ms", "1000");
        MirrorMaker mm = new MirrorMaker(props);
        mm.start();
        return mm;
    }

    // Starts a one-node KRaft broker inside this JVM, from spring-kafka-test
    static EmbeddedKafkaBroker startBroker() {
        // logging is off: MirrorMaker logs normal shutdown steps at ERROR. Logback's
        // Logger is named in full because org.slf4j.Logger, imported, has no setLevel
        ((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
                .setLevel(Level.OFF);
        PrintStream stdout = System.out;
        System.setOut(new PrintStream(OutputStream.nullOutputStream()));
        try {
            // production clusters turn automatic topic creation off; so do these
            EmbeddedKafkaBroker broker = new EmbeddedKafkaKraftBroker(1, 1).brokerProperties(
                    Map.of("auto.create.topics.enable", "false"));
            broker.afterPropertiesSet();
            return broker;
        } finally {
            System.setOut(stdout);
        }
    }
}
Output
primary holds {backup.orders=[b-1], orders=[p-1, p-2]}
backup  holds {orders=[b-1], primary.orders=[p-1, p-2]}
topics: [backup.checkpoints.internal, backup.heartbeats, backup.orders, heartbeats, orders] and 4 mm2-* topics
topics: [heartbeats, orders, primary.checkpoints.internal, primary.heartbeats, primary.orders] and 4 mm2-* topics
MirrorClient on backup:
  remoteTopics     [primary.heartbeats, primary.orders]
  upstreamClusters [primary]
  hops to primary  1
  source of primary.orders: primary, upstream name: orders
  • Each cluster now holds its own orders and the other's as backup.orders or primary.orders. A consumer that needs everything subscribes to the pattern (.*\.)?orders, as show does.
  • Nothing was copied back: there is no backup.primary.orders, even after several more topic refreshes. The policy sees that primary.orders on the backup came from primary, and the flow to primary skips it to avoid a cycle.
  • MirrorClient reads this structure back: the backup's remote topics, its one upstream cluster, and that primary is 1 hop away, which it learns from the heartbeat topics.
  • The replication policy also maps names both ways: the source of primary.orders is primary, and its name upstream is orders.

Active-active does not merge the data. Two copies of a key can be written in two regions at the same time, and Kafka does nothing to resolve the conflict. The application decides how, for example by giving each region ownership of its own customers.

Keeping topic names with IdentityReplicationPolicy

For a migration or a one-way standby, a renamed topic forces every consumer to change its configuration on failover. IdentityReplicationPolicy, added in Kafka 3.0, keeps the original names:

Java
import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.regex.Pattern;
import org.apache.kafka.clients.admin.Admin;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.apache.kafka.connect.mirror.MirrorClient;
import org.apache.kafka.connect.mirror.MirrorMaker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;

public class IdentityPolicy {

    public static void main(String[] args) throws Exception {
        EmbeddedKafkaBroker primary = startBroker();
        EmbeddedKafkaBroker backup = startBroker();
        produce(primary, "p-1", "p-2");

        MirrorMaker mm = startMirrorMaker(primary, backup, Map.of(
                "primary->backup.enabled", "true",
                "primary->backup.topics", "orders",
                "replication.policy.class",
                "org.apache.kafka.connect.mirror.IdentityReplicationPolicy"));
        show("backup", backup, 2);
        try (Admin admin = admin(backup)) {
            System.out.println("topics on backup: "
                    + new TreeSet<>(admin.listTopics().names().get()));
        }
        Map<String, Object> props = new HashMap<>(Map.of(
                "bootstrap.servers", backup.getBrokersAsString(),
                "replication.policy.class",
                "org.apache.kafka.connect.mirror.IdentityReplicationPolicy"));
        try (MirrorClient client = new MirrorClient(props)) {
            System.out.println("remoteTopics on backup: " + client.remoteTopics());
            System.out.println("source of orders: "
                    + client.replicationPolicy().topicSource("orders"));
            System.out.println("upstreamClusters: " + client.upstreamClusters());
        }
        mm.stop();
        primary.destroy();
        backup.destroy();
    }

    static void produce(EmbeddedKafkaBroker broker, String... values) throws Exception {
        try (Admin admin = admin(broker)) {
            admin.createTopics(List.of(new NewTopic("orders", 1, (short) 1))).all().get();
        }
        try (KafkaProducer<String, String> producer = new KafkaProducer<>(
                Map.of("bootstrap.servers", broker.getBrokersAsString()),
                new StringSerializer(), new StringSerializer())) {
            for (String v : values) {
                producer.send(new ProducerRecord<>("orders", v)).get();
            }
        }
    }

    // Lists every non-internal topic with its values, once the given number has arrived
    static void show(String name, EmbeddedKafkaBroker broker, int expected) throws Exception {
        Map<String, List<String>> topics = new TreeMap<>();
        try (KafkaConsumer<String, String> consumer = new KafkaConsumer<>(Map.of(
                "bootstrap.servers", broker.getBrokersAsString(), "group.id", "viewer",
                "auto.offset.reset", "earliest", "metadata.max.age.ms", "1000"),
                new StringDeserializer(), new StringDeserializer())) {
            consumer.subscribe(Pattern.compile("(.*\\.)?orders"));
            int seen = 0;
            while (seen < expected) {
                for (ConsumerRecord<String, String> r : consumer.poll(Duration.ofMillis(500))) {
                    topics.computeIfAbsent(r.topic(), t -> new ArrayList<>())
                            .add(r.value());
                    seen++;
                }
            }
        }
        System.out.println(name + " holds " + topics);
    }

    static Admin admin(EmbeddedKafkaBroker broker) {
        return Admin.create(Map.<String, Object>of("bootstrap.servers",
                broker.getBrokersAsString()));
    }

    // Runs MirrorMaker 2 in dedicated mode inside this JVM, as connect-mirror-maker.sh does.
    // The intervals are cut from minutes to one second, and every internal topic gets one
    // replica, because each cluster here has a single broker.
    static MirrorMaker startMirrorMaker(EmbeddedKafkaBroker primary, EmbeddedKafkaBroker backup,
            Map<String, String> flows) {
        Map<String, String> props = new HashMap<>(flows);
        props.put("clusters", "primary, backup");
        props.put("primary.bootstrap.servers", primary.getBrokersAsString());
        props.put("backup.bootstrap.servers", backup.getBrokersAsString());
        props.put("replication.factor", "1");
        for (String topic : List.of("checkpoints.topic", "heartbeats.topic", "offset-syncs.topic",
                "config.storage", "offset.storage", "status.storage")) {
            props.put(topic + ".replication.factor", "1");
        }
        for (String task : List.of("refresh.topics", "refresh.groups", "emit.checkpoints",
                "sync.group.offsets", "emit.heartbeats", "sync.topic.configs")) {
            props.put(task + ".interval.seconds", "1");
        }
        props.put("sync.topic.acls.enabled", "false"); // these brokers have no authorizer
        props.putIfAbsent("offset.flush.interval.ms", "1000");
        MirrorMaker mm = new MirrorMaker(props);
        mm.start();
        return mm;
    }

    // Starts a one-node KRaft broker inside this JVM, from spring-kafka-test
    static EmbeddedKafkaBroker startBroker() {
        // logging is off: MirrorMaker logs normal shutdown steps at ERROR. Logback's
        // Logger is named in full because org.slf4j.Logger, imported, has no setLevel
        ((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
                .setLevel(Level.OFF);
        PrintStream stdout = System.out;
        System.setOut(new PrintStream(OutputStream.nullOutputStream()));
        try {
            // production clusters turn automatic topic creation off; so do these
            EmbeddedKafkaBroker broker = new EmbeddedKafkaKraftBroker(1, 1).brokerProperties(
                    Map.of("auto.create.topics.enable", "false"));
            broker.afterPropertiesSet();
            return broker;
        } finally {
            System.setOut(stdout);
        }
    }
}
Output
backup holds {orders=[p-1, p-2]}
topics on backup: [heartbeats, mm2-configs.primary.internal, mm2-offsets.primary.internal, mm2-status.primary.internal, orders, primary.checkpoints.internal, primary.heartbeats]
remoteTopics on backup: [primary.heartbeats]
source of orders: null
upstreamClusters: [primary]
  • The records arrived in a topic called orders on the backup, so consumers can fail over with only a new bootstrap.servers.
  • Only the heartbeats kept a prefix: MirrorClient lists primary.heartbeats as the one remote topic, and still finds primary upstream through it.
  • For orders itself, the policy returns null as the source: a replicated topic cannot be told apart from a local one by its name.

That last point is the trap. Without the prefix, MM2 cannot detect cycles, so enabling both flows with this policy would copy records back and forth forever. Use it only for one-way replication, and do not let applications write to the target's copy while replication runs.

A production configuration

A dedicated MM2 cluster is configured with one properties file, the same on every MM2 node. The file below follows the Kafka 4.2 documentation and the defaults read from the 4.2.2 jars; it was not run here, since it needs two real clusters:

Properties
# mm2.properties
clusters = primary, backup
primary.bootstrap.servers = kafka-a1:9092,kafka-a2:9092,kafka-a3:9092
backup.bootstrap.servers = kafka-b1:9092,kafka-b2:9092,kafka-b3:9092

primary->backup.enabled = true
primary->backup.topics = orders.*, payments
primary->backup.groups = billing, shipping
primary->backup.sync.group.offsets.enabled = true
primary->backup.emit.checkpoints.interval.seconds = 10
primary->backup.sync.group.offsets.interval.seconds = 10

replication.factor = 3
checkpoints.topic.replication.factor = 3
heartbeats.topic.replication.factor = 3
offset-syncs.topic.replication.factor = 3
config.storage.replication.factor = 3
offset.storage.replication.factor = 3
status.storage.replication.factor = 3

# several MM2 nodes in one dedicated cluster need the internal REST API (KIP-710)
dedicated.mode.enable.internal.rest = true
tasks.max = 4
MirrorMaker 2 defaults worth knowing (Kafka 4.2.2)
SettingDefaultEffect
refresh.topics.interval.seconds600New source topics are found within 10 minutes
sync.topic.configs.interval.seconds600Config changes reach the target within 10 minutes
emit.checkpoints.interval.seconds60Translated offsets are up to a minute old
sync.group.offsets.enabledfalseTarget groups are not written unless turned on
offset.lag.max100Translations can be up to about 100 records behind
replication.factor2Raise to 3 for remote topics
topics.excludemm2.*\.internal, .*\.replica, __.*Internal topics are never copied
groups.excludeconsole-consumer-.*, connect-.*, __.*Tool and Connect groups are skipped

Run MM2 near the target cluster: consuming across a long network link tolerates latency better than producing across it. Watch replication-latency-ms and the lag of MM2's own consumers. The tasks.max setting spreads topic partitions over several tasks; the default of 1 copies everything on one thread.

Choosing a replication setup

Goals and the setup that fits
GoalSetup
Standby cluster for disaster recoveryOne flow, DefaultReplicationPolicy, group offset sync on, consumers that tolerate duplicates
Exact consumer positions after failoverLower offset.lag.max, accepting more offset-sync writes
Two regions writing at the same timeBoth flows with DefaultReplicationPolicy, consumers subscribed by pattern
Moving to a new cluster with the same topic namesOne flow with IdentityReplicationPolicy, writes only on the source
Aggregating regional clusters into oneOne flow per region into the central cluster; prefixes keep regions apart
Copying a few topics to another team's clusterA narrow topics list and sync.topic.acls.enabled=false

MM2 runs on the Connect runtime described on Kafka Connect. Committed offsets, which MM2 translates, are explained on Kafka offsets, and the cluster operations used on each side on Kafka cluster administration.