Skip to content

Checking your reading list…

Retry verification

Stay curious. Build better.

Appearance

Choose how BestHub looks on this device.

Changes apply immediately.

Search articles

Open Discover with these filters

Suggested searches

RocketMQ HA: Master-Slave Replication, Dledger Raft, and Production Failover Strategies

RocketMQ HA: Master-Slave Replication, Dledger Raft, and Production Failover Strategies

This article details RocketMQ's high availability mechanisms, covering master-slave replication models, HA replication internals, synchronous vs asynchronous trade-offs, Dledger's Raft-based consensus for automatic failover, migration strategies, production configurations, monitoring practices, and source code analysis of core replication and election logic.

Overview

This article provides a comprehensive analysis of RocketMQ's high availability (HA) system, focusing on master-slave replication and the Dledger Raft-based consensus module. It explains the replication topology, HA kernel internals, synchronous vs asynchronous replication trade-offs, master-slave latency monitoring, read-write separation, Dledger's automatic leader election, migration strategies, production configurations, operational checklists, and core source code walkthroughs. The author emphasizes that true HA requires three capabilities: replication (data durability), detection (failure visibility), and failover (write takeover) — traditional master-slave only provides replication, relying on monitoring and manual operations for the other two, while Dledger automates detection and failover via Raft.

1. Master-Slave Replication Model: Pairing and Groups

Topology rule: nodes with the same brokerName form a master-slave pair; brokerId=0 is master, non-zero is slave. Clients treat the pair as a single routing unit — writes always go to brokerId 0, reads can be diverted to slaves if configured. Common misconfigurations: slave's brokerName mismatches master (no replication relationship), or brokerIP1 set to an internal alias causing HA connection to wrong address (replication never establishes). Verification: mqadmin shows master listing slave address and slave reporting connection status.

NameServer only handles routing, not decisions: brokers heartbeat every 30s, clients pull routes every 30s. Master failure is not immediately detected — route convergence waits for heartbeat expiration (default 2 minutes), during which clients may still write to the dead master until connection failure triggers retry (fault avoidance from previous article). Traditional master-slave failover always includes two waits: route convergence (seconds to minutes) + human decision (depends on team readiness). Dledger addresses the latter.

Replication and flush are independent 2x2 configurations: brokerRole controls "replica existence": SYNC_MASTER waits for slave ack, ASYNC_MASTER returns immediately, SLAVE marks node as replica. flushDiskType controls "local durability": SYNC_FLUSH waits for fsync, ASYNC_FLUSH returns after page cache write.

Four combinations mapped to business criticality: financial transactions use SYNC_MASTER + SYNC_FLUSH (highest latency, survive machine/disk failure); general business uses SYNC_MASTER + ASYNC_FLUSH (machine crash loses only last few ms, reconciled by accounting); logging/telemetry can use full async. Common accident: confusing SYNC_FLUSH with SYNC_MASTER — thinking replicas are safe when only local flush is stricter.

Why not SYNC_FLUSH + ASYNC_MASTER? It promises "local durability, replica optional" — if master disk fails, data gap appears immediately. Only suitable when upstream can replay. The four combos are codified in middleware specs and verified during new pipeline onboarding (see article 05 "Reliability Levels").

2. HA Replication Kernel: Push and Report

HA replication runs on a dedicated TCP long connection (default port 10912) with a minimal protocol: master actively pushes incremental log data; slave unidirectionally reports its offset.

Master side: After CommitLog appends new messages, HAService detects replicable offset change, wakes all HAConnection s, sends incremental packets per slave's synced offset.

Slave side: HAClient maintains long connection (5s reconnect), writes received data directly to local CommitLog — no consumption, no index build, pure log replication — then reports its maxPhysicOffset to master.

Core data structure: inSyncReplicas = minimum offset reported by all slaves — represents "safety watermark covered by all replicas". Synchronous replication waits here: SYNC_MASTER write requests block until inSyncReplicas advances past the write's offset; ASYNC_MASTER returns immediately, data may not have left NIC.

