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.
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
- 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
on the target. It can also write the translated offsets into the target's consumer groups.<source>.checkpoints.internal - MirrorHeartbeatConnector: writes a heartbeat record every second to a
topic. Heartbeats are replicated like any topic, so a cluster can tell which clusters feed it, and how many hops away they are.heartbeats
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.
| Mode | Started with | Best for |
|---|---|---|
| Dedicated | connect-mirror-maker.sh mm2.properties | Most deployments: one config file describes all clusters and flows |
| On a Connect cluster | The three connectors created through the Connect REST API | Teams 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 primarybackupEmbeddedKafkaKraftBrokerspring-kafka-testMirrorMakerconnect-mirror-maker.shstartMirrorMakerauto.create.topics.enable=false
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:
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);
}
}
}
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 prefixes remote topics with the source cluster's alias and a dot, so the backup can hold its ownDefaultReplicationPolicy next to the copy.orders - 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.
was copied as a topic override.retention.ms was not: it is in the defaultmessage.timestamp.type list, together withconfig.properties.exclude ,min.insync.replicas and the replication throttles, which depend on the target cluster.unclean.leader.election.enable- The backup gained
,heartbeats and threeprimary.checkpoints.internal topics, the Connect worker's config, offset and status topics for this flow.mm2-*.primary.internal , the primary's heartbeats replicated like any topic, arrives after the next topic refresh, so the program waits for it.primary.heartbeats - The primary gained
, because offset syncs are stored on the source by default, and the internal topics of themm2-offset-syncs.backup.internal herder. MM2 starts a herder for every pair of clusters, even for a disabled flow, so that heartbeats are emitted both ways.backup->primary - The connector's JMX metric
per partition matches the 3, 1 and 2 records copied. The same MBeans holdrecord-count andreplication-latency-ms .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: billingauditoffset.lag.max=0
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);
}
}
}
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,
read offsets 1 to 9, so records 1 to 3 were processed twice, andbilling read 9 records it had already handled.audit - With
, the translations were exact: 4 and 10.offset.lag.max=0 continued with offsets 4 to 9 andbilling read nothing.audit - In both runs
, which reads the checkpoints, and the offsets written into the backup's groups byRemoteClusterUtils.translateOffsets agree.sync.group.offsets.enabled=true
The reason is how syncs work. The source connector emits an offset sync only when the distance from the last sync exceeds offset.lag.maxoffset.lag.max
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.enabledfalseRemoteClusterUtils.translateOffsets
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.*
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);
}
}
}
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
and the other's asorders orbackup.orders . A consumer that needs everything subscribes to the patternprimary.orders , as(.*\.)?orders does.show - Nothing was copied back: there is no
, even after several more topic refreshes. The policy sees thatbackup.primary.orders on the backup came fromprimary.orders , and the flow toprimary skips it to avoid a cycle.primary reads this structure back: the backup's remote topics, its one upstream cluster, and thatMirrorClient is 1 hop away, which it learns from the heartbeat topics.primary- The replication policy also maps names both ways: the source of
isprimary.orders , and its name upstream isprimary .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
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);
}
}
}
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
on the backup, so consumers can fail over with only a neworders .bootstrap.servers - Only the heartbeats kept a prefix:
listsMirrorClient as the one remote topic, and still findsprimary.heartbeats upstream through it.primary - For
itself, the policy returnsorders as the source: a replicated topic cannot be told apart from a local one by its name.null
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:
# 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
| Setting | Default | Effect |
|---|---|---|
refresh.topics.interval.seconds | 600 | New source topics are found within 10 minutes |
sync.topic.configs.interval.seconds | 600 | Config changes reach the target within 10 minutes |
emit.checkpoints.interval.seconds | 60 | Translated offsets are up to a minute old |
sync.group.offsets.enabled | false | Target groups are not written unless turned on |
offset.lag.max | 100 | Translations can be up to about 100 records behind |
replication.factor | 2 | Raise to 3 for remote topics |
topics.exclude | mm2.*\.internal, .*\.replica, __.* | Internal topics are never copied |
groups.exclude | console-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-mstasks.max
Choosing a replication setup
| Goal | Setup |
|---|---|
| Standby cluster for disaster recovery | One flow, DefaultReplicationPolicy |
| Exact consumer positions after failover | Lower offset.lag.max |
| Two regions writing at the same time | Both flows with DefaultReplicationPolicy |
| Moving to a new cluster with the same topic names | One flow with IdentityReplicationPolicy |
| Aggregating regional clusters into one | One flow per region into the central cluster; prefixes keep regions apart |
| Copying a few topics to another team's cluster | A narrow topicssync.topic.acls.enabled=false |
MM2 runs on the Connect runtime described on