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 Send Internals: Three Semantics, Retry Budgets, Broker Fault Avoidance

RocketMQ Send Internals: Three Semantics, Retry Budgets, Broker Fault Avoidance

This article dissects RocketMQ's producer-side internals, comparing synchronous, asynchronous, and one-way send semantics, detailing the retry loop's time budget and exception classification, explaining broker latency-based fault avoidance, queue selection algorithms, async backpressure via semaphores, and the end-to-end reliability chain requiring idempotent consumption.

Introduction

Sending is the first mile of the message pipeline and the part that "looks simplest but costs the most when it fails." A single producer.send() hides five layers: time budget, exception classification, queue selection, fault avoidance, and semaphore backpressure. This article dives into the send-side source code (RocketMQ 4.9.x) to explain the differences among three send semantics, why retry is not a blind loop, how a slow broker is automatically avoided, and why async send needs backpressure.

Three Real-World Incidents

Incident 1: Callback Only Logs, 30k Reconciliation Gap

A marketing team used async send for coupon verification. The SendCallback.onSuccess only logged; onException was empty. When broker disk watermark triggered write rejection, tens of thousands of messages received NOT_AVAILABLE in the callback — silently lost. Reconciliation revealed a 30k gap; manual replay took three days. Fix: enforce callback state machine, failures go to compensation table; root fix: "callback branch treated equally with main flow" added to code review checklist. Async send's reliability ceiling equals how seriously you write the callback.

Incident 2: P99 Latency Jumps from 50ms to 2.2s, Zero Errors

A payment gateway's send P99 spiked from 50ms to 2+ seconds while success rate stayed 100% — no alerts. Root cause: one broker's host GC pauses caused 2-second response times. Synchronous send doesn't retry on success, so the slowness directly inflated interface latency. Enabling sendLatencyFaultEnable isolated that broker and P99 immediately recovered. Failures trigger alerts; slowness doesn't. Fault avoidance solves "which broker to retry"; "who is slowing you down" requires active detection.

Incident 3: Order Status Messages Consumed Out of Order

Order status flow messages used default round-robin send — three status messages for the same order landed in different queues. Two consumers processed in parallel, causing state machine validation failures. Quick fix: MessageQueueSelector hashing by order ID to ensure same key → same queue. Root fix: full ordered message solution (sender selector + consumer orderly, covered in episode 06). Round-robin guarantees throughput; ordering requires explicit declaration — you can't have both.

Technical Analysis: Inside the Send-Side Source Code

1.1 sendDefaultImpl : A Complete Send Journey

All synchronous sends eventually call sendDefaultImpl. Eight steps; three key points:

Pre-checks (message size, route existence) fail fast — no retry loop entry.

Route comes from local cache, not live NameServer pull — NameServer brief unavailability doesn't affect sending.

Time budget recalculated every retry iteration — budget exhausted exits loop immediately, throwing exception upstream.

The loop's design philosophy: retry is not a mindless for loop but "optimal decision within budget." Each round: (1) can we still try? (time), (2) who to try? (fault avoidance), (3) is it worth retrying? (exception classification). Three decision points evolve independently; configurable via budget, retry counts, and fault-avoidance switch. sendDefaultImpl only orchestrates.

vs Kafka Producer: Kafka's sender thread "batches then sends" — throughput via accumulator; RocketMQ "sends immediately" — latency via single-message fast path. Hence Kafka higher throughput but larger single-message P99 jitter (batch wait), RocketMQ stable single-message latency but weaker batching. Latency-sensitive messaging chooses RocketMQ; log pipelines choose Kafka — root cause is producer thread model.

Instance semantics: producer registers by group; same process, same group name → only one active producer (duplicate registration errors). Different groups coexist. Group on sender side mainly for ops (tracing, monitoring aggregated by group), unlike consumer side where group determines partition assignment. Also producer.start() does NOT connect to broker — connection established on first send. "Start success" ≠ "send ready"; health checks must send a probe message — essential for canary readiness probes.

1.2 Three Send Semantics: Three Prices for Reliability