Synchronous replication latency breakdown: single write P99 = local flush + slave flush network RTT. In 1ms LAN RTT, extra latency typically <2ms — far cheaper than "crash loses data", hence general business recommended SYNC_MASTER.

Link failure manifestations differ critically for on-call troubleshooting: ASYNC_MASTER disconnect is silent — writes succeed normally, replication stall only visible in metrics, business unaware until crash (root cause of Incident 1). SYNC_MASTER disconnect hangs writes — write requests wait for slave ack, manifest as write RTT spike, retry exhaustion (Incident 2 scene), often misdiagnosed as DB slowness.

Common troubleshooting entry: broker HA status logs and master-slave diff metric — seeing "offset report stop" or "diff persistently non-zero" points to link issues, don't circle in business layer.

Master-slave diff monitoring caliber: Metric = master replicable offset - inSyncReplicas. Normal: MB-level fluctuation, second-level catch-up. Two alert lines: (1) sustained > threshold (e.g., 64MB > 1 min) indicates replication bandwidth or slave processing lag; (2) long-term non-zero but static indicates report stopped (link issue). Two lines map to two fixes; alert message includes remediation action so on-call doesn't reason on scene.

3. Master-Slave Latency and Read-Write Separation

Latency cause: replication bandwidth limited while writes are bursty. Replication is single-channel serial between master and slave; large batch pushes (marketing blasts, bulk imports) or large message storms (images, big payloads) saturate channel, queuing writes on slave side. Latency window = queued bytes / replication bandwidth. Measurement uses broker_a_diff (master-slave offset delta) plus slave lag bytes, assisted by observing report interval stability — lengthening interval often precedes link congestion.

Read-write separation implementation: slaveReadEnable=true lets consumers select read nodes by "replication latency gradient" — default reads master; only when request's tolerated latency (latencyLevel gradients: 5s, 10s, longer) can be satisfied by slave's replication lag does read downgrade to slave. Boundary clarification: this is "stale-read diversion for latency tolerance", NOT strong consistent read — data read is within replication lag window; business must accept (e.g., analytics, retry compensation); ordered consumption and "offset mismatch" scenarios must not enable diversion — offsets absent on slave cause empty pulls. Pragmatic advice for small/medium clusters: keep slaves for disaster recovery and drill resources, enable diversion only when needed, don't introduce stale-data complexity to save minor read traffic.

Incident 1 mechanism review as checklist: slave disconnects, HAClient retries every 5s, but if slave network or master address config broken, reconnect forever fails — while ASYNC_MASTER writer feels nothing. Two weeks silent degradation showed all green: master process up, port reachable, write RTT normal, consumption normal. Replica health cannot be judged by "process alive" but by "offset advancing" behavioral metric — exactly why Incident 1 root cause fix wired master-slave diff to alert: diff static = replication stopped, even if both processes healthy.

On-call caliber: Master-slave diff alert → first distinguish "report stopped" (link issue, fix network/config) vs "steady growth" (bandwidth/backlog, throttle or scale). Don't restart master directly — restart interrupts writes and doesn't fix link. Under SYNC_MASTER , slave disconnect manifests as write hang not error; on-call seeing "write RTT spike + broker no error" combo, first check master-slave diff and report interval.

4. Dledger: Protocol Decides Who Is Master

Traditional master-slave three capability gaps — no auto-detection, no auto-failover, strong consistency relies on config discipline — Dledger fills all via Raft. Dledger is RocketMQ 4.5+ built-in distributed log library, attaching CommitLog multi-replica management to Raft:

Typically 3 replicas (extensible to 5), one Leader accepts writes, others Followers.

Write flow: Leader appends local log, sends AppendEntries to Followers, advances commit index and returns success to client only after majority ack.

Follower down one: writes continue (majority alive); two down: group unwritable — 3 replicas tolerate 1 failure, 5 tolerate 2.

