🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Kafka Multi-Datacenter Replication

đŸŸĸ Free Lesson

Kafka Multi-Datacenter Replication

Datacenter 1 (Primary)ProducersKafka Cluster3 Brokers / 9 PartitionsLocal ConsumersMirrorMaker 2Replication PoliciesOffset SyncTopic TranslationCheckpoint ConnectorDatacenter 2 (Secondary)Kafka Cluster3 Brokers / 9 ReplicatedReplicated TopicsFailover ConsumersBi-directional Replication

Overview

Multi-datacenter Kafka replication enables disaster recovery, geo-redundancy, and data locality across distributed infrastructure. This guide covers MirrorMaker 2 replication, failover strategies, and active-active architectures.

Use Cases

  • Disaster Recovery: Failover to secondary DC during outages
  • Geo-Redundancy: Serve consumers from nearest datacenter
  • Compliance: Meet data residency requirements
  • Performance: Reduce latency for geographically distributed users

Replication across sites is asynchronous by nature, so the first number to agree on is the recovery point objective: with MirrorMaker 2 the worst-case loss after a total site failure is whatever lag had accumulated, typically tens of milliseconds on a healthy link and minutes when a link degrades. The second number is the recovery time objective, which is dominated by how fast you detect the outage and repoint clients, not by how fast data moves. Bandwidth follows directly from your produce rate: a cluster ingesting 80 MB per second ships roughly 6.9 TB per day to the second site, and a link that cannot carry that continuously will fall behind, so cross-site links need monitoring as carefully as the brokers themselves. Sites separated by 80 milliseconds of round-trip time add at least that much to any synchronous acknowledgement, which is exactly why replication is offered as an asynchronous feature rather than as a stronger guarantee.

MirrorMaker 2 Architecture

Core Components

ComponentFunction
Source ConnectorReads from source cluster
Sink ConnectorWrites to target cluster
Checkpoint ConnectorSyncs consumer offsets
Heartbeat ConnectorMonitors cluster health

Those four connectors run on a Kafka Connect cluster rather than inside the brokers, which is why MirrorMaker 2 costs hardware of its own: one source task per input partition pulls from the remote cluster and produces into the local one, a checkpoint task periodically writes the consumer group positions it observed, and a heartbeat task emits a steady signal so a consumer in the second datacenter can tell "replication stopped" from "the source site went away". A dedicated Connect cluster per direction is the norm, sized with tasks.max at least equal to the number of mirrored partitions divided by the number of workers, because a task that outlives its share of partitions simply queues behind the others. Placement matters too: run the workers near the source cluster to keep fetches local, and give them their own disk, since a mirrored topic's data is written twice in the path from producer to second site.

MirrorMaker 2 Configuration

# mm2.properties
clusters = dc1, dc2

# DC1 connection
dc1.bootstrap.servers = kafka-dc1:9092
dc1.security.protocol = SSL

# DC2 connection
dc2.bootstrap.servers = kafka-dc2:9092
dc2.security.protocol = SSL

# Replication flow
dc1->dc2.enabled = true
dc1->dc2.topics = orders.*, payments.*

# Topic naming
topics.pattern = ${sourceCluster}.${topic}

# Replication policy
replication.factor = 3
sync.topic.configs.enabled = true
refresh.topics.interval.seconds = 60

Kafka Connect Configuration

{
  "name": "mirror-maker-2",
  "config": {
    "connector.class": "org.apache.kafka.connect.mirror.MirrorSourceConnector",
    "tasks.max": "5",
    "clusters": "dc1,dc2",
    "dc1.bootstrap.servers": "kafka-dc1-1:9092,kafka-dc1-2:9092,kafka-dc1-3:9092",
    "dc2.bootstrap.servers": "kafka-dc2-1:9092,kafka-dc2-2:9092,kafka-dc2-3:9092",
    "dc1->dc2.enabled": "true",
    "dc1->dc2.topics": "orders,payments,users",
    "topics.pattern": "${sourceCluster}.${topic}",
    "sync.topic.configs.enabled": "true",
    "replication.factor": "3",
    "emit.heartbeats.enabled": "true",
    "emit.checkpoints.enabled": "true"
  }
}

Replication Policies

Topic Translation

python
# Custom topic naming convention
# Source: orders (DC1)
# Replicated: dc1.orders (DC2)

TOPIC_TRANSLATION = {
    'source_pattern': '{topic}',
    'target_pattern': '{source_cluster}.{topic}',
    'examples': {
        'orders': 'dc1.orders',
        'payments': 'dc1.payments',
        'users': 'dc1.users'
    }
}

Replication Factor

# Check replication status
kafka-topics.sh --bootstrap-server kafka-dc2:9092 \
  --describe --topic dc1.orders

# Output:
# Topic: dc1.orders  Partition: 0  Leader: 1  Replicas: 1,2,3  Isr: 1,2,3
# Topic: dc1.orders  Partition: 1  Leader: 2  Replicas: 2,3,1  Isr: 2,3,1

Filter Policies

