RocketMQ Consumer Deep Dive: Rebalance, Offsets, Retry & Push/Pull Internals
This article provides a comprehensive analysis of RocketMQ's consumer-side mechanisms, covering ConsumerGroup semantics, Rebalance algorithms and costs, offset management with minimum unacknowledged watermark, concurrent vs ordered consumption retry models, Push vs Pull implementations, production configuration baselines, and core source code walkthroughs with real-world incident postmortems.
Reading font

Three Core Threads
The article centers on three key insights: (1) Rebalance is the root of all consumption issues — subscription consistency, allocation algorithms, and scaling costs all originate here; (2) Offsets represent the "minimum unacknowledged" not "latest consumed" — duplicate delivery is normal, idempotency is mandatory; (3) Retry is not a free safety net — concurrent retry switches instances, ordered retry blocks in place, mechanisms differ fundamentally.
Incident Postmortems
Incident 1: Kubernetes HPA Causes Sawtooth Backlog
An order-consumer group used HPA; CPU spikes scaled instances from 4 to 8 then back. Each scaling triggered full Rebalance: reassigned queues had to finish existing messages before release, new instances had to re-fetch routes and build ProcessQueues. During peak, 7 Rebalances in 30 minutes turned TPS curve into sawtooth, triggering backlog alerts four times. Mitigation: disable HPA, fix instance count. Root fix: write "keep consumer group instance count stable" into elasticity policy — Rebalance is not free redistribution; every round carries consumption pause cost.
Incident 2: Same Group, Different Topics, Mutual Message Loss
Two services shared group pay-group: legacy subscribed pay-topic, new subscribed refund-topic. After deployment both worked intermittently. Root cause: RocketMQ requires identical subscription relationships within a group ; broker overwrites group subscription config — each service overwrote the other's subscription on restart. Mitigation: split groups. Root fix: manage group names in config, one service per group — ConsumerGroup is the unit of load balancing and subscription consistency, not a namespace.
Incident 3: Broadcast Mode Container Rebuild Replays Full History
A config-refresh service used BROADCASTING mode; offsets stored in local instance files. Container image upgrade rebuilt pods, local offset files lost, broker had no offsets for that group — 48 hours of history replayed, downstream config API overwhelmed. Mitigation: temporarily switch to clustering mode to stop replay. Root fix: mount persistent volume for broadcast offset files, or switch to clustering + local cache filtering — Broadcast mode's "independent offsets" are freedom, but also unmanaged risk.
Technical Analysis: Building the Consumer Skeleton
1.1 ConsumerGroup: Load Balancing & Consistency Unit
The consumer load balancing unit is ConsumerGroup , not topic, not instance. Instances in same group share all queues of subscribed topics; broker manages subscription, offsets, retry config per group. Implications: group instances must subscribe identically (Incident 2); group instance count determines parallelism split (excess instances get zero queues, mirroring Incident 1); group offsets, retry topic ( %RETRY%group), DLQ topic ( %DLQ%group) all follow group name — wrong group name breaks entire metadata chain.
FAQ: Different groups consuming same topic? Each independently consumes full messages — offsets, retry, DLQ fully isolated. This is standard multi-subscriber pattern: order messages consumed by points, risk, analytics groups independently. Cost: broker maintains per-group offsets and retry overhead; topic subscription group count must be included in capacity planning (retry traffic stacks per group) — "Group isolation" is designed decoupling, not free broadcast.
Engineering discipline: Group name is an architectural asset, not a string in code. Lifecycle management (who uses, what subscribed, QPS) must enter config management, treated equally with topics. Many teams approve topics but let group names run wild, leading to "share group to save trouble" landmines like Incident 2.
Overlooked semantics: Retry topic ( %RETRY%group ) and DLQ topic ( %DLQ%group ) are system topics dynamically created by group name , inheriting default queue count, permissions, retention. Bad group names (special chars) can cause retry topic creation failure — symptom: "consumption fails but retry messages disappear", more insidious than message loss. Group naming convention: start with letter, only alphanumeric/underscore, self-describing — add to code review checklist.
1.2 Subscription Consistency: Incident 2 Mechanism
Why inconsistent subscriptions manifest as "intermittent"? Mechanism at broker: each client heartbeat carries its subscription data (SubscriptionGroupManager reports per group), broker overwrites across instances — last reporter wins . Legacy service restarts, group subscription becomes legacy version; new service restarts, flips back. Both services' consumption fluctuates depending on who restarted last — this "drift on restart" fault is 10x harder to debug than stable reproduction.
4.x defense: client logs error on startup (subscription inconsistency detection), but logs ≠ alerts. Engineering remediation order: First, only one subscription per group (one service one group); second, dynamic subscription scenarios must use config center to push identical subscription; third, monitor subscription hash consistency — turn "restart drift" into explicit alert. 5.x adds stricter validation, but discipline doesn't expire with version upgrades.
Kafka Comparison: Kafka solves subscription consistency at client collaboration layer (ConsumerGroupProtocol, leader assigns + SyncGroup, inconsistency triggers full rebalance and rejection); RocketMQ overwrites at broker per group. Different mechanisms, same conclusion: Homogeneous consumer group is a shared prerequisite for both systems. Difference: Kafka inconsistency explodes immediately (rebalance storm), RocketMQ inconsistency leaks slowly (mutual overwrite) — former scares, latter kills.
Why not validate at client? Because client only sees itself, not whole group — subscription consistency is a "group-level" constraint requiring broker's global authoritative view. 4.x client detection (compare local subscription hash) only catches "simultaneously online instances" inconsistency, misses "rolling deploy window sequential versions" inconsistency — so monitoring audit uses broker-side group config as source of truth, client detection only supplements local self-check.
Rebalance: Root of All Consumption Issues
2.1 Mechanism Overview: Full Reconciliation Every 20 Seconds
Push consumer Rebalance triggered by RebalanceService every 20s (or immediate via broker notification), per subscribed topic: Fetch full queue list from broker + fetch all consumer IDs for group from broker → allocation algorithm computes "which queues I own" → diff against local ProcessQueueTable — extra queues create and start pulling, removed queues stop pulling, finish in-flight then release. Entire process lock-free: each instance independently computes and executes, relying on "algorithmic determinism" for non-overlapping results.
Understanding "lock-free independent computation" is key to all Rebalance anomalies: if two instances momentarily use different consumer list versions (new instance not yet perceived by other), they may compute overlapping assignments — both consume same queue, messages duplicate but offset advances by minimum unacknowledged, no loss only duplicates. Window typically hundreds of milliseconds, "At-least-once" semantics partly comes from Rebalance transition state — second reason consumption idempotency is mandatory (first is offset rollback replay).
Lock-free design hidden corollary: Rebalance correctness entirely depends on "sorted input consistency" assumption — queue list and consumer list sorting rules must be globally consistent. Anyone breaking sorting assumption (e.g., custom allocation strategy without sorting) causes persistent overlapping assignment — not millisecond transition but continuous double-consumption. Custom strategy review focus: input sorting and output determinism.
2.2 Allocation Algorithms: Three Strategies' Ledger
Default AVG essence is "contiguous slicing": sorted queues evenly segmented, each segment to one instance. Biggest advantage: Minimal churn during Rebalance — instance exit just redistributes its segment to neighbors, other instances' queues stay put; critical for ordered consumption (segment doesn't migrate, ordered chain doesn't jitter). ROUND scatters locality; Consistent Hash distribution depends on virtual node count and ring quality, queue skew may give single instance 60% load — load test distribution before using in consumption.
Selection Discipline: Default AVG is correct for 90% scenarios. Real evaluation isn't "which algorithm better" but "Will my instance count change frequently?" — Yes, calculate Rebalance migration cost (ordered consumption migration = ordered chain interruption); No, AVG once and for all. Consistent Hash suits "instance-queue affinity" special cases, not general solution.
2.3 Rebalance Cost: Incident 1 Sawtooth Origin
Break down Rebalance cost: removed queues — instance waits for in-flight consumption to finish before removing ProcessQueue (fast path hundreds of ms, slow path by backlog volume); new queues — re-fetch route, build ProcessQueue, fetch offsets from broker, resume pull pipeline — peak handoff of a large queue can pause seconds. Scaling N instances = full group N Rebalances = each queue at least one handoff. Sawtooth isn't bug, it's handoff cost; governance reduces handoff count, not parameter tuning.
Monitoring classic false alarm: Consumption lag denominator is queue, numerator aggregated per queue — empty queues (no messages yet) counted in "allocated", so some instances showing lag=0 is normal. Real metrics: "Sum of lag on queues with backlog" and "Max single queue lag" — former reflects total volume, latter reflects skew. Dashboard default diff occasionally has statistical error (offset commit 5s cycle), use broker-side getConsumerStatus data for secondary confirmation.
Governance checklist: K8s rolling deploy serial (maxSurge=0, one-by-one, only one instance in/out per round); HPA disable for consumer groups or desensitize thresholds (scale once, tolerate extra buffer); stagger deploy windows from big promotions. Monitoring: add "Rebalance count" metric (client logs or instrumentation), sawtooth appears → instantly answer "is it Rebalance again?" — saves half hour blind debugging.
Ordered groups more sensitive, extra queue lock handoff: new instance must acquire queue-level distributed lock from broker before taking over queue, lock handoff failure triggers brief "dual-read" protection (messages duplicate but order preserved). Ordered group instance changes must follow "per-instance, wait stable" rhythm : one new instance up, observe lock stable, then next. This rhythm is "serialized rolling deploy" reinforced for ordered scenarios — Chapter 06 will expand lock mechanism fully.
Consumption Offsets: Why "Minimum Unacknowledged"
3.1 Two-Layer Structure: ProcessQueue & offsetStore
Biggest offset misconception: Offset is not "where I consumed to", but "all earlier messages in this queue are processed" . Mechanism: each pulled message enters ProcessQueue (in-flight snapshot, TreeMap sorted by offset), business success removes from TreeMap — Committable offset = minimum offset in TreeMap . Middle message slow, whole watermark stuck: m3 processing, even if m4,m5 done, offset stays 3.
Design cost: "Slowest consumer determines watermark"; benefit: Offset always maps to a definite safe point : replay from offset neither misses (all before offset processed) nor depends on business callback order. Kafka similarly uses min unacknowledged watermark (accumulator offset sequence) — convergent evolution implementing "at-least-once" at offset layer. Side effect: duplicate consumption — m4,m5 done but uncommitted, crash replays. So consumption logic must be idempotent, write into coding standards.
3.2 Commit Timing & Why "Commit Before Process" Impossible
CLUSTERING mode offsetStore commits offsets to broker periodically (default 5s batch); broadcast writes local file. Business code has no "early commit" entry — offset computed by framework via minimum unacknowledged. So "commit before process loses messages" in RocketMQ only possible in two cases: 1) Using PullConsumer managing offsets manually (manual commit, self-responsible for ordering semantics); 2) Business logic persists then returns success, but persistence transaction not guaranteed — that's business transaction issue, not offset mechanism.
Three offset engineering points: First , offset lagging actual consumption by seconds is design behavior, not backlog — monitor backlog via ProcessQueue size and message lag, not offset diff; Second , offset rollback (replay history) uses mqadmin resetOffset, confirm downstream idempotency first, then choose "by time" or "by offset"; Third , offset retention (broker default 48h) determines "how far back can replay", cold topic offsets expire then start from latest — low-frequency topics needing history must plan retention upfront.
Offset rollback three disciplines: Stop consumption before rollback — rollback without stopping, new pulls immediately overwrite historical offset, rollback wasted; Watch retry topic immediately after rollback — historical messages with poison will instantly flood retry chain; Rollback per group — all group instances must perceive offset change, rolling rollback inferior to full group (offset broker-authoritative, full group replay same coordinate). Rollback is three-step ordered operation, not one command.
Offset & flow control linkage detail: Offset commit cycle (5s) and flow control threshold (in-flight 1000) jointly determine "crash replay volume" — worst case replay ≈ consume TPS × 5s + in-flight threshold. This volume must be calculated for downstream in capacity review: downstream idempotency table, rate limit config, replay tolerance all designed to this ceiling. Parameters not isolated — increasing flow control threshold simultaneously amplifies replay volume — another "risk switch" evidence.
Offset operational pitfall: Offset skip and offset reset are different things . Backlog unacceptable (historical data no processing value), correct action is skip to latest offset resume consumption, not grind slowly — hours of downstream eating garbage. Before skip, export backlog interval messages for archive, leave "processed but traceable" evidence chain — skip not discard, release after archive. Also skip per "queue × group" granularity, only skip bad queues, not all.
Consumption Retry & DLQ: Two "Retries", Two Worlds
4.1 Concurrent Consumption: 16-Level Backoff Switching Instances
Concurrent listener returns RECONSUME_LATER or throws exception, message doesn't return to original queue but client publishes back to %RETRY%group retry topic , broker delays by 16 levels (10s, 30s, 1m, 2m… max 2h) step-by-step re-deliver — re-delivered messages re-enter Rebalance, may go to different instance. 16 levels exhausted → %DLQ%group DLQ. Chain fully visible: retry topic is %RETRY%group, DLQ is %DLQ%group, listener uses MessageExt.getReconsumeTimes() to distinguish first vs retry.
4.2 Ordered Consumption: Local Blocking Cost
Ordered retry completely different: No retry topic, local infinite retry + queue-level suspend — to preserve queue order, failed message must retry in place until success, all subsequent messages queue up. Default retry count Integer.MAX_VALUE: one poison message (bad data, deserialization always crashes) can block entire queue for hours. Ordered consumption MUST configure maxReconsumeTimes, exceed limit record DLQ then skip (return success to pass), business compensates via DLQ records — Chapter 06 expands full solution.
DLQ Governance Trio: ① DLQ topic alert — DLQ appearance means 16-level backoff couldn't save, likely code or data issue, manual intervention P1; ② Scheduled compensation task fixes data then re-publish to original topic (confirm downstream idempotency before re-publish); ③ DLQ retention same as normal messages, expire delete — compensate early. Retry surge earlier signal than DLQ: 16-level first level only 10s, retry TPS surge appears hours before DLQ — monitor retry curve. All three share prerequisite: DLQ topic permissions and monitoring pre-configured — configure after incident, messages already in expiry countdown.
Retry topic cold fact: %RETRY% topic read permission only open to clients subscribed to corresponding group with retry enabled , and its queue count defaults to one — all 16-level re-delivered messages squeeze into this single queue. Retry storm (mass simultaneous failures) makes this queue bottleneck: re-delivery queues, backoff rhythm disrupted. So "retry surge" alert needs two tiers: mild surge auto-observe, retry TPS approaching half of main consumption TPS → manual intervene — backoff mechanism already overloaded.
Concurrent vs Ordered, Push vs Pull: Two Pairs of Mode Choices
5.1 Concurrent vs Ordered Consumption
Concurrent: thread pool parallel listener, high throughput, failure → retry topic, offset advances by min unacknowledged — default for business messages. Ordered: queue-level lock serial execution, throughput limited by single thread, failure local retry, queue blocked = consumption paused — only for "same key must process in order" scenarios: order state machine, binlog sync, account ledger. Ledger: Ordered consumption trades throughput for order, trades "queue block risk" for "no disorder" ; businesses needing order must first confirm "disorder business consequence" worth this cost — many self-proclaimed order-needed scenarios can resolve via "state machine idempotency".
Pragmatic compromise: "Local ordering" — business groups by order ID, account ID etc., same key must order — use MessageQueueSelector route same key to same queue (sender guarantees), consumer uses ordered consumption or "concurrent + per-key partition queue". Ordering granularity narrows from "entire message stream" to "within same key", queue block impact shrinks from global to single key — granularity narrowing is core engineering approach for ordered messages, Chapter 06 expands full solution.
5.2 Push Truth: Pull Wrapped in Long Polling
PushConsumer's "push" is illusion: underlying PullMessageService long-polls (Chapter 01 source foreshadowing), pulls messages then callbacks listener, no messages → suspend waiting broker notification. Framework handles pull rhythm, flow control, offsets, retry; cost: these behaviors default uncontrollable — consumption throttle ( PullThresholdForQueue default 1000 in-flight), listener timeout (concurrent 15min), thread pool size (default 20) all Push-mode encapsulated parameters. PullConsumer manages all: manual offset commit, self-controlled rhythm — streaming frameworks (Flink connector) use Pull, business rarely does.
API selection logic in one sentence: Want "framework managed" choose Push, want "self control" choose Pull . Push suits most business consumption: offsets, retry, flow control fully managed, cost is parameter understanding overhead; Pull suits three scenarios: streaming integration (Flink manages offset to checkpoint), batch offline consumption (scheduled batch pull, not real-time), ultra-high throughput (self-control pull rhythm squeeze broker). Pull users must implement offset commit and retry themselves — losing these two managed pieces means taking on "at-least-once" implementation responsibility.
Counter-intuitive point: Push "flow control" isn't service rejection but pause pulling — in-flight exceeds threshold, stop pulling, wait consumption digest. So flow control trigger manifests as "consumption latency quietly grows" not errors — monitor ProcessQueue in-flight volume and flow control trigger logs.
Production Practice: Consumer Config & Health Check
6.1 Consumer Production Full Config
Baseline config ready to copy (consumer group code + key parameters annotated):
DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("pay-consumer");
consumer.setNamesrvAddr("ns1:9876;ns2:9876");
// --- Subscription: only this one per group, into config management ---
consumer.subscribe("pay-topic", "*");
// --- Consumption mode & start offset ---
consumer.setMessageModel(MessageModel.CLUSTERING); // default, don't change
consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_LAST_OFFSET);
// --- Parallelism: thread count <= total queues ---
consumer.setConsumeThreadMin(20);
consumer.setConsumeThreadMax(20);
// --- Pull batch size: default 32, throughput can increase ---
consumer.setPullBatchSize(32);
// --- In-flight flow control: default 1000, backlog sensitive increase ---
consumer.setPullThresholdForQueue(2000);
// --- Retry: concurrent default 16 levels ---
consumer.setMaxReconsumeTimes(16);
// --- Listener: idempotent + exception classification, see below ---
consumer.registerMessageListener(listener);Exception classification in listener is most critical discipline beyond config: retryable exceptions (downstream temporarily unavailable) return RECONSUME_LATER for framework backoff; non-retryable poison (deserialization failure, missing data) record DLQ table then return CONSUME_SUCCESS to pass — let retry mechanism do what it's good at, don't feed poison into 16-level backoff spinning.
Beyond parameters, three "configured at broker, effective at consumer" global items to verify: consumer group "disable start" (consumption disable switch) used during release freeze to prevent new version accidental launch; consumer group retry config (max retries can override client value at broker) — broker prevails during troubleshooting; group consumption concurrency limit, thread count etc. in 5.x console support dynamic adjustment — dynamic adjust via canary, never full blast. These items enter 6.2 health checklist together.
6.2 Pre-Launch Health Checklist
Nine items before consumer group launch: ① Group name & subscription in config management (Incident 2); ② Instance count ≤ total queues & elasticity strategy assessed (Incident 1); ③ Consumption logic idempotent (offset replay + Rebalance transition both cause redelivery); ④ Exception classification implemented (poison messages no death loop); ⑤ DLQ alert & compensation task ready; ⑥ Backlog monitoring caliber correct (lag not offset diff); ⑦ Offset retention covers business replay window; ⑧ Broadcast mode offset persistence confirmed (Incident 3); ⑨ Ordered consumption maxReconsumeTimes configured. All nine green then ramp — each maps to a real incident.
Parameter "tuning view" closing: Consumer parameters mostly not performance knobs but "risk switches". Increase pull batch & in-flight threshold → throughput rises but memory & duplicate window simultaneously grow; increase thread count → parallelism rises but downstream connections & contention simultaneously grow. Every adjustment must ask "this value larger, what risk bought what?" — can't answer, don't touch. Consumer stability relies on health checklist, not parameter craftsmanship.
6.3 On-Call Caliber: Three Alert Handling Playbooks
Backlog alert: First check lag trend (spike vs gradual), then Rebalance logs (sawtooth), finally instance-queue distribution (skew) — troubleshoot in "mechanism first, code second" order. Retry surge: Watch %RETRY% topic TPS, first check listener exception classification logs to identify which exception class surging — downstream jitter temporary, code bug persistent. DLQ appears: P1 manual intervene, first inspect message body judge poison vs data issue, fix data then compensate re-publish, full record for postmortem.
Core Source Code: Four Key Implementations
First: rebalanceByTopic Diff Allocation
Lock-free independent computation core, source of all Rebalance phenomena:
private void rebalanceByTopic(final String topic, boolean isOrder) {
// 1. Full queue list (broker pull)
Set<MessageQueue> mqAll = mqClient.getTopicRouteInfo(topic);
// 2. Full consumer IDs (broker heartbeat table)
List<String> cidAll = mqClient.findConsumerIdList(topic, group);
if (mqAll == null || cidAll == null) return;
// Sorting ensures "everyone computes consistent input"
Collections.sort(mqAll);
Collections.sort(cidAll);
// 3. Allocation strategy: compute "which queues I own"
List<MessageQueue> allocateResult = strategy.allocate(this, group, this.clientId, mqAll, cidAll);
// 4. Diff: remove extra, add missing
boolean changed = updateProcessQueueTableInRebalance(topic, allocateResult, isOrder);
}Second: ProcessQueue.removeMessage
"Minimum unacknowledged watermark" implementation, soul of offset mechanism:
public long removeMessage(List<MessageExt> msgs) {
long result = -1;
lockTreeMap.writeLock().lock();
try {
// Remove completed messages from in-flight TreeMap
for (MessageExt m : msgs) {
msgTreeMap.remove(m.getQueueOffset());
}
// Watermark = minimum offset remaining in-flight
if (!msgTreeMap.isEmpty()) {
result = msgTreeMap.firstKey();
}
} finally {
lockTreeMap.writeLock().unlock();
}
return result; // committable offset
}Third: Concurrent Consumption Thread Model
Listener runs in dedicated thread pool, timeout & flow control hang here:
// ConsumeMessageConcurrentlyService
public void submitConsumeRequest(List<MessageExt> msgs, ProcessQueue pq, MessageQueue mq) {
// Batch split: single task max consumeMessageBatchMaxSize messages
ConsumeRequest request = new ConsumeRequest(batch, pq, mq);
// Submit to consumption thread pool
this.consumeExecutor.submit(request);
}
// ConsumeRequest.run: invoke listener + write back result
public void run() {
status = listener.consumeMessage(msgs, context);
// Decide by status: remove / rollback retry
processConsumeResult(status, msgs);
}Fourth: updateProcessQueueTableInRebalance "Return Queue" Branch
How removed queues exit gracefully:
// Diff: first handle "queues to return"
Iterator<Entry<MessageQueue, ProcessQueue>> it = pqTable.entrySet().iterator();
while (it.hasNext()) {
Entry<MessageQueue, ProcessQueue> e = it.next();
if (e.getKey().getTopic().equals(topic) && !newSet.contains(e.getKey())) {
// Not in new allocation: stop pulling
e.getValue().setDropped(true);
// Clean retry queue messages
removeRetryQueue(e.getKey());
// Persist offset then remove
offsetStore.persist(e.getKey());
it.remove();
}
}Source Code Thread: rebalanceByTopic decides "queue belongs to whom", removeMessage decides "how offset computed", thread model decides "how consumption runs", return-queue branch decides "how handoff graceful". Four implementations connected = full consumer picture — every monitoring phenomenon (sawtooth, backlog, duplicate, stuck queue) maps to one segment.
Beyond source code, add "why read source": Consumer issues mostly not "errors" but "behavior violates expectation" — duplicates, backlogs, disorder, retry ineffective. Answers not in error stacks, in mechanisms. Those who read these four segments, see phenomenon → directly infer which segment's behavior; those who haven't, guess and search — same problem, minutes vs hours difference. This is why series insists on source segments per chapter: Mechanism is source of judgment, tools merely amplify judgment.
Seven Accounts: Consumer Real Costs
Account 1: Parallelism. Parallelism ceiling = queue count not instance count (Chapter 01); instance internal parallelism = consumption threads, interacts with pull batch & in-flight threshold — three knobs together, tuning threads alone often ineffective.
Account 2: Rebalance. Every full reconciliation + queue handoff has consumption pause, frequent instance changes manifest as sawtooth backlog — governance via "less Rebalance", not parameter tuning.
Account 3: Duplicate Consumption. Offset rollback, Rebalance transition, re-delivery three paths all cause redelivery — idempotency (unique key + dedup table) mandatory bill, unpaid paid by data consistency.
Account 4: Retry. Concurrent retry 16-level backoff ~half-day window, retry messages occupy topic storage & traffic; ordered retry occupies queue — "retry free" illusion, monitoring must count retry traffic.
Account 5: Offset. Offset retention (default 48h) determines replay window; cold topic offsets expire then manual intervene — replay window business requirement, not technical default.
Account 5.5: Consumption Latency. End-to-end latency = send + store + pull + queue wait + business process. Queue wait easiest to deteriorate: peak queue depth (lag / consume TPS) directly multiplies latency — latency SLA not guaranteed by tuning parameters, by capacity planning: consume TPS headroom = peak traffic × recoverable capacity within peak duration. This account calculated at capacity review, 10x cheaper than post-alert.
Account 6: DLQ. DLQ write-only + limited retention — no alert & compensation task, DLQ = "silently disappearing messages"; governance trio is DLQ mechanism's final link.
Account 7: Broadcast. Broadcast offsets local, no retry managed, capacity scales linearly with instances — three costs exchange "everyone full", not convenience switch, independent architectural decision.
Closing question: Why consumer accounts harder than producer? Producer account = "single message cost", linearly predictable; Consumer account = "group of instances serving group of queues continuously", disturbed by Rebalance, skew, poison, retry four dynamic factors — any factor mutates, ledger recalculates. So consumer capacity planning needs double headroom (parallelism headroom + consume TPS headroom), and monitor all four disturbance factors — dynamic system budget, static ledger plus dynamic alerts dual defense.
20 Interview Questions (with Answers)
Q1: ConsumerGroup responsibilities? A: Load balancing unit (instances share queues); subscription consistency unit (same group must subscribe identically, broker overwrites per group); metadata anchor (offsets, %RETRY%, %DLQ% follow group name). Group name architectural asset, one service one group.
Q2: CLUSTERING vs BROADCASTING core difference? A: CLUSTERING: queue division, offsets broker, failure retryable, business default. BROADCASTING: all instances full consumption, offsets local file, failure single retry, backlog unmanaged — only for "everyone needs" like local cache refresh.
Q3: Subscription inconsistency fault mechanism & governance? A: Broker overwrites group subscription, last reporter wins, different subscriptions overwrite each other causing "restart drift" intermittent. Governance: one service one group, dynamic subscription via config center, subscription hash consistency audit alert.
Q4: Rebalance full flow? A: Every 20s (or broker notify) per topic: pull full queue list + group consumer IDs → sort for input consistency → allocation algorithm computes "my queues" → diff local ProcessQueueTable → add/remove. Lock-free independent compute, algorithmic determinism guarantees non-overlap.
Q5: Why duplicate during Rebalance? A: Two instances momentarily different consumer list versions (new instance not yet perceived) compute overlapping assignment, both consume same queue; offset advances by min unacknowledged, no loss but duplicate. "At-least-once" partly from Rebalance transition.
Q6: Three allocation algorithms selection? A: AVG (default): contiguous slices, minimal Rebalance churn, 90% correct; ROUND: uniform but scatters locality; Consistent Hash: instance changes only affect adjacent segments, but distribution depends on hash quality, may skew — selection based on "will instance count change frequently?" not algorithm merit.
Q7: Rebalance cost & governance? A: Removed queues consume in-flight before release, new queues rebuild pull pipeline, peak handoff pauses seconds; N scaling = each queue at least one handoff. Governance: serial rolling deploy, HPA desensitize/disable, stagger deploy windows, Rebalance count separate metric.
Q8: Why offset "minimum unacknowledged" not "latest consumed"? A: Offset = ProcessQueue TreeMap minimum offset: middle message unfinished watermark stuck. Benefit: offset always definite safe point, replay no miss; Cost: slowest message determines watermark + completed-uncommitted messages duplicate on crash — idempotency mandatory.
Q9: Why "commit before process" impossible in RocketMQ? A: CLUSTERING offset computed by framework via min unacknowledged, periodic commit, business no early commit entry. Manual offset control only via PullConsumer — self-manage means self-responsible for ordering & loss semantics.
Q10: Offset commit timing & lag? A: Default 5s periodic batch commit to broker, offset always lags actual consumption by seconds — design behavior not backlog. Monitor backlog via lag & ProcessQueue in-flight, not offset diff.
Q11: Offset rollback (history replay) operation & cautions? A: mqadmin resetOffset by time or offset. Three disciplines: confirm downstream idempotency & assess replay volume; stop consumption then rollback (else new offset overwrites); watch retry topic after rollback prevent poison flooding retry chain. Cold topics watch offset retention — expired only from latest.
Q12: Concurrent consumption retry mechanism? A: Failed message to %RETRY%group topic, broker 16-level delay (10s~2h) re-deliver, re-delivered messages re-enter Rebalance may switch instance; 16 levels exhausted → %DLQ%group DLQ. Listener uses getReconsumeTimes() distinguish first vs retry.
Q13: Why ordered retry different? A: For queue order, failed message local infinite retry (default MAX_VALUE) + queue suspend, no retry topic — one poison blocks entire queue. Must configure maxReconsumeTimes, exceed limit record DLQ then skip pass.
Q14: DLQ governance solution? A: Trio: DLQ topic alert (appearance = P1 manual); scheduled compensation fix data then re-publish original topic (confirm idempotency before re-publish); DLQ retention same as normal, expire delete — compensate early. Retry surge earlier signal than DLQ.
Q15: Poison message handling? A: Listener exception classification: retryable return RECONSUME_LATER for backoff; non-retryable (deserialization fail, missing data) record DLQ table then return CONSUME_SUCCESS pass. Concurrent feeding 16-level backoff spins half-day, ordered blocks queue — classification mandatory discipline.
Q16: How PushConsumer "push" implemented? A: Long-polling wrapped pull: PullMessageService per queue pull, messages callback listener, no messages suspend wait broker notify (Chapter 01 source). Framework encapsulates rhythm, flow control, offset, retry — flow control trigger manifests as latency growth not error.
Q17: Consumption flow control working? A: Push mode in-flight exceeds pullThresholdForQueue (default 1000) pauses pull, wait consumption digest — no error, only slower. Monitor ProcessQueue in-flight & flow control logs; backlog sensitive increase threshold but assess memory.
Q18: Concurrent thread model & parallelism tuning? A: Listener runs in consumeExecutor thread pool (default 20), single task max consumeMessageBatchSize. Parallelism = threads × instances, ceiling bounded by total queues; tuning requires threads, pull batch, in-flight threshold three together, threads alone often ineffective.
Q19: Consumer group backlog troubleshooting three axes? A: ① Lag trend: spike check upstream traffic or Rebalance, gradual check consumption latency degradation; ② Rebalance logs & count: sawtooth = handoff cost; ③ Instance-queue distribution: queue skew or thread pool saturated. "Mechanism first, code second" order, don't start with thread dump — most backlog locatable at mechanism layer.
Q20: Consumer group pre-launch mandatory checks? A: Group name & subscription in config management; instance count ≤ queues & elasticity assessed; consumption logic idempotent; exception classification implemented; DLQ alert & compensation ready; backlog monitoring caliber correct (lag); offset retention covers replay window; broadcast offset persistence confirmed; ordered consumption maxReconsumeTimes configured — nine green then ramp.
One-Page Cheat Sheet
Consumer Nine Sentences: ① Group name architectural asset: one service one group, subscription into config management; ② Rebalance lock-free independent compute: 20s reconciliation, sorting ensures determinism; ③ Allocation default AVG: minimal churn is hard truth; ④ Rebalance has cost: queue handoff = consumption pause, governance via less movement; ⑤ Offset is minimum unacknowledged: duplicate normal, idempotency mandatory; ⑥ Commit cycle 5s: offset always lags seconds, backlog watch lag; ⑦ Concurrent retry 16-level switch instance, ordered retry local block queue; ⑧ Poison messages must classify: record DLQ pass, don't feed backoff; ⑨ DLQ trio: alert, compensate, early — DLQ mechanism without this final link equals none.
Summary & Next Chapter Preview
All consumer mechanisms answer one question — "How does a group of instances process a group of queues exactly once, no more no less" . Rebalance answers "who processes which segment", offset answers "processed to where counts safe", retry answers "what if processing fails". Three answers combine into complete "at-least-once" implementation: no-loss guaranteed by offset closure, no-duplicate impossible, covered by idempotency. Remember "duplicate normal, idempotency mandatory, handoff has cost" — half of consumer production issues preemptively resolved.
Final "capability ladder": Layer 1 use (configure listener, run send/receive); Layer 2 know parameters (each switch risk & benefit); Layer 3 know mechanisms (Rebalance, offset, retry source logic); Layer 4 infer (see phenomenon → locate mechanism segment). Most stop at Layer 2 — tune parameters but can't explain why. This chapter targets Layer 3: mechanisms internalized, parameters merely externalized. Layer 4 needs more source reading, more incident postmortems, no shortcut.
Next chapter "Storage Engine" dives into broker disk: Why CommitLog hybrid storage "trades write amplification for global order", how ConsumeQueue index distributes, PageCache & flush real costs, message life on disk — grounding previous two chapters' "send" and "consume" onto storage layer.
Next Chapter Highlights: ① CommitLog hybrid storage design & write path; ② ConsumeQueue & IndexFile dual index division; ③ Three flush strategies & PageCache accounting; ④ Storage layer reverse constraints on send/consume behavior (which parameters storage decides).
For questions about attribution, corrections or content rights, please contactand we will review it promptly.