Leader election follows standard Raft five steps:

Follower heartbeat timeout

Become Candidate, increment term

Request votes from all

Obtain majority votes, become Leader

Send heartbeats to take over

Two critical voting constraints:

One vote per term (first-come-first-served, prevents duplicate election).

Vote includes log completeness check — candidate with longer log gets vote.

Second constraint is data safety root: new Leader always contains all committed logs, never elects "data-missing master", so failover needs no manual reconciliation — protocol guarantees committed data not lost. Split-brain prevented by majority constraint: any decision (election, commit) requires majority; two majorities must intersect, so at most one majority operates. During partition, old Leader side lacking majority ack fails writes and steps down; new Leader emerges in majority side — no dual-master writes. Note minority side becomes unavailable, which is correct protocol behavior.

Essential difference in one sentence: Master-slave replication = "operations decides who is master"; Dledger = "protocol decides who is master" — failover from manual minutes to automatic seconds, and during switch writes either succeed (majority durable) or explicitly fail (client retryable), eliminating "returned success but actually lost" gray zone. Costs are explicit: Leader write waits majority RTT, P99 higher than old async replication; ops gains a Raft group monitoring surface and version requirements; crucially Dledger data format differs from old CommitLog — existing cluster migration is "new group new writes", not in-place upgrade (detailed next section). Selection pays three bills: trade seconds auto-failover + strong consistency for write latency + new ops surface.

Why general business may not need Dledger: Dledger's core value (auto-election + strong consistency) is overkill for teams where "manual recovery within 10 minutes" is acceptable — SYNC_MASTER master-slave + drill discipline already covers. Truly needing Dledger are three categories: write volume too high for manual failover window, transaction loss requires "no loss" not "recoverable", team lacks 7x24 on-call. Choose by team shape, not technical advancement.

5. Migration and Selection: Three Routes

As of 4.5+, RocketMQ HA has three routes:

Traditional master-slave (since 2.x): no auto-failover, simplest ops, lowest latency.

Dledger (Raft group): auto second-level election, strong consistency, slightly higher P99.

Controller mode (4.5+ new): retains old storage engine but adds external Controller component for failure detection and master-slave failover — compromise for existing master-slave clusters to gain auto-failover without storage change: data format unchanged, near-zero migration cost; cost is extra component ops, and consistency guarantee weaker than Dledger (in-flight data during switch relies on config and reconciliation).

Decision tree four branches:

Only need backup + read diversion, can accept manual failover → Traditional master-slave (config SYNC_MASTER, wire diff alert, do drills).

Require auto-failover + strong consistency → Dledger 3 or 5 replicas.

Existing master-slave wants auto-failover, don't want storage change → Controller mode.

Regardless of route, must do failover drills — master-slave drill "manual failover recovery time", Dledger drill "kill Leader, measure new election + route convergence". Documentation reading doesn't count. Drill records three numbers in runbook: election (or switch) duration, client route convergence duration, write loss window during event — next incident handled by the book.

Dledger migration correct posture is three-step, core idea: data not cross-format moved, transition via business-level dual-write :

Create new Dledger group, start dual-write (old and new topics parallel write, independent consumption verification).

Stop writes to old group, let consumption catch up, data reconciliation (by business key count match between two groups).

Switch client routing to new topic, observe one business cycle, then decommission old group.

Forbid in-place config change: pointing old broker directory to Dledger config mixes old CommitLog with new Dledger logs in same directory — offset system and recovery logic completely mismatch (Incident 3 scene). Dual-write ordering handled separately: same business key must write to both groups in same order, else cross-group disorder during switch — use selector key rules from article 06 to keep consistent.

Replica count and deployment three details: (1) Dledger group nodes must cross rack/AZ deploy — three machines in same DC cannot survive DC failure; (2) Groups independent (broker-a, broker-b each a Dledger group), no cross-group election; (3) allAckInSyncStateSet (wait all replicas) vs default majority ack difference chosen by loss tier — general business majority sufficient, money chain can tune full ack, cost: any single failure makes writes fail.