# Replicate only specific topics
dc1->dc2.topics = orders.*, payments.*

# Exclude certain topics
dc1->dc2.topics.exclude = .*\.internal, .*\.temp

# Replicate by pattern
topics.regex = orders|payments|users

Offset Synchronization

Checkpoint Connector

# Offset sync configuration
emit.checkpoints.enabled = true
emit.checkpoints.interval.seconds = 60

# Consumer group translation
groups.enabled = true
groups = order-processor, payment-processor

The checkpoint connector is the piece that makes failover survivable, and its default cadence is one minute: every emit.checkpoints.interval.seconds it reads the positions the source-side group committed and writes them into a __consumer_offsets mirror in the destination cluster, renamed to the source prefix such as dc1.order-processor. That renaming is deliberate, so a group of the same name already running in the second datacenter is never clobbered. The consequence you must plan for is a window: fail the site over right after a checkpoint and the new consumer resumes roughly sixty seconds behind where the old one stopped, re-reading up to a minute of records. Mitigations exist and they are not free — the offset-sync topics written by emit.offset-syncs.enabled record positions far more frequently for precise recovery, shortening the checkpoint interval costs write traffic on both clusters, and applications that must not double-charge a customer handle duplicates with idempotency keys instead of trusting replication to be exact.

Offset Sync Example

python
# DC1 Consumer Group Offsets
{
    "group": "order-processor",
    "topic": "orders",
    "partition": 0,
    "offset": 152345,
    "timestamp": 1640995200000
}

# Synced to DC2
{
    "group": "dc1.order-processor",
    "topic": "dc1.orders",
    "partition": 0,
    "offset": 152345,  # Same offset
    "timestamp": 1640995200000
}

Failover with Offset Reset

python
from kafka import KafkaConsumer

# After failover, reset to synced offset
consumer = KafkaConsumer(
    'dc1.orders',
    bootstrap_servers=['kafka-dc2:9092'],
    group_id='order-processor-failover',
    auto_offset_reset='earliest',
    enable_auto_commit=False
)

# Manually seek to synced offset
offsets = get_synced_offsets('order-processor', 'orders')
for partition, offset in offsets.items():
    consumer.seek(partition, offset)

Failover Strategies

Failover is a decision, not a script, and the decision needs three inputs: is the primary really unreachable rather than just partitioned, is replication caught up enough for the recovery point objective, and is every producer already able to write to the secondary. The classic mistake is acting on the first input alone. A network partition between the two sites makes the primary look dead from the second site while it continues serving local traffic, and if you promote the secondary without fencing the first you end up with two clusters accepting writes for the same business entities. Real implementations therefore pair health checks with a lock in a system that both sites cannot reach simultaneously, keep producers behind a configuration service or a DNS name they must re-resolve, and refuse to promote while replication lag exceeds an agreed limit rather than promoting and quietly losing orders.

Detection speed sets the recovery time. A ten-second health check interval with three failures before acting means at least thirty seconds to notice, which is usually acceptable; a five-minute interval means users find the outage before your alerting does. Whichever you choose, measure the whole sequence in a drill — detection, promotion, client reconfiguration, catch-up — because the number that goes into the recovery time objective is that total, not the time it took the broker process to stop.

Active-Passive Failover

python
class KafkaFailoverManager:
    def __init__(self, primary_cluster, secondary_cluster):
        self.primary = primary_cluster
        self.secondary = secondary_cluster
        self.active = 'primary'
    
    def get_producer(self):
        if self.active == 'primary':
            return KafkaProducer(bootstrap_servers=self.primary)
        else:
            return KafkaProducer(bootstrap_servers=self.secondary)
    
    def failover(self):
        self.active = 'secondary'
        # Reset consumer offsets to synced position
        self.reset_consumer_offsets()
    
    def failback(self):
        # Ensure all data is replicated back
        self.wait_for_replication_complete()
        self.active = 'primary'

Health Check Configuration

python
import requests
from kafka import KafkaConsumer

def check_cluster_health(bootstrap_servers):
    """Check if Kafka cluster is healthy"""
    try:
        consumer = KafkaConsumer(
            bootstrap_servers=bootstrap_servers,
            request_timeout_ms=5000
        )
        # Check if we can list topics
        topics = consumer.topics()
        consumer.close()
        return True
    except Exception as e:
        print(f"Cluster health check failed: {e}")
        return False

# Monitor and failover
def monitor_and_failover(primary, secondary):
    while True:
        if not check_cluster_health(primary):
            print("Primary cluster failed, initiating failover")
            failover_manager.failover()
            break
        time.sleep(10)

Automatic Failover with ZooKeeper

python
from kazoo.client import KazooClient

class ZooKeeperFailover:
    def __init__(self, zk_hosts):
        self.zk = KazooClient(hosts=zk_hosts)
        self.zk.start()
    
    def watch_cluster(self, cluster_path, callback):
        @self.zk.DataWatch(cluster_path)
        def watch_node(data, stat):
            if data is None:
                callback('cluster_down')
            else:
                callback('cluster_up')

Active-Active Architecture