Figure 2 shows timing comparison. Synchronous: request-response, explicit result, retryable, cost = throughput (sender thread blocks on socket read). Async: immediate return, result via SendCallback, throughput via pipeline parallelism, cost = you must handle callback seriously. One-way: write socket and return, no response waited, highest throughput, zero reliability.

Loss risks differ completely. Sync: failure throws exception, upstream can sense and fallback; loss only if upstream ignores exception. Async: failure only visible in callback; unchecked = silent loss — Incident 1 essence: turned "must handle" into "casual log". One-way: no failure perception channel at all — broker reject, network disconnect, message oversize all silent. Semantic choice is essentially choosing "failure visibility": how much awareness you trade for throughput determines how many messages you lose during failure.

Async throughput ceiling has a hidden account: sender thread pool capacity × budget determines sync QPS floor (extreme: 200 threads × 1 slow send/sec = 200 QPS floor). Async returns wait time to thread pool — 200 threads + 2048 in-flight async → QPS ceiling lifted to semaphore level. This explains why "sync to async" is often the first send-side optimization knife: network didn't get faster, thread pool wait cost eliminated. After switching, callback discipline (1.5) and semaphore tuning must follow, else saved wait cost becomes callback pile-up accidents.

1.3 Queue Selection & Broker Fault Latency Avoidance

selectOneMessageQueue

is the smartest send-side code. With sendLatencyFaultEnable (off by default in 4.9, production should enable), it's no longer pure round-robin: each send result backfills brokersFaultDelayTable — which broker slowed, how much, how long to avoid, all recorded in FaultItem. Queue selection: first round-robin from last broker, then filter out machines in isolation period. Figure 3 illustrates the mechanism.

Duration gradient design: ≤100ms → duration 0 (normal); >550ms → avoid 1 minute; >2000ms → circuit-break isolate 10 minutes. It quantifies "slow" into "avoidance duration" — a 1-second-slow machine isn't permanently blacklisted; recovers and auto-returns to round-robin. Two boundaries: isolation by broker name (master+slave together); newly scaled brokers at low traffic need warm-up — cold-start high latency keeps them out of traffic; use load test or warm-up scripts to "heat" them.

Interaction with retry — clear responsibilities: Fault avoidance only decides "which broker to retry", not "whether to retry" (exception classification + time budget decide), nor "can it recover" (isolation temporary, recovery judged by real traffic after duration expires). Three mechanisms each own a segment; troubleshooting: high failure rate → check retry & exception classification; high P99 → check avoidance & budget; uneven traffic → check FaultItem isolation status. Memorize these boundaries, send-side troubleshooting radius shrinks to minutes.

1.4 Retry & Timeout Budget: The Truth Behind P99 Spikes

Figure 4 shows sync send exception classification decision tree. Three exception categories, three paths: network-layer exception → switch broker retry; broker response exception → decide retry value by response code ( NOT_AVAILABLE worth retry, NO_PERMISSION useless); interrupt exception → don't swallow, terminate immediately. Overarching constraint: time budget: callTimeout = sendMsgTimeout - elapsed, budget exhausted → loop exits immediately.

Incident 2 maps here: that GC-paused broker took 2 seconds per attempt, succeeded within 3-second budget — no exception, no retry, no alert, only P99 silently multiplied. Root cause: "slow" harder to govern than "fail": failure triggers retry & exception path; slow only pollutes latency curve. Three countermeasures: fault avoidance must be on (slow machine enters isolation), budget split (3-second budget fits at most one full attempt + one fast fail, don't expect three retries within budget), load-test baseline (know your P99 baseline, deviation triggers alert — method in 2.2).

How to set budget: sendMsgTimeout is not "how slow to tolerate" but "what's the max price for this action." 3 seconds means worst-case this send occupies a sender thread for 3 seconds — 200-thread pool, extreme case 3 seconds accumulates 66 slow sends and saturates pool. Larger budget → deeper backlog during failure → upstream thread pool more prone to avalanche. Tightening to 1 second + fast retry usually more stable than 3-second large budget — prerequisite: fault avoidance enabled so retry lands on healthy machine.

1.5 Async Send Backpressure: Semaphore & Callback Thread

Async send seems "zero cost" but has invisible watermark: asyncSenderSemaphore, default 65535. Each in-flight async request acquires a permit; broker response releases. This semaphore is producer self-protection — broker slowdown piles in-flight requests, 65535 requests' context (message body ref + callback object) resident in memory; without this gate, one broker jitter blows producer heap.

Callback thread model matters: SendCallback executes on Netty IO thread. Two implications: (1) Don't do heavy work in callback (DB writes, remote calls — blocks IO thread, slows entire client network processing). Correct pattern: callback only does status determination, heavy work offloaded to business thread pool. (2) Exceptions thrown in callback must be caught locally — thrown on Netty thread, nobody catches. Correct async send pattern: semaphore for backpressure, callback for determination, compensation table for fallback, business thread pool for execution.

1.6 Send Path Performance Switches

Message body > compressMsgBodyOverHowmuch (default 4KB) auto-compresses — CPU trades network/storage; large payload scenes benefit; small dense messages low compression ratio wastes CPU — adjust threshold per typical business message size.

VIP channel ( vipChannelEnabled) uses separate port (9877) on same broker with independent Netty handlers, isolating send traffic from consume/heartbeat — broker busy, send less interfered; cost = double ports & thread resources; enable on demand.

Message size validation both client and broker (client maxMessageSize default 4MB). Oversize intercepted by checkMessage client-side, never enters retry loop — "send oversize exception" always code bug, not cluster issue. Large messages (e.g., second-level log batches) correct solution: application-side sharding or compression, not raising 4MB — broker 4MB limit unmovable (memory & replication protocol designed around it); forcing alignment only postpones accident to broker side.

Viewing these switches together: send-side performance tuning has almost no mysticism — each switch maps to a clear resource trade-off: compression trades CPU, VIP channel trades resource isolation, semantics trade visibility, budget trades backlog risk. Before tuning, ask "what am I trading for what"; if can't answer, don't touch — this habit blocks 90% of "tweak a param casually" accidents, the parameter view emphasized throughout the series.

1.7 Send-Side Reliability Engineering: Fallback Chain & Idempotency

Assemble mechanisms into complete fallback chain (Figure 5): sync send (or async with serious callback) → result check → failure into local compensation table → scheduled retry → consumer idempotent deduplication. First four links guarantee "no loss"; last link digests "possible duplicates" — retry, compensation replay, rebalance all produce duplicate delivery; RocketMQ promises at-least-once, idempotency is business-side mandatory tax.

Idempotency implementation typically "unique key + deduplication table": message carries business unique key (order ID + action), consumer uses DB unique index or Redis

SETNX</sub> to deduplicate. Key granularity: deduplicate by "business action" not "message ID" — same message re-delivered gets different ID, same action may have different messages. Solidify this link, send-side optimistic strategies (aggressive retry, compensation replay) gain confidence — <strong>Idempotency is reliability foundation, not optional.</strong></p><p>Fallback chain has a commonly omitted seventh link: <strong>Drill.</strong> Compensation table written ≠ fallback works — will compensation task miss scans? Will replay kill downstream? Where is manual intervention entry? All validated only by real fault drill. Drill method simple: test env artificially fail send (stop broker, wrong route), observe if compensation table collects and replays as expected — last link only counts when drill passes, consistent with Episode 01 checklist "drilled".</p><h2>Production Practice: Config, Load Test & On-Call</h2><h3>2.1 Producer Full Config (Transaction Service Baseline)</h3><pre><code>// ==== Producer Production Config (Transaction Baseline) ====
DefaultMQProducer producer = new DefaultMQProducer("order-group");
producer.setNamesrvAddr("ns1:9876;ns2:9876");

// --- Budget & Retry ---
producer.setSendMsgTimeout(1000); // tighten budget + fault avoidance switches machine
producer.setRetryTimesWhenSendFailed(2);
producer.setRetryTimesWhenSendAsyncFailed(2);

// --- Fault Latency Avoidance (MUST ENABLE) ---
producer.setSendLatencyFaultEnable(true);

// --- Backpressure & Performance ---
producer.setClientAsyncSemaphoreValue(2048); // async in-flight cap (default 65535)
producer.setCompressMsgBodyOverHowmuch(8192); // small dense messages raise compression threshold

// --- Size ---
producer.setMaxMessageSize(4194304);

// --- Tracing (see Ep01 1.6) ---
producer.setEnableMsgTrace(true);

Compared to Episode 01 "three-piece set", this config adds three performance items: budget tightened to 1s (with fault avoidance, retries land on healthy machines), async semaphore tightened to 2048 (transaction messages small, 65535 wasteful, tighter → earlier backpressure, stable memory), compression threshold adjusted per typical message size. Three-piece set (retry count, status check, compensation table) = reliability chassis; these three performance items = latency chassis — both layers needed, missing one loses immunity to a class of accidents.

2.2 Load Test Baseline: Give P99 a Baseline

Incident 2's missing alert root: no send latency baseline. Pre-launch use official load tool to baseline, write into monitoring:

# Official load tool (included in package)
sh producer.sh -n "ns1:9876;ns2:9876" \
-t order-topic -w 32 -s 1024 \
-k false   # -k true for ordered load test

# Baseline table (example: 4C8G producer)
# Single 1KB: P99 < 8ms (same DC)
# Sync TPS: single instance ~8000
# Async TPS: single instance ~30000
# Semaphore 2048 in-flight duration cap
#   = 2048 / 30000 s ≈ 68ms peak

Baseline three numbers: single-message P99 (latency chassis), single-instance TPS ceiling (capacity planning), semaphore exhaustion time (backpressure trigger point). Together they answer "can current config handle peak promo" — orders of magnitude better than guessing params. Load test must also do one key action: manually stop a broker, observe fault avoidance activation & recovery curve — budget-internal auto-switch, zero failures = drill passed.

2.3 On-Call Playbook

Three send-side alert categories handling order. First, send failure rate spike: check NameServer broker up/down logs (node removed?), then corresponding broker disk watermark & GC — failure rate is cluster health FIRST signal. Second, P99 spike but success rate normal: check fault avoidance enabled, then per-broker send RT distribution (dashboard has broker-level RT chart) — likely one machine dragging. Third, async callback pile-up: check semaphore usage & callback thread pool — pile-up means broker response slower or callback doing heavy work. All three alerts share one principle: Send-side issues must be traced "client perception → broker state → machine state" from near to far — client side first check failure classification (timeout/reject/route missing), broker side then check watermark & GC, finally host machine. Reverse order (restart broker first) washes away most valuable scene evidence — fault avoidance FaultItem table, NameServer removal logs, broker RT curves are one-time-only evidence. Write troubleshooting order into on-call handbook, new hires can follow map.

Core Source Code: Four Key Implementations

3.1 sendDefaultImpl : Budget-Driven Retry Loop

private SendResult sendDefaultImpl(
 Message msg, CommunicationMode mode,
 SendCallback callback, long timeout) {
 long begin = System.currentTimeMillis();
 // 1. Route: local cache first
 TopicPublishInfo info = tryToFindTopicPublishInfo(topic);
 if (info == null || !info.ok()) {
 throw new MQClientException("No route info", null);
 }
 int timesTotal = 1 + clientConfig.retryTimes; // actually getRetryTimesWhenSendFailed()
 int times = 0;
 String[] brokersSent = new String[timesTotal];
 for (; times < timesTotal; times++) {
 String lastBroker = times == 0 ? null : brokersSent[times];
 // 2. Select queue: retry avoids faulty
 MessageQueue mq = selectOneMessageQueue(info, lastBroker);
 // 3. Budget check: insufficient → exit immediately
 if (timeout - costTime < 0) break;
 sendResult = sendKernelImpl(msg, mq, mode, callback, topicInfo, timeout - costTime);
 brokersSent[times] = mq.getBrokerName();
 return sendResult; // success returns immediately
 }
 // All failed: throw last exception
 }

Three details: brokersSent array records each round's broker, retry "switch machine" relies on it; budget check before queue selection — queue selection has overhead, no need to select for a doomed-to-timeout round; loop returns SendResult , exception path caught by outer layer for classification — orchestration layer only manages flow, semantic judgment pushed down to sendKernelImpl & exception handling.

3.2 selectOneMessageQueue : Where Fault Avoidance Takes Effect

public MessageQueue selectOneMessageQueue(
 TopicPublishInfo tpInfo,
 String lastBrokerName) {
 if (this.sendLatencyFaultEnable) {
 int index = tpInfo.getSendWhichQueue().getAndIncrement();
 int size = tpInfo.getMessageQueueList().size();
 for (int i = 0; i < size; i++) {
 int pos = Math.abs(index++) % size;
 MessageQueue mq = select(pos);
 // Skip brokers in isolation period
 if (!latencyFaultTolerance.isAvailable(mq.getBrokerName())) continue;
 // Prefer last successful (stickiness)
 if (lastBrokerName == null || mq.getBrokerName().equals(lastBrokerName)) return mq;
 }
 // All isolated: pick least latency as fallback
 return latencyFaultTolerance.pickOneAtLeast() corresponding queue;
 }
 // Avoidance disabled: pure round-robin
 return tpInfo.selectOneMessageQueue(lastBrokerName);
 }

Note "stickiness" design: lastBrokerName non-null prefers it — last successful machine likely fast this time too, trusting locality; only when it enters isolation does it yield to others. "All isolated" fallback branch is anti-avalanche last gate: rather send to least-bad than reject outright — combined with upper compensation table, always leaves a lifeline for messages.

3.3 sendAsync : Semaphore Backpressure & Callback

private void sendAsync(
 final Message msg,
 final SendCallback sendCallback,
 final long timeout) {
 // Backpressure gate: in-flight request cap
 boolean acquired = this.asyncSenderSemaphore.tryAcquire(timeout, TimeUnit.MILLISECONDS);
 if (!acquired) {
 // No permit: fast fail
 sendCallback.onException(new RemotingTooMuchRequestException("async semaphore"));
 return;
 }
 // Go through Netty async channel
 this.mQClientFactory.getMQClientAPIImpl().sendMessageAsync(addr, brokerName, msg, timeout, new SendMessageCallback(...) {
 public void onComplete(...) {
 // Release permit
 asyncSenderSemaphore.release();
 // Determine: forward business callback
 }
 });
 }

tryAcquire with timeout is key design: permit contention waits at most timeout ms — not instant fail, not infinite wait. Permit release in callback onComplete (finally semantics) — both success and failure paths release; miss one → leak, 2048 permits leak dry, send permanently fails. Incident 1's "callback only logs" has another hidden risk: onException branch must also release permit and notify business; missing either half is an accident.

3.4 FaultItem : Latency Table Minimal Unit

class FaultItem implements Comparable<FaultItem> {
 private volatile long currentLatency;
 // Isolation deadline timestamp
 private volatile long startTimestamp;

 // Send result backfill: latency + avoidance duration
 public void update(long latency, long duration) {
 this.currentLatency = latency;
 this.startTimestamp = System.currentTimeMillis() + duration;
 }

 public boolean isAvailable() {
 return System.currentTimeMillis() >= startTimestamp;
 }

 // Available first, then lower latency preferred
 @Override
 public int compareTo(FaultItem o) {
 if (isAvailable() != o.isAvailable()) return isAvailable() ? -1 : 1;
 if (currentLatency != o.currentLatency) return currentLatency < o.currentLatency ? -1 : 1;
 return 0;
 }
 }

A class with only two fields and three methods supports the entire fault avoidance — textbook good design. volatile ensures Netty callback thread write, send thread read visibility; compareTo order (availability > latency) defines "least bad": isolation-expired machine even if previously slow ranks before still-isolated machines — gives faulty machine a comeback chance, avoids "one slow = permanent cold palace".

Seven Accounts: Send-Side Cost Ledger

1. Semantic Account. Sync buys "awareness", async buys "throughput", one-way buys nothing. Business messages default sync; async must pair with serious callback & compensation; one-way only for tracking logs. 2. Budget Account. sendMsgTimeout prices worst-case occupancy: larger budget → deeper thread pool backlog during failure. 1s budget + fault avoidance + fast retry usually beats 3s large budget. 3. Avoidance Account. Fault avoidance default off — without it, slow broker continuously pollutes P99 unnoticed. Enabling adds one in-memory table + one lookup, negligible cost; gain: "slow" becomes governable quantity for first time. 4. Backpressure Account. Async semaphore = in-flight request memory watermark: 65535 wasteful for small-message services, 2048 more stable. Tightening semaphore essence = earlier fast fail — turns memory risk into handleable exception. 5. Idempotency Account. Retry, compensation replay, rebalance all produce duplicates — "at-least-once" protocol makes idempotency business tax. Unique key + deduplication table built once, whole chain benefits; skip it, all previous reliability investments pay for duplicate accidents. 6. Baseline Account. Load test baseline cost ~half day, buys three things: P99 baseline alerts evidence-based, capacity planning numbers, fault drill script. Un-baselined services, every "got slower" is mystic troubleshooting. 7. Ordering Account. Round-robin and ordering mutually exclusive: default round-robin maximizes throughput, leaves ordering risk to business. Messages needing ordering must explicit selector (same key → same queue), and restrict ordering scope to minimum (only enable ordering for topics that truly need it).

High-Frequency Interview Questions (with Answers)

20 Q&A covering: three semantics differences & loss risks; sendDefaultImpl retry loop key mechanisms; broker fault latency avoidance principle; why P99 spikes with 100% success & how to troubleshoot; sendMsgTimeout setting rationale; async send memory explosion prevention; SendCallback correct pattern; send retry duplicate consumption; VIP channel purpose & when to use; >4MB message handling; ordered message sender implementation; No route info trigger timing; send latency spike troubleshooting three axes; compression mechanism & cost; sync send thread model; selectOneMessageQueue stickiness design; fault avoidance false-positive on new brokers; compensation table design; producer startup注意事项; complete send-side load test baseline steps.

One-Page Cheat Sheet

Send Kernel Nine Sentences: ① Sync awareness, async throughput, one-way naked — semantic choice = failure visibility choice; ② Retry three pillars: time budget, exception classification, fault avoidance — missing one is gambling; ③ Fault avoidance default off, production must on — "failures alert, slowness doesn't"; ④ Budget 1s beats 3s: budget prices worst-case occupancy, not tolerance; ⑤ Async semaphore = memory watermark, 2048 beats 65535; ⑥ Callback on Netty IO thread: only judge, no heavy work, onException equals onSuccess; ⑦ Permit both success/failure branches must release, miss one = leak; ⑧ SEND_OK not finish: compensation table + consumer idempotency closes loop, idempotency key uses business action not message ID; ⑨ Launch three things: load test baseline, fault drill validates avoidance, monitor alerts on 50% baseline deviation.

Summary & Next Episode Preview

All send kernel mechanisms answer one question: "How much resource is this send worth, how much risk to take?" Time budget prices risk, exception classification prices retry, fault avoidance prices machine, semaphore prices in-flight requests. Remember these pricing relationships, any send-side param you can derive reasonable value instead of copying. Revisit three opening incidents: callback unchecked = "awareness voluntarily given up"; slow broker no alert = "fault avoidance not enabled"; out-of-order = "round-robin vs ordering trade-off not explicitly declared" — none are "tool broken", all are "pricing relationships not thought through". This series' consistent stance: read mechanisms as ledgers, accidents become deducible inevitabilities, not bad luck. Next episode "Consumer & Consumption Moves" shifts to other end of pipeline: Push vs Pull consumer thread models, Rebalance full flow & duplicate window, concurrent vs ordered consumption implementation differences, consumption offset commit timing — Incident 3's "consumer out-of-order" gets full solution there.

About this article

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

source code analysisperformance tuningFault ToleranceMessage QueueRocketMQidempotencyProducerRetry MechanismBackpressureSend Semantics

Discussion 0

Questions, practical examples and thoughtful responses.

Open full discussion