6. Production Practice: Config, Health Check, On-Call

6.1 Master-Slave Baseline Config

Complete copy-paste baseline (master and slave annotated with diff items):

# ==== master (broker-a) ====
brokerClusterName=DefaultCluster
brokerName=broker-a
brokerId=0                  # 0 = master
brokerRole=SYNC_MASTER      # synchronous replication
flushDiskType=ASYNC_FLUSH   # async flush
# General business combo: SYNC+ASYNC_FLUSH
haListenPort=10912          # HA replication port
brokerIP1=10.0.1.11         # HA connection address
# slave side: brokerId=1
#   brokerRole=SLAVE
#   brokerIP1=10.0.1.12
slaveReadEnable=false       # read diversion on demand
haMasterAddress=10.0.1.11:10912
heartbeatCluster=true       # cluster heartbeat
# Alert lines (wire to monitoring):
#   master-slave diff > 64MB sustained 1 min
#   diff long-term non-zero and static (report stopped)
#   slave disk water > 80%

Three disciplines beyond config:

Master and slave brokerName must match — onboarding health check verifies pairing (master lists slave, slave reports connection). brokerRole and flushDiskType written into baseline patrol — actual config vs promised tier mismatch = P0 (same discipline as article 05 Incident 2, re-verified at replica layer). SYNC_MASTER group slave monitoring same weight as master — slave disk water, HA connection status, offset report interval all need alerts, because it's now in write path.

6.2 Dledger Group Full Config

# ==== Dledger broker (n0) ====
brokerClusterName=RaftCluster
brokerName=broker-a
enableDLegerCommitLog=true  # enable Dledger
dLegerGroup=broker-a        # group name
dLegerPeers=n0-10.0.1.11:40911;
n1-10.0.1.12:40911;
n2-10.0.1.13:40911
# line-end \ for properties continuation
dLegerSelfId=n0             # this node ID
storePathRootDir=/data/rocketmq
# three nodes three independent dirs
# Migration discipline:
#   1. New group dual-write (old+new topics parallel)
#   2. Old group stop-write, consumption catch-up, reconcile
#   3. Cut traffic, decommission old group
#   FORBID in-place config change restart

Dledger group ops points: three nodes' dLegerPeers list identical, dLegerSelfId each unique; group nodes must cross rack/AZ, else DC failure kills whole group; version requires 4.5+, recommend newer (early versions had election/recovery fixes). Monitoring focus differs from master-slave: watch Leader stability (frequent leadership change indicates network jitter or disk slowness), AppendEntries replication lag, majority ack wait watermark — Raft group "healthy" defined as "Leader stable + replication smooth", not "three processes alive".

6.3 HA Health Check Checklist

Onboarding and patrol each pass these eight items: brokerName pairing verification (master lists slave, slave connects master). brokerRole and flushDiskType match promised tier and in baseline patrol.

Master-slave diff metric wired to alert (sustained growth + report stopped two lines).

Slave disk water and HA connection status have alerts (SYNC group same weight).

Read-write diversion enabled matches business tolerance (ordered pipelines not enabled).

Failover drill institutionalized (master-slave monthly failover, Dledger monthly kill Leader), duration data into runbook.

Dledger group cross-rack/AZ deployment verified.

Migration follows three-step dual-write, forbid in-place config change.

Items 1,2,4 correspond to three incidents — these eight turn "HA looks complete" into "every segment verified".

6.4 On-Call Caliber: Three HA Alert Handlings

Master-slave diff sustained growth: First check if slave report stopped (link issue, fix network/config) or steady growth (bandwidth/backlog, throttle or scale). Don't restart master directly — restart interrupts writes and doesn't fix link.

Write RTT spike + broker no error: SYNC group first check slave status (disk full, HA disconnect, offset stall) — this is Incident 2 scene. After confirming slave failure, can temporarily switch to