Bi-directional Replication

# Both directions enabled
dc1->dc2.enabled = true
dc1->dc2.topics = orders.*, payments.*

dc2->dc1.enabled = true
dc2->dc1.topics = orders.*, payments.*

# Prefix remote topics with the source cluster so mirrored copies
# (dc1.orders, dc2.orders) stay distinguishable from local ones
replication.policy.class = org.apache.kafka.connect.mirror.DefaultReplicationPolicy

# Never mirror back what just arrived from the other site
dc1->dc2.topics.exclude = ^dc2\..*
dc2->dc1.topics.exclude = ^dc1\..*

Active-active removes the promotion step and the single-writer discipline with it, so every write has to be safe to receive twice from two directions. MirrorMaker 2 will happily copy a topic back to where it came from unless the naming keeps the origin visible and an exclude pattern blocks the return path; without both, a single message can bounce between sites indefinitely while replication lag grows without bound. Beyond loops, you must decide what happens when both sites write the same key. Kafka offers no conflict resolution: replication preserves ordering within a partition but has no opinion about two partitions holding different values for the same business entity. Teams that need a rule usually pick one of three: give each entity a home region so conflicting writes cannot occur, keep cross-region events append-only so duplicates merge instead of overwriting, or resolve in the application using a domain rule that is safer than comparing timestamps, since clocks in two datacenters are never in perfect agreement.

Conflict Resolution

python
# Use unique keys to prevent conflicts
def produce_with_unique_key(producer, topic, message):
    # Add datacenter identifier to key
    key = f"{message['id']}-{get_datacenter_id()}"
    producer.send(topic, key=key.encode(), value=json.dumps(message).encode())

# Merge strategy for conflicts
class ConflictResolver:
    def resolve(self, dc1_message, dc2_message):
        # Last-write-wins based on timestamp
        if dc1_message['timestamp'] > dc2_message['timestamp']:
            return dc1_message
        return dc2_message

Monitoring Multi-DC Replication

Key Metrics

# Prometheus metrics to monitor
metrics:
  - name: mirrormaker_replication_latency
    description: "Replication latency between DCs"
    threshold: "> 1000ms"
    
  - name: mirrormaker_replication_lag
    description: "Messages pending replication"
    threshold: "> 10000"
    
  - name: mirrormaker_replication_rate
    description: "Messages replicated per second"
    alert: "< expected_rate * 0.5"

Monitoring Dashboard

{
  "panels": [
    {
      "title": "DC1 to DC2 Replication Lag",
      "type": "timeseries",
      "targets": [
        {
          "expr": "sum(mirrormaker_replication_lag{source='dc1', target='dc2'})",
          "legendFormat": "{{topic}}"
        }
      ]
    },
    {
      "title": "Replication Latency",
      "type": "timeseries",
      "targets": [
        {
          "expr": "histogram_quantile(0.99, mirrormaker_replication_latency_bucket)",
          "legendFormat": "p99 latency"
        }
      ]
    }
  ]
}

Disaster Recovery Testing

Regular DR Drills

#!/bin/bash
# dr_drill.sh

echo "Starting DR drill..."

# 1. Verify replication status
kafka-mirror-maker.sh --describe --mm2-cluster dc1-to-dc2

# 2. Simulate primary failure
kubectl scale statefulset kafka-dc1 --replicas=0

# 3. Verify failover
sleep 30
check_consumer_lags --cluster dc2

# 4. Failback
kubectl scale statefulset kafka-dc1 --replicas=3

# 5. Verify replication restored
verify_replication_complete --mm2-cluster dc1-to-dc2

A drill only proves what it exercises. Scaling the primary stateful set to zero tests broker failover, but it does not test the certificate expiring in the second site, the stale DNS record clients cached, the ACL that exists only in the primary, or the consumer group whose checkpoint never advanced because the connector had been failing for a day. Schedule the full sequence quarterly, record the elapsed time from detection to healthy consumers in the second site, and compare that number with the recovery time objective you published — if the drill took 42 minutes and the objective says 15, the fix is process and client configuration, not more brokers. Failback deserves the same scrutiny: drain the mirrored backlog, confirm both directions are current, and only then return traffic to the primary, because an early failback discards everything the second site accepted while it was authoritative.

Common Mistakes

Promoting the second site as soon as the primary stops answering health checks

Fix: Gate promotion on replication lag being inside the recovery point objective and fence the old primary with a lock neither site can hold at the same time

Relying on a checkpointed offset as if it were the consumer's real position

Fix: Account for up to emit.checkpoints.interval.seconds of re-read after failover, or shorten the interval and deduplicate with idempotency keys

Naming mirrored topics with the identity policy in an active-active setup

Fix: Keep the source-cluster prefix from the default replication policy and add a topics.exclude pattern on each link so data never bounces between sites

Summary

Multi-datacenter Kafka replication with MirrorMaker 2 provides robust disaster recovery and geo-redundancy. Implement proper offset synchronization, failover strategies, and active-active configurations to ensure high availability across datacenters.

See Also

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-16

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Kafka Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement