RocketMQ Reliability Deep Dive: Three-Phase Model, Transaction Messages & Atomic Guarantees
This article details RocketMQ's end-to-end message reliability through a three-phase model (send, store, consume), transaction messages using half-messages and a check-back mechanism to atomically bind local transactions with message delivery, idempotency design, reconciliation fallback, and production-grade configurations with real incident postmortems.
Reading font
Overview: Reliability as a Contract, Not a Switch
Message reliability is not a single configuration but a chain of acknowledgments and compensations across six gates: send acknowledgment, network, storage persistence, delivery, consumption execution, and result acknowledgment. Each gate can lose messages; any gate assuming "someone else handles it" breaks the chain. The correct reliability review walks the chain segment by segment: does each segment have a "confirmed-only-counts" mechanism? Does failure have a destination? Does retry have idempotency guard? Only when all three questions pass is the segment closed-loop.
Three-Phase Reliability Model
The model divides responsibility into three segments:
Send segment (producer → broker): ensures "acknowledged as received". Loss points: callback only logs, oneway fire-and-forget, retry exhausted silently abandoned.
Storage segment (broker internal): ensures "persistence and redundancy". Loss points: async flush crash loses a window, no replicas, watermark rejection.
Consumption segment (broker → business result): ensures "business landed". Loss points: commit offset before crash, retry exhausted into DLQ unwatched, no idempotency polluted by duplicates.
Responsibility boundaries are clear: before producer receives ACK → sender's account; after ACK until consumption → broker's account; after broker delivers but business not landed → consumer's account. First troubleshooting question: "Which segment lost it?" Segment location automatically maps tools and playbooks.
End-to-end promise = send_ack × storage_durable × consume_ack × idempotent_dedup × reconciliation_fallback. Multiplicative relationship: any factor zero → overall zero. Sync flush to financial grade but sender uses oneway → still loses. Consumer idempotency perfect but offset commit before processing → still loses. Reliability review must find the shortest board, not admire single high-end configs.
Send Segment: Acknowledgment Chain & Retry
2.1 Synchronous Acknowledgment Five-Step Chain
Sync send acknowledgment chain: encode request → network write → broker flush (wait fsync if sync flush) → replication ack (wait replica if sync replication) → ACK return. Any step fails (timeout/exception), client switches broker and retries (fault latency avoidance from previous article). Critical insight: timeout ≠ failure — first request may have persisted, only ACK lost; retry causes duplication. This is the mechanistic root of "sender retry + consumer idempotency are a bound pair".
Sync retry time budget: sendMsgTimeout (default 3000ms) × (1 + retryTimesWhenSendFailed default 2) = caller waits up to 9 seconds. Two direct corollaries:
Upstream interface timeout must exceed 9 seconds, otherwise retry gets cut off into fake failures (many "failures" in Incident 1 were actually upstream timeout truncating retry).
For latency-sensitive interfaces, actively shrink budget (e.g., 2s × 1 retry), adopt "fast fail + compensation" strategy instead of dead waiting. Budget is essentially "business-acceptable queue upper bound", must be reviewed together with business interface.
2.2 Correct Asynchronous Send Posture
Async send throughput dividend has a price: acknowledgment deferred to callback thread — callback doing nothing = no acknowledgment . Correct posture checklist:
Callback splits by send status.
Failed messages written to compensation table (same DB as business transaction), carrying original message body and retry count.
Scheduled job scans compensation table for re-send; still failing escalates to manual.
Send success rate per topic into monitoring dashboard.
This "async + persist + re-send" combo achieves near-async throughput with near-sync reliability, costing one compensation table and one re-send job — the sweet spot for most businesses.
oneway applicability boundary: it gives up even the chance to "know failure" . Only for losable scenarios (telemetry, heartbeat, recomputable logs). Any transaction chain forbids oneway — write into code standard, not just docs, because oneway code looks clean and passes review easily. Litmus test: if this message is lost, is there another path to recover it? Yes (log replayable, telemetry补采) → allow oneway.
Transaction Messages: Half-Message Two-Phase Commit
Transaction messages solve exactly one problem: atomicity of "local transaction success" and "message sent" . Two naive paths both broken: send then commit → transaction fails, message cannot retract; commit then send → send fails, business already effective. RocketMQ reorders: message lands first (half-message) → execute business → tell broker result.
Producer sends half-message (stored in system topic RMQ_SYS_TRANS_HALF_TOPIC, invisible to business subscribers).
Broker acknowledges receipt → execute local transaction (business + state table same DB transaction).
Return COMMIT → half-message promoted to real topic for delivery; ROLLBACK → half-message deleted; UNKNOW or timeout → enters check-back flow.
Half-message design guarantees "message already durable during transaction execution, yet not prematurely consumed". Even if process crashes mid-transaction, half-message remains on disk, check-back mechanism can complete. This distinguishes from "local message table" approach: state guaranteed by broker, not dependent on business scheduled scan.
Boundaries: transaction messages do not guarantee consumption success (that's consumption segment's ack/retry), and do not provide local transaction rollback capability (check-back only queries state, cannot modify business). Therefore local transaction must be "idempotent and queryable": state persisted first, then slow ops; at any crash moment, check-back can read fact from DB. Often misused as "distributed transaction silver bullet"; correct understanding: it only welds "transaction success ⇔ message must arrive" seam; upstream/downstream reliability each need their own acknowledgment chains.
Transaction Check-Back: Three Chances & Idempotent Design
Check-back trigger: half-message exceeds check-back interval (default 60s) still unresolved — producer crash restart, transaction result unknown, network disconnect all lead here. Broker's TransactionalMessageCheckService periodically scans unresolved half-messages and initiates check-back. Producer's checkLocalTransaction called, only three legal returns :
COMMIT_MESSAGE (state table = success, half-message promoted)
ROLLBACK_MESSAGE (state table = fail, half-message deleted)
UNKNOW (state undetermined, wait next round)
Check-back has upper limit (transactionCheckMax default 15). Exceeding limit → half-message moves to dead-letter topic and logs. Therefore "no record found" correct return is UNKNOW (wait for fact), returning ROLLBACK amplifies DB jitter into business loss (Incident 3 root cause).
Check-back executor three iron laws:
Read-only, no writes — check-back is "query fact", replaying business logic in executor guarantees disaster (duplicate orders, duplicate deductions all originate here).
Trust only state table — memory variables, app logs, ThreadLocal cannot be basis, because check-back may execute on another cluster instance.
No record → return UNKNOW — as long as state table write and business write are in same DB transaction, record eventually queryable; UNKNOW just means "reply later".
State table anchor design: transaction_id PK + state (INIT/DONE/FAIL) + biz_key + updated_at, same DB as business table, written in business transaction — query state = query business fact.
Consumption Segment: Offset Acknowledgment, Retry & Idempotency
Consumption reliability starts with "acknowledge after business processing". In concurrent mode, RocketMQ advances offset only after all messages in batch return CONSUME_SUCCESS; RECONSUME_LATER or exception throws message back to retry queue (%RETRY%topic) with delay levels, exceeding maxReconsumeTimes (default 16) → dead-letter queue %DLQ%. So "process then commit" is framework default; message loss holes usually at: manual early ACK (autoCommit misuse), or listener swallows exception and returns success — offset only advances confirmed-completed interval, exceptions must truthfully propagate for framework to decide retry .
Retry & DLQ ops: DLQ is consumption segment's final destination, must have monitoring and replay plan — DLQ pile >0 and growing alerts; manual confirm then replay via compensation tool or new consumer group. Retry exhausted messages don't "auto disappear" but "become dead-letter waiting for you"; nobody watches DLQ = turn "consumption failure" into "business loss". Retry queue delay levels (10s to 2h exponential backoff) give downstream self-heal window; maxReconsumeTimes tuned smaller can enter DLQ faster for earlier manual intervention — set by business failure handling capacity, not blindly default.
Consumption idempotency is reliability's mirror face: retries (sender retry, broker redelivery, consumer retry) inevitably produce duplicates, reliability scheme without idempotency is incomplete . Standard implementation: business unique key deduplication table — consumption logic first step insert dedup record (unique key conflict = duplicate), same transaction as business write — either both happen or neither. Dedup key uses business unique key (order_id), not msgId (msgId changes on redelivery). Dedup table needs expiration cleanup (retention covers max retry window ~4.5h default, keep 24h safe), else ever-growing hurts performance — aligns with previous article IndexFile message key design principle: one key serves query, dedup, aggregation three purposes.
Idempotency Layers
DB layer unique key (strongest)
Application layer dedup table (second, must be same transaction as business)
Cache layer setnx (weakest, restart loses guard)
Money chains at least first two layers. Anti-pattern: "check exists then insert" for idempotency (concurrency guaranteed to leak), unique constraint is concurrency safety's last defense.
End-to-End Fallback: Reconciliation & Compensation
First three segments' acknowledgment chains push loss probability extremely low, but "extremely low" ≠ zero — extreme window between ACK and persistence, disk-level faults, check-back limit exceeded are probability tails. Reconciliation is reliability's last levee : by business dimension (order, payment) periodically compare "upstream fact table" with "downstream result table", missing triggers compensation (re-send message or directly execute business action). Reconciliation granularity and frequency by asset sensitivity: financial T+0 minute-level, general business T+1 daily — value: turn "extreme window loss" from "lost forever" into "delayed repair".
Reconciliation system three design points:
Upstream fact first — all business actions first land a record in fact table (state PENDING), message send and downstream processing revolve around fact table state flow, so reconciliation has "correct baseline".
Compensation must be idempotent — compensation is essentially replay, shares same dedup key as consumption idempotency.
Alert tiering — reconciliation finds missing → auto compensate → compensate fails escalate manual → manual tickets have ledger traceable. Write these three into transaction system design template for true end-to-end closed-loop.
Reliability Tiers & Cost: Buy Acknowledgment by Business Level
Every acknowledgment level has real cost: sync send adds one RTT, sync flush adds one fsync (P99 disk-bound), transaction messages add half-message + check-back complexity — same traffic, L3 combo send P99 typically 10x+ L1. Correct posture: classify business first, then configure combo by tier :
L1 log/telemetry (oneway or async, allow small loss)
L2 general business (sync send + async flush + sync replication + idempotency fallback)
L3 transaction/financial (sync send + sync flush + sync replication + transaction messages + state table + reconciliation fallback)
Tiering written into middleware selection spec; new chain onboarding maps to tier — buying transaction messages for telemetry is waste, configuring oneway for financial chain is accident.
Degradation matrix as important as tiering: any L3 item degraded → promise drops to L2 or L1 — review must annotate each item "if this degrades can business accept?" If cannot answer, add monitoring and plan (Incident 2 lesson). Remember cheapest cost rung: fallback always one tier cheaper than acknowledgment — reconciliation + compensation catches "extreme window loss" cheaper than making all segments sync; assign "extremely low probability" to reconciliation, spend "acknowledgment cost" on high-frequency paths — that's engineering reliability budget allocation.
Production Practice: Reliability Config & Health Checks
8.1 Producer Baseline Config (Annotated)
# ==== Send Acknowledgment (Reliability Core) ====
sendMsgTimeout=3000 # Single timeout
retryTimesWhenSendFailed=2 # Sync retry 2 times
retryTimesWhenSendAsyncFailed=2
retryAnotherBrokerWhenNotStoreOK=true
# Switch broker on flush/replication failure
# ==== Transaction Messages (Transaction Producer Required) ====
producerGroup=tx-order-producer
# Transaction check-back relies on group to locate producer
# ==== Consumer Acknowledgment ====
consumeTimeout=15 # Consume timeout (minutes)
maxReconsumeTimes=5 # Retry 5 times → DLQ
# DLQ pile into alert, replay plan readyThree disciplines beyond config:
Upstream interface timeout must exceed send retry total budget (9s), else retry truncated into fake failure.
Async callback must split by status, failure into compensation table not just log.
Transaction producer and normal producer separate groups — check-back locates instance by producerGroup; mixed group risks hitting instance without transaction listener, check-back spins empty.
8.2 Broker Transaction Check-Back & Idempotency Tables
# ==== Broker Transaction Check-Back Params ====
transactionTimeOut=6000 # Timeout judgment (ms)
transactionCheckMax=15 # Check-back upper limit
transactionCheckInterval=60000
# Check-back interval, longer half-message stay = larger window
-- Transaction State Table (Same DB, Same Transaction as Business)
CREATE TABLE tx_state (
transaction_id VARCHAR(64) PRIMARY KEY,
state TINYINT NOT NULL,
-- 1 INIT / 2 DONE / 0 FAIL
biz_key VARCHAR(64) NOT NULL,
updated_at DATETIME NOT NULL
);State table and business table must be same DB same transaction — physical basis of "query state = query business fact"; cross-DB re-enacts Incident 3. Idempotent dedup table same: insert same transaction as business write, unique key guards concurrency. Both tables need cleanup: tx_state terminal state retain 7 days; dedup table retention covers max retry window (default retry chain ~4.5h, keep 24h safe). Health check dual probes:
# Probe 1: Transaction half-message backlog (check-back debt)
mqadmin consumerProgress -g \
CID_RMQ_SYS_TRANS_HALF_TOPIC
# lag growing continuously = check-back falling behind
# Probe 2: DLQ backlog (consumption debt)
for t in $(mqadmin topicList |
grep %DLQ%); do
mqadmin consumerProgress -g $t
done
# lag >0 and continuous = messages retry exhausted
# Alert lines: half-message lag >100 sustained 10min
# DLQ lag >0 immediate alert8.3 Reliability Health Checklist (8 Items)
Onboarding and periodic inspection each pass these eight: ① Send semantic matches business tier (forbid transaction chain oneway); ② Async callback splits by status, failure into compensation table; ③ Upstream timeout > retry budget; ④ Flush/replication combo matches promise and in baseline inspection; ⑤ Transaction state table same DB same transaction, no-record returns UNKNOW; ⑥ Check-back executor zero write ops; ⑦ Consumption idempotency unique key landed and same transaction; ⑧ DLQ and half-message dual probes into alerts. Items ②④⑤ correspond to three incidents — these eight turn "reliability looks right" into "every segment verified".
8.4 On-Call Playbook: Three Reliability Alert Handlings
Send success rate drop : first check compensation table pile growth rate (distinguish jitter vs sustained failure), then segment by broker health (busy/watermark/master-slave), finally check business send code (upstream timeout truncating retry budget is high-frequency cause).
Half-message backlog : check check-back executor instances alive, state table query normal (DB jitter causes UNKNOW chain), transactionCheckMax capped — each backlogged half-message occupies check-back window.
DLQ backlog : first identify message type (by topic + exception stack triage), confirm then execute replay plan; dead-letters without plan must not batch skip — every DLQ entry is hard evidence of "business not done".
Core Source Code: Four Key Implementations
1. Transaction Message Send Main Flow
public SendResult sendMessage(Message msg, Object arg) {
// 1. Send half-message first (system topic invisible)
SendResult sendResult = this.send(msg);
if (SEND_OK != sendResult.getSendStatus()) {
throw send half-message failed;
}
// 2. Execute local transaction (business + state table)
LocalTransactionState state = executeLocalTransaction(msg, arg);
// 3. Terminate half-message per result
if (COMMIT_MESSAGE == state) {
endTransaction(msg, COMMIT);
} else if (ROLLBACK_MESSAGE == state) {
endTransaction(msg, ROLLBACK);
}
// UNKNOW: leave to check-back fallback
return sendResult;
}2. Broker Check-Back Scheduler
public void run() {
while (!isStopped()) {
// Scan unresolved half-messages
List<MessageExt> halves = scanUnresolvedHalfMessages();
for (MessageExt half : halves) {
// Exceed limit: move to dead topic and alert
if (checkTimes(half) > maxCheckTimes) {
moveToDeadTopic(half);
continue;
}
// Check-back producer for answer
EndTransactionResult r = checkTransactionState(half);
if (COMMIT == r) {
commit(half);
} else if (ROLLBACK == r) {
delete(half);
}
// UNKNOW: wait next round
}
waitForRunning(checkInterval);
}
}3. Correct Check-Back Executor
public LocalTransactionState checkLocalTransaction(MessageExt msg) {
// 1. Read-only state table, no business replay
String tid = msg.getKeys();
TxState s = txStateMapper.selectById(tid);
// 2. No record: UNKNOW wait for fact
if (s == null) {
return UNKNOW;
}
// 3. Answer per fact
if (s.state == DONE) {
return COMMIT_MESSAGE;
}
if (s.state == FAIL) {
return ROLLBACK_MESSAGE;
}
// 4. INIT: business not settled yet
return UNKNOW;
}4. Consumer Result Processing & Offset Advance
public void processConsumeResult(ConsumeConcurrentlyStatus status, ConsumeConcurrentlyContext ctx) {
if (CONSUME_SUCCESS == status) {
// All success: advance offset
this.removeMsgs(pq, msgs);
return;
}
// Has failures: triage by retry count
for (MessageExt msg : failMsgs) {
if (msg.getReconsumeTimes() >= maxReconsumeTimes) {
// Exceeded: to DLQ for manual
sendMessageToDead(msg);
} else {
// Not exceeded: send back to retry queue
sendMessageBack(msg);
}
}
// Offset only advances confirmed-completed interval
this.updateOffset(pq, okMsgs);
}Source code reads one line: first segment "land first then do business", second segment "compensation must have limit", third segment "only query fact no replay", fourth segment "confirmed then advance". Four segments connected, message-not-lost mechanism boundaries fully visible — every step of Incident 1 to 3 finds corresponding mechanism or missing piece in these four.
Seven Accounts: Real Cost of Reliability
1. Acknowledgment Account : Each acknowledgment level directly adds latency: sync send one RTT, sync flush one fsync, transaction message one half-message round-trip — acknowledgment buys "knowing", budget by business tier, no one-size-fits-all.
2. Retry Account : Retry rescues "transient failure" while amplifying duplicates — sender retry + consumer idempotency are bound clause, configuring only one side equals not configuring. Retry budget (9s) alignment with upstream timeout is high-frequency troubleshooting point.
3. Transaction Account : Transaction message cost is "local transaction time window": half-message from send to termination, local transaction must settle fast — slow ops in transaction (remote calls, bulk writes) lengthen half-message stay, increase check-back probability. Transaction body must be small, slow ops extracted out.
4. Check-Back Account : 15 check-backs are "fact appearance" window: state table same DB same transaction → facts visible in seconds, 2-3 rounds terminate; cross-DB or default rollback on no-record → 15 rounds all waste — check-back limit not failure protection but design error developer.
5. Idempotency Account : Dedup table storage and performance are real money: unique key index, expiration cleanup, extra write same transaction as business — financial chains two layers minimum, log chains can keep only unique key fallback. Idempotency cost far lower than duplicate business cost (duplicate charge, duplicate shipment).
6. Reconciliation Account : Reconciliation system coverage cost by dimension: fact table design, comparison job, compensation tool, manual ledger — T+0 minute-level reconciliation is a subsystem. But it catches "last loss after all other means fail", ROI on financial chains extremely high.
7. Tier Account : Reliability is tiered pricing: L1 to L3 latency and complexity differ by order of magnitude — selection first question always "what happens if this chain loses?" Answer decides budget. Paying for unneeded tier is waste; saving on needed tier is accident.
20 Interview Questions (with Answers)
Q1–Q20 cover three-phase responsibilities, sync send five steps, retry budget calculation, async correct posture, oneway boundary, retry duplication cause, storage reliability combos, transaction message problem & boundary, full flow, half-message location, check-back trigger & flow, three return values, check-back vs retry, state table design, check-back limit exceeded, consumer offset acknowledgment, retry & DLQ mechanism, consumption idempotency implementation, end-to-end reconciliation, reliability tier selection & cost ladder. (Detailed answers omitted for brevity; each answer mirrors article's technical depth.)
One-Page Cheat Sheet: Nine Reliability Maxims
End-to-end promise = five factors multiplied: any zero → overall zero.
Lost message first segment: send ACK logs / broker storage / consumer offset three-segment locate.
Retry budget 9s: upstream timeout must exceed it.
Callback doing nothing = no acknowledgment: failure must land compensation table.
Transaction message: land first then do business — half-message → local transaction → terminate.
Check-back only queries fact, no replay: no record → return UNKNOW.
State table same DB same transaction: query state = query fact.
Retry inevitably brings duplicates: idempotency is bound clause, unique key guards concurrency.
DLQ and half-message dual probes into alerts: dead-letter unwatched = business lost.
Summary & Next Episode Preview
Message-not-lost is not a config but a relay of acknowledgments and compensations — send segment uses "sync acknowledgment or async + failure fallback" to guarantee "I know"; storage segment uses "flush/replication combo" to guarantee "really not lost"; consumption segment uses "process then acknowledge + idempotency" to guarantee "landed not afraid of duplicates"; outermost reconciliation catches extreme window loss. Reliability budget allocated by business tier, fallback always one tier cheaper than acknowledgment — these two are this article's selection philosophy and the complete answer welding Incident 3 shut.
Cross-article memory anchor: Article 2 "fault avoidance" solves "cannot write to good machine", Article 3 "offset closed-loop" solves "read where counts", Article 4 "flush/replication" solves "will disk lose", this article's three-phase contract connects these dots — any message loss incident finds its break point on this relay chain : break at acknowledgment (callback unhandled), break at persistence (combo degraded), break at idempotency (duplicate becomes dirty data), or break at fallback (reconciliation uncovered). Locate break point, fix has only one correct answer.
Next article "Sequential & Delay Messages" enters two "non-reliability but often confused" advanced topics: sequential message queue-level lock and MessageListenerOrderly implementation, why sequential throughput can't scale, delay message timing wheel implementation and 18 delay levels, and "arbitrary time delay" two implementation routes comparison — solving e-commerce high-frequency needs "same order status flow must be sequential" and "30-min unpaid auto-cancel" in one go.
For questions about attribution, corrections or content rights, please contactand we will review it promptly.
Published
AI-assisted summary