ASYNC_MASTER</sub> to stop bleeding (accept replica gap in window, record, reconcile post-incident).</li>
<li><strong>Dledger frequent leadership change:</strong> First check inter-node network quality (packet loss, jitter) and disk IO latency (slow fsync prolongs heartbeat processing). Don't scale business traffic until stable — Raft group demands higher network stability than master-slave.</li>
</ul>

<h2>7. Core Source Code: Four Key Implementations</h2>
<h3>Segment 1: Master Push Loop</h3>
<p>CommitLog new data wakes connections to push:</p>
<pre><code>// master: HAService main loop (simplified)
public void run() {
while (!isStopped()) {
// wait wake: new message written or timer
this.waitForRunning(5000);
// notify all slave connections
// push incremental by each's synced offset
for (HAConnection conn :
connectionList) {
conn.notifyTransferSome(
commitLog.getMaxOffset());
}
}
}

Segment 2: Slave Report Offset

Receive data, write local log, report progress:

// slave: HAClient receive handling (simplified)
private void processReadEvent() {
// read log data pushed by master
int size = socketChannel.read(
readBuffer);
if (size > 0) {
// directly append local CommitLog
boolean ok = commitLog.append(
readBuffer, size);
if (ok) {
// report new offset to master
reportOffset += size;
sendReport(reportOffset);
}
}
}

Segment 3: Synchronous Replication Wait and Wake

inSyncReplicas coverage releases:

// master: synchronous replication wait (simplified)
private boolean doWaitTransfer(
long nextOffset, int ackNums) {
int notCovered = 0;
for (HAConnection conn :
connectionList) {
long slaveAck =
conn.getSlaveAckOffset();
if (slaveAck < nextOffset) {
notCovered++;
}
}
// uncovered count within tolerance passes
if (notCovered <=
connectionList.size()
- ackNums) {
// wake writer threads waiting on ack
notifyWriterOK();
return true;
}
return false;
}

Segment 4: Dledger Election Vote Handling

Term and log completeness dual constraints:

// Dledger: vote request handling (simplified)
public VoteResponse handleVote(
VoteRequest req) {
// term behind: reject
if (req.getTerm() < curTerm) {
return reject(OLD_TERM);
}
// log completeness: longer log gets vote
if (req.getLastLogIndex()
< lastLogIndex) {
return reject(LOG_SHORT);
}
// one vote per term
if (votedTerm == req.getTerm()
&& votedId != req.getId()) {
return reject(ALREADY);
}
// record vote and refresh heartbeat timer
votedTerm = req.getTerm();
votedId = req.getId();
lastHeartbeat = clock();
return grant();
}
Source code reading thread: Segment 1 is "new data pushes", segment 2 is "receive, persist, report progress", segment 3 is "majority coverage confirms", segment 4 is "vote recognizes log not relationship". Four segments connected, replication mechanism boundary and Dledger safety boundary fully visible — Incident 1 "silent degradation" breaks at segment 2 report, Incident 2 "write hang" blocks at segment 3 wait, Incident 3 "offset chaos" faults at mixing two engines in one directory.

8. Seven Bills: Real Cost of HA

Latency bill. SYNC_MASTER adds one LAN RTT per write (typically <2ms), SYNC_FLUSH adds one fsync — HA's first cost is latency, pay by business tier, no one-size-fits-all.

Monitoring bill. Replica health by behavioral metrics not process metrics: master-slave diff, report interval, HA connection status, slave disk water — four alert lines are minimum for "HA visible". Incident 1's two-week silent degradation essence is this bill unpaid.

Drill bill. Failover capability doesn't exist without drill: monthly failover (or kill Leader), on-call duration, route convergence, loss window three numbers into runbook. Drill consumes minutes of window, buys certainty at incident scene.

Selection bill. Traditional master-slave simplest ops but failover manual; Dledger auto-failover + strong consistency but higher P99, new ops surface; Controller compromises — pick by team shape (on-call capability) and loss requirement, not technical advancement.

Migration bill. Dledger migration must new-group dual-write transition: dual-write period doubles writes, ordering must preserve, reconciliation must run — migration cost far higher than "config change restart", but Incident 3 proves skipping this bill costs more.

Replica bill. 3 replicas tolerate 1 failure, 5 tolerate 2 — each added replica is 3x storage + 1x replication bandwidth. Dledger group cross-DC deploy hard requirement, inter-DC RTT directly into write latency.

People bill. HA ultimately lands on people: will on-call handle per caliber, are drill records maintained, is migration runbook executed — these three "have or not" decide real recovery time at incident scene more than any config.

9. 20 Interview Questions (with Answers)

The article includes 20 detailed Q&A covering topology rules, brokerRole vs flushDiskType, sync vs async behavior, HA protocol flow, inSyncReplicas definition, master-slave diff measurement/alerting, read-write separation enablement/boundaries, slave disconnect SYNC/ASYNC manifestations, traditional master-slave pain points, Dledger purpose, Raft election flow, majority commit durability, why new Leader has all committed logs, Raft split-brain prevention, Dledger replica count/deployment, Dledger vs master-slave trade-offs, Controller mode, Dledger migration correct posture, failover drill methodology, and HA solution selection decision tree. Each answer is concise and technically precise, suitable for interview preparation.

10. One-Page Cheat Sheet

HA Nine Sentences: brokerName pairing makes master-slave: master lists slave, slave connects master. brokerRole and flushDiskType each manage one thing: replica existence vs local existence — don't confuse. HA is push + report: master pushes incremental, slave reports offset. inSyncReplicas is safety watermark: synchronous replication waits for it. Replica health by behavior not process: diff stall = replication stopped. ASYNC disconnect silent, SYNC disconnect hangs: failure manifestation dictates troubleshooting entry. Raft vote recognizes log not relationship: new Leader must contain all committed logs. Dledger migration is group swap not upgrade: three-step dual-write, forbid in-place config change. Failover capability doesn't exist without drill: duration data into runbook.

11. Summary and Next Article Preview

HA is the product of three capabilities: replication, detection, failover. Traditional master-slave uses brokerRole for replication, monitoring for detection, drills for failover; Dledger pushes latter two into protocol, majority commit turns "no loss" from config discipline into mathematical guarantee. Selection criterion is team shape and loss requirement, not technical advancement : teams with on-call capability, master-slave + drills suffice; no on-call or strong consistency needed → Dledger. Most forbidden is stopping at "configured master-slave but never drilled" intermediate state — that's paper HA, incident scene only amplifies its gaps. Cross-article memory anchor: Article 04 "three water gates" guard disk, Article 05 "flush/replication combos" guard single-node durability, this article "master-slave and Raft" guard machine-level failure — storage reliability is concentric circles expanding outward: in-process, intra-machine, inter-machine, inter-DC . Each layer expands with new costs (latency, monitoring, drills), and each layer's promise builds on the previous — SYNC_MASTER's "no loss" builds on Article 04's disk system, Dledger's "no loss" builds on committed log definition. Troubleshooting starts with "which layer lost", fix converges automatically. Next article "Performance Tuning" enters series technical closure: full-chain performance accounting — write side (flush strategy, batch send, compression), replication side (HA bandwidth/latency), consume side (concurrency/batch), JVM/OS coordination (off-heap, page cache, file handles), and "measure first then tune" load test methodology — stitching scattered performance knowledge from previous articles into a complete tuning map.

About this article

For questions about attribution, corrections or content rights, please contactadmin@besthub.devand we will review it promptly.

Distributed SystemsMigrationMonitoringHigh AvailabilitySource Code AnalysisMessage QueueRocketMQFailoverRaft ConsensusMaster-Slave ReplicationDledgerAsynchronous ReplicationSynchronous ReplicationHA Replication

Discussion 0

Questions, practical examples and thoughtful responses.

Open full discussion