Kafka vs RocketMQ vs RabbitMQ: The Design Trade-offs Behind the Benchmark Numbers
During a peak sale, 80k TPS caused RabbitMQ to pile up 3 million messages and crash consumers — a real incident from our team. We later moved the order pipeline to RocketMQ, relying on transactional messages and billion-level backlog handling to survive the peak with zero message loss. This article explains the selection logic, underlying principles, and production defense designs of the three major MQs, suitable for backend developers doing tech selection or preparing for interviews.
1. Selection First: Three MQs, Three Design Philosophies
Many people start by memorizing throughput parameters, but that misses the point. These three are not substitutes for each other; they are trade-offs among three message semantics:
| Middleware | One-line Positioning | Design Philosophy | Persona Metaphor |
|---|---|---|---|
| Kafka | Distributed event log platform | Data semantics: how fast data flows | Freight train, carries one million items per trip |
| RocketMQ | Distributed business message middleware | Business semantics: how should this order proceed | SF Express: transactions, retries, and traceability out of the box |
| RabbitMQ | Enterprise message broker | Delivery semantics: where should the message go | Courier: flexible and punctual, but can't handle Double 11 |
A sentence I often tell my team: When selection stalls, ask "If this message is lost, will we lose money?" If money is lost, use RocketMQ; if it's just logs, pick Kafka without hesitation; if you need fancy routing and light weight, RabbitMQ is nice.
The judgment logic can be condensed: look at whether your business is a "stream" or a "transaction", whether you prioritize "throughput" or "routing".
Quick Selection by Scenario
| Scenario | Selection | One-line Reason |
|---|---|---|
| Log collection, tracking, stream computing, CDC/binlog sync, real-time data warehouse | Kafka | Million-level QPS, unbeatable Flink/Spark/ES ecosystem, losing one or two messages is fine |
| Order, payment, inventory, financial transaction main chain | RocketMQ | Transaction messages + delayed messages + ordered messages, business necessities |
| Complex routing notifications (SMS/email/Push fan-out), internal system decoupling, legacy system refactoring | RabbitMQ | Exchange routing is most flexible, microsecond latency, light ops |
| Small traffic, multi-protocol access (IoT/MQTT), need priority queues | RabbitMQ | AMQP/MQTT/STOMP multi-protocol, friendly management UI |
| Need both stream and queue, K8s cloud-native, willing to handle ops complexity | Look at Pulsar | Storage-compute separation, but not in today's scope |
Two Selection Principles Often Overlooked
First, hybrid selection is more common than picking a side. I've seen systems use Kafka for logs and RocketMQ for orders simultaneously, with clear boundaries and each doing its own job.
Second, architecture convergence principle: if the company already has an MQ, don't easily introduce a second one; the ops cost often outweighs the feature benefit. If you already have Kafka and the business volume isn't large, reusing Kafka is cheaper than standing up a new RocketMQ.
Of course, there are also anti-examples of selection. I've seen others step into these three traps:
- Using Kafka for business transactional messages → semantic mismatch, reliability can't hold up;
- Using RabbitMQ to handle high throughput → backlog OOM, cluster avalanche;
- RocketMQ ordered messages used incorrectly → state confusion, ghost data in database.
Selection is only 20% of the work; the remaining 80% is defense design against four pitfalls: lost messages, duplicates, ordering, and backlog. Below we first understand the design behind the parameters, then break down each pitfall.
2. Hard Metrics Comparison: Don't Memorize the Table, Understand the Trade-offs
Performance and Reliability
| Dimension | RocketMQ | RabbitMQ | Kafka |
|---|---|---|---|
| Origin/Language | Alibaba, Java (readable source) | VMware, Erlang (high refactoring barrier) | LinkedIn/Apache, Scala/Java |
| Protocol | Custom Remoting (4.x) / gRPC (5.x) | AMQP / MQTT / STOMP | Custom binary TCP |
| Single-node throughput | Hundreds of thousands | Tens of thousands (~5w) | Hundreds of thousands to millions |
| End-to-end latency | Millisecond-level | Microsecond-level, lowest | Millisecond-level (higher with batching) |
| Backlog capacity | Billion-level without performance degradation | Weak, struggles at ten million | TB-level, strongest |
| Message reliability | High (sync dual-write/sync flush) | High (Confirm + mirrored/quorum queues) | Medium (acks=all for high, at cost of performance) |
| Availability architecture | Master-slave sync / DLedger (Raft) | Mirrored queues / Quorum queues (Raft) | ISR replicas + Controller |
| Ops cost | Medium (Java stack friendly) | Low | Medium-high (depends on ZK/KRaft) |
Business Features
| Dimension | RocketMQ | RabbitMQ | Kafka |
|---|---|---|---|
| Message model | Topic → MessageQueue (queue-centric) | Exchange → Queue (routing-centric) | Topic → Partition (partition-centric) |
| Consumption mode | Long-polling Pull (pseudo Push) | Push (with prefetch flow control) | Pure Pull (self-paced) |
| Transactional messages | Native half-message + callback | No native, rely on Confirm + local message table | Has transaction API, more for stream processing EOS |
| Delayed messages | Native 18 levels / 5.x arbitrary time | TTL + dead-letter workaround / plugin | No native, need self-build |
| Ordered messages | Queue-level ordering (native selector) | Only single-queue single-consumer ordered | Partition-level ordering |
| Message replay | Reset by time/offset | Consumed and deleted, not supported | Rewind by offset/timestamp at will |
| Retry/DLQ | 16-level gradient retry + DLQ | Limited retry + dead-letter exchange | Weak, need business self-build |
| Routing/Filter | Tag / SQL92 attribute filter | Four Exchange types, most flexible | Topic+Partition, client-side filter |
| Priority queues | Not supported | Native support | Not supported |
| Broadcast consumption | BROADCASTING mode | Fanout | Need multiple Groups to simulate |
| Message trace | Built-in | Plugin | Need external tools |
| Big data ecosystem | Average | Weak | Unbeatable |
Why is throughput so different? Kafka relies on sequential disk writes + page cache + batch accumulation + zero-copy to push throughput to millions; RabbitMQ's broker is heavy in functionality, creating a natural bottleneck; RocketMQ sits in between, balancing performance and functionality.
Why is latency reversed? RabbitMQ uses Erlang's lightweight scheduling, transferring messages as they arrive; Kafka batches messages for throughput, naturally increasing latency to milliseconds. This is the classic throughput-latency trade-off; there's no free lunch.
The parameter table is easy to forget, but once you understand the architectural root cause, you won't forget it. The next chapter is where the real gap appears.
3. Architecture and Storage: Where Does the Performance Gap Come From
3.1 Three Architecture Diagrams, See the Division at a Glance
Three key architectural conclusions:
- Who is "smarter": RabbitMQ's broker does routing, ACK tracking, and dead-letter handling, making it heavy and slow; Kafka's broker only appends and replicates, pushing logic to clients, so it's fast.
- Storage model: RabbitMQ messages go into queue structures with many random writes, so backlog degrades performance; RocketMQ and Kafka both do sequential disk writes + page cache, so they can handle backlog.
- High availability: RabbitMQ uses mirrored/quorum queues (Raft); RocketMQ 4.x has a message-loss window with asynchronous master-slave replication, while 5.x / DLedger uses Raft for true strong consistency; Kafka uses ISR + min.insync.replicas, with Controller handling leader migration.
3.2 Kafka's Four Killer Techniques for Speed
- Sequential disk writes: Each partition is a pure append log; writes always go to the end of the file. Sequential disk writes can reach 600MB/s, 2-3 orders of magnitude faster than random writes. Kafka treats disk as a large sequential log.
- PageCache priority, not JVM heap: Reads and writes go through OS page cache, with kernel async flush. JVM heap is only a few GB and lost on restart; page cache survives restart, and GC pressure is much lower.
- Zero-copy sendfile: Data goes from disk → kernel buffer → NIC, never through user space. The normal path does 4 copies; sendfile reduces to 2 copies, saving 2 copies and 2 user-space switches.
- Batching + partition parallelism: Producers batch send, consumers pull by partition in parallel, combined with sparse indexes and client-side deserialization, minimizing broker load.
Pitfall warning: zero-copy has failure conditions. When TLS is enabled, message format conversion is performed, or cross-cluster replication happens, sendfile can't be used. Many "cloud Kafka throughput halved" incidents hit exactly this.
There's also a counterintuitive point: Kafka keeps one independent log file per partition; sequential reads are pure, but too many partitions degrade into random writes. So more partitions isn't always better.
The cost is feature subtraction — no delayed queue, no business transactional messages, no single-message operations. It's not that it can't do them; it deliberately doesn't.
3.3 RocketMQ's Storage Ingenuity: CommitLog + ConsumeQueue
For writes, all topics are mixed and appended sequentially (learning from Kafka's speed); for reads, lightweight index queues locate messages. Each ConsumeQueue index is only 20 bytes: [offset, size, tagHash], like a book's table of contents.
This is RocketMQ's confidence to support massive business topics. Kafka does random reads under many topics; RocketMQ solves this with "one sequential write, multi-dimensional index read". When piled up, only disk files increase, and consumption progress stores only offsets, unlike RabbitMQ where queue structures live in memory, so billion-level backlog doesn't affect performance.
At the routing layer, RocketMQ uses NameServer instead of ZooKeeper: lightweight, stateless, avoiding ZK's heavy ops and split-brain problems. Brokers register topic routing with NameServer at startup and maintain heartbeats; producers/consumers pull routing at startup.
The consumption model also has a clever design — long-polling Pull: after a consumer sends a Pull request, if the broker has no messages, it holds the request (default 15s) and returns immediately when a message arrives. This avoids the traffic impact of Push and the empty-polling overhead of Pull.
| Consumption mode | Representative | Features |
|---|---|---|
| Pure Pull | Kafka | Consumer self-paced, but empty polling has overhead |
| Push | RabbitMQ | Good real-time, but can overwhelm consumers; needs prefetch flow control |
| Long-polling Pull | RocketMQ | Advantages of both |
3.4 RabbitMQ: Not "Slow", but "Different Scenario"
RabbitMQ is based on Erlang OTP, with Actor model in-memory exchange extremely fast and naturally high availability/fault tolerance. Its core competitiveness is the Exchange routing model: Direct, Topic, Fanout, Headers four exchange types, completely decoupling "send" and "who receives", with routing rules flexible to the max.
But the weakness is clear: messages preferentially reside in memory, so when backlog grows, it frantically writes to disk and performance avalanches; mirrored queues do master-slave with high sync replication overhead. So don't choose it for high-throughput + high-backlog scenarios.
3.5 Storage Model Determines a Key Capability: Can You Replay?
| Storage model | Behavior | Replay capability |
|---|---|---|
| Kafka: independent log file per partition | Consumption ≠ deletion; consumer maintains offset | Rewind by offset/timestamp at will (within retention) |
| RocketMQ: CommitLog + ConsumeQueue + IndexFile | Consumption progress stored as offset | Reset by time/offset |
| RabbitMQ: traditional queue | Consumed and deleted | Not supported |
Real experience: message replay is a lifesaver when troubleshooting online issues. We chose RocketMQ for e-commerce orders largely because we can replay messages by time point when problems occur.
Architecture understood, now we enter the deep water: transactional messages. This is RocketMQ's killer feature that widens the gap.
4. Transactional Messages: RocketMQ's Killer Feature
4.1 The Problem: Send Message First or Write to DB First?
In real development we often encounter this: placing an order requires deducting inventory and sending a message to notify the points system. Sending a message inside @Transactional? If the transaction rolls back after sending, it's dirty data. Writing to DB first then sending? If DB commit succeeds but message sending fails, the downstream never receives notification.
Local transaction and sending a message are not naturally atomic. That's the philosophical problem of "send first or write to DB first".
4.2 Half Message + Callback: Two-Phase Commit + Compensation
RocketMQ's solution is essentially "two-phase commit + compensation callback":
Principle details: Half messages are written to internal topic RMQ_SYS_TRANS_HALF_TOPIC (also written as %half%) and persisted, invisible to consumers. After the local transaction succeeds, Commit makes the message visible in the real topic; if it fails, Rollback discards it.
Technical highlight: the callback mechanism completes "final consistency". When network jitter causes the broker to miss Commit/Rollback, the broker actively calls back the producer, ultimately guaranteeing "local transaction success ⇔ message must be delivered". Compared to "local message table + scheduled scan", it eliminates scan latency and DB pressure.
4.3 Core Code
Native API version:
TransactionMQProducer producer = new TransactionMQProducer("order_tx_group");
producer.setNamesrvAddr("127.0.0.1:9876");
producer.setTransactionListener(new TransactionListener() {
/** Half message sent successfully, execute local transaction */
@Override
public LocalTransactionState executeLocalTransaction(Message msg, Object arg) {
try {
// Local transaction: deduct inventory + write local message table (same transaction)
orderService.createOrder((OrderDTO) arg);
return LocalTransactionState.COMMIT_MESSAGE;
} catch (Exception e) {
return LocalTransactionState.ROLLBACK_MESSAGE;
}
}
/** Broker callback: query DB authoritative state, never rely on memory (lost on restart) */
@Override
public LocalTransactionState checkLocalTransaction(MessageExt msg) {
String orderId = msg.getKeys();
boolean exists = orderService.existsByOrderNo(orderId);
return exists ? LocalTransactionState.COMMIT_MESSAGE
: LocalTransactionState.UNKNOW; // If not sure, check again next round
}
});
producer.start();
Message msg = new Message("ORDER_TOPIC", "PAID", orderId, JSON.toJSONBytes(order));
msg.setKeys(orderId); // For message trace queries
producer.sendMessageInTransaction(msg, order);
Spring Boot version (rocketmq-spring):
// Sender
TransactionSendResult r = rocketMQTemplate.sendMessageInTransaction(
"order_tx_group",
MessageBuilder.withPayload(AddPointCmd.of(order))
.setHeader(RocketMQHeaders.TRANSACTION_ID, order.getTxId())
.build(),
order); // arg is passed through to local transaction executor
// Transaction listener
@RocketMQTransactionListener(txProducerGroup = "order_tx_group")
public class OrderTxListener implements RocketMQLocalTransactionListener {
@Override
public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object arg) {
try {
orderService.doLocal((Order) arg);
return RocketMQLocalTransactionState.COMMIT;
} catch (Exception e) {
return RocketMQLocalTransactionState.ROLLBACK;
}
}
@Override
public RocketMQLocalTransactionState checkLocalTransaction(Message msg) {
String txId = (String) msg.getHeaders().get(RocketMQHeaders.TRANSACTION_ID);
return orderMapper.existsByTxId(txId)
? RocketMQLocalTransactionState.COMMIT
: RocketMQLocalTransactionState.ROLLBACK;
}
}
4.4 Three Must-Avoid Pitfalls + Callback Details
Mention these three pitfalls in an interview and you get extra points:
txProducerGroupmust match the producer group; if wrong, Half messages hang forever;- Callback must query DB authoritative state, not rely on in-memory variables, which are lost on process restart;
- Consumers must be idempotent, because there's no transaction between broker and consumer; only at-least-once is guaranteed.
Regarding the callback return value, there's an easy point to get tangled: If you can be sure, explicitly return COMMIT/ROLLBACK; don't return UNKNOWN for long. Returning UNKNOWN when you truly can't judge (e.g., transaction still executing) is reasonable to let next round check, but long-term UNKNOWN causes repeated callbacks and backlog.
The default max callback count is 15 times with 60s interval (configurable); after exceeding, messages go to TRANS_CHECK_MAX_TIME_TOPIC. In production, you must monitor this topic — the messages there are hanging transactions.
4.5 What If You Don't Have Transactional Messages?
For Kafka or RabbitMQ scenarios, the standard fallback is local message table (Transactional Outbox) + scheduled task scanning and resending: business table and message table are written in the same local transaction, then asynchronously delivered. An advanced approach is Outbox + Debezium CDC, using binlog to capture message table changes and deliver to MQ, even eliminating table scans.
4.6 Kafka's Exactly-Once: Idempotence + Transactions
Kafka also has transactions, but the semantics differ — it solves atomic writes across partitions in stream processing, not "local transaction + send message" consistency.
Properties props = new Properties();
props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "kafka:9092");
props.put(ProducerConfig.ACKS_CONFIG, "all");
props.put(ProducerConfig.RETRIES_CONFIG, Integer.MAX_VALUE);
props.put(ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG, true); // Idempotence: PID + SeqNum dedup
props.put(ProducerConfig.MAX_IN_FLIGHT_REQUESTS_PER_CONNECTION, 5);
props.put(ProducerConfig.TRANSACTIONAL_ID_CONFIG, "order-tx-001");
KafkaProducer<String, String> producer = new KafkaProducer<>(props);
producer.initTransactions();
try {
producer.beginTransaction();
producer.send(new ProducerRecord<>("order-topic", "1001", "Order created"));
producer.send(new ProducerRecord<>("inventory-topic", "1001", "Inventory deducted"));
producer.send(new ProducerRecord<>("points-topic", "1001", "Points added"));
producer.commitTransaction(); // Atomic write across topics/partitions
} catch (Exception e) {
producer.abortTransaction();
}
// Consumer must use read_committed, otherwise it may read uncommitted messages
consumerProps.put(ConsumerConfig.ISOLATION_LEVEL_CONFIG, "read_committed");
Principle highlight: Idempotence relies on PID + monotonically increasing SeqNum, with broker-side caching of last sequence for dedup; transactions rely on internal
__transaction_statetopic + Hanging Transaction detection (auto-abort after 24h unresolved).
Key insight: Kafka's EOS only holds within the Kafka→Kafka (read_committed) closed loop. Once messages leave Kafka into business databases, Exactly-Once must be guaranteed by consumer-side idempotency.
After transactions, the next high-frequency need is delayed messages — "auto-cancel after 30 minutes unpaid", where the three MQs have completely different fates.
5. Delayed Messages: One 30-Minute Order Close, Three Fates
| MQ | Solution | Pitfall |
|---|---|---|
| RocketMQ | Native 18 levels (1s~2h), 5.x supports arbitrary time | 4.x levels are fixed, cannot be arbitrary |
| RabbitMQ | Message TTL + dead-letter exchange forwarding | Head-of-line blocking; plugin approach can bring down cluster under load |
| Kafka | No native support, DIY time wheel / delayed topic | High cost; better to switch MQ |
5.1 RabbitMQ: TTL + Dead Letter, Works but Has Pitfalls
Head-of-line blocking pitfall: RabbitMQ's TTL is a head-of-line blocking check — the first message has a 30-minute TTL, the second has 5 minutes, but the second must wait for the first to expire! I've stepped on this myself; short-delay messages get completely blocked by long-delay ones.
Solution: Split queues by delay tier (1min/5min/10min/30min each one queue), or use the rabbitmq_delayed_message_exchange plugin. But the plugin is based on Mnesia sorting, a large volume can bring down the cluster; use with caution.
5.2 RocketMQ: One Line Does It, the Principle Is "Swapping the Topic"
// 4.x: delayLevel 1~18, level 3 = 10s
Message msg = new Message("order_topic", body);
msg.setDelayTimeLevel(3);
producer.send(msg);
// 5.x: arbitrary second-level delay
Message<String> msg5 = MessageBuilder.withPayload(orderId)
.setHeader(RocketMQHeaders.DELAY_TIME_SECONDS, 30 * 60)
.build();
rocketMQTemplate.syncSend("ORDER_CANCEL_TOPIC", msg5);
Principle highlight: When sending a delayed message, before writing to CommitLog, the broker replaces the topic with the internal topic for the corresponding delay level, managed by 18 scheduled tasks in
ScheduleMessageService. When the time expires, the message is rewritten back to the real topic and delivered. It doesn't occupy business queues or block. 5.x switches to time wheel (TimerWheel) + tiered disk storage, supporting arbitrary second-level precision.
5.3 Kafka: DIY
Kafka has no native delayed messages; you must build multi-level delay topics or a time wheel. A lightweight alternative: Redis ZSET as a time wheel, score stores expiration time, deliver to MQ when due. But honestly, if delayed messages are a business need, switch to RocketMQ instead.
Delay and transactions are both "single-message semantics". Next, we discuss a more tangled topic: ordering.
6. Ordered Messages: Global Ordering Is a False Need
First remember the core formula:
Same business key → same queue/partition → single-threaded consumption = local ordering.
An order's "create → pay → complete" must be ordered, but order A and order B don't need ordering between them. Global ordering = single queue single consumer = throughput goes to zero (degrading to thousands of TPS). Whoever suggests it takes the blame.
6.1 RocketMQ: Send Selects Queue + Consume with Orderly
// Sender: same orderId always goes to the same MessageQueue
SendResult result = producer.send(msg, new MessageQueueSelector() {
@Override
public MessageQueue select(List<MessageQueue> mqs, Message m, Object arg) {
long orderId = (Long) arg;
int index = (int) (orderId % mqs.size());
return mqs.get(index);
}
}, orderId);
// Consumer: must use ordered listener, single queue single thread
consumer.registerMessageListener(new MessageListenerOrderly() {
@Override
public ConsumeOrderlyStatus consumeMessage(List<MessageExt> msgs,
ConsumeOrderlyContext ctx) {
process(msgs);
return ConsumeOrderlyStatus.SUCCESS;
}
});
Spring version is simpler:
rocketMQTemplate.syncSendOrderly("ORDER_STATUS_TOPIC",
MessageBuilder.withPayload(statusEvent).build(),
String.valueOf(orderId)); // hashKey
@RocketMQMessageListener(
topic = "ORDER_STATUS_TOPIC",
consumerGroup = "order-status-cg",
consumeMode = ConsumeMode.ORDERLY, // Single-threaded serial, no thread pool concurrency
maxReconsumeTimes = 5
)
public class OrderStatusListener implements RocketMQListener<MessageExt> {
@Override
public void onMessage(MessageExt msg) {
// Business exception → log to side table, must return, no infinite retries
}
}
The fatal flaw of ordered messages: one stuck message blocks the entire queue. Ordered consumption locks the queue; returning
SUSPEND_CURRENT_QUEUE_A_MOMENTon exception blocks the queue. Our practice is "retry 3 times then move to async compensation table and let go", avoiding a single dirty message killing the whole chain.
Companion discipline: business timeout must be <30s (RocketMQ default retry is 15min, too long); no Thread.sleep and no remote calls without timeout.
6.2 Kafka: Key Hashing + Prevent Reorder on Retry
// Same bizKey hashed to the same partition = local ordering, without affecting multi-partition parallel throughput
producer.send(new ProducerRecord<>("order-event",
Math.abs(orderId.hashCode()) % partitions, orderId, json));
Kafka has two ordering pitfalls:
- Retries can kick a message out of its original position: must set
max.in.flight.requests.per.connection=1, or enableenable.idempotence=true(thenmax.in.flight ≤ 5can still preserve order via SeqNum); - Rebalance or partition expansion can briefly break ordering: expanding partitions requires caution; observe after expansion.
6.3 RabbitMQ: Single Queue Single Consumer
RabbitMQ can only preserve ordering with a single queue and single consumer; concurrency breaks order, essentially trading throughput for ordering.
6.4 Two Advanced Pitfalls
Hot queue skew: A well-chosen hashKey doesn't mean even distribution. If a leading merchant accounts for 40% of orders, one queue accumulates millions while others sit at zero. The solution is salt spreading hash(orderId + random(0~2)), at the cost of sacrificing local ordering, backed by business state machine.
Reordering due to retries: retry messages arrive later than new messages, causing business state confusion. The solution is to include a version number/timestamp in messages, compare state machines on consumption, and use "latest state overwrites" for critical states rather than "incremental accumulation".
With ordering done, let's talk about the most life-threatening problem: message loss.
7. Message Loss: Three-Stage Defense
A message's lifecycle has three leakage points that must be blocked segment by segment:
| Stage | RocketMQ | RabbitMQ | Kafka |
|---|---|---|---|
| Producer | Synchronous send + check SendStatus=SEND_OK + retry on failure (default 2); for financial scenarios use transactional messages |
DB + Publisher Confirm + mandatory + Return fallback + scheduled compensation |
acks=all + retries + enable.idempotence |
| Broker | flushDiskType=SYNC_FLUSH sync flush + SYNC_MASTER sync dual-write (or DLedger three replicas) |
Queue durable=true + message persistent + mirrored/Quorum queues |
replication.factor>=3 + min.insync.replicas=2 + disable unclean.leader.election.enable |
| Consumer | Return CONSUME_SUCCESS only after business success; failures go to %RETRY% and after 16 retries to %DLQ% |
Manual basicAck, disable autoAck, prefetch for flow control |
Commit after business processing with commitSync, never auto-commit |
Financial-grade must enable sync flush + sync dual-write, at the cost of RT increase. That's another trade-off between reliability and performance.
7.1 RabbitMQ Producer Standard Pattern for "No Loss"
Save message to DB first → send with msgId → Confirm callback updates status → Return fallback for routing failure → scheduled task compensation:
MsgLog log = saveMsgLog(order); // status=0 pending confirmation
CorrelationData cd = new CorrelationData(log.getMsgId());
rabbitTemplate.convertAndSend("order.exchange", "order.create", order, cd);
rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
if (ack) {
msgLogRepository.updateStatus(correlationData.getId(), 1); // Reached Exchange
} else {
msgLogRepository.updateStatus(correlationData.getId(), 2); // Failed, wait for compensation
}
});
// ReturnCallback: reached Exchange but not routed to any Queue
rabbitTemplate.setReturnCallback((msg, code, text, exchange, routingKey) -> {
msgLogRepository.updateStatus(msg.getMessageProperties().getCorrelationId(), 2);
});
7.2 Kafka Producer: High Reliability + High Throughput Config
Properties props = new Properties();
props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "kafka:9092");
props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
// High reliability
props.put(ProducerConfig.ACKS_CONFIG, "all"); // Wait for ISR confirmation
props.put(ProducerConfig.RETRIES_CONFIG, Integer.MAX_VALUE);
props.put(ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG, true); // Prevent duplicates from retries
props.put(ProducerConfig.MAX_IN_FLIGHT_REQUESTS_PER_CONNECTION, 5);
// High throughput
props.put(ProducerConfig.COMPRESSION_TYPE_CONFIG, "lz4"); // Batch compression, 3-5x compression ratio
props.put(ProducerConfig.BATCH_SIZE_CONFIG, 16384);
props.put(ProducerConfig.LINGER_MS_CONFIG, 5); // Micro-batching, trade 5ms for throughput
KafkaProducer<String, String> producer = new KafkaProducer<>(props);
producer.send(record, (metadata, exception) -> {
if (exception != null) {
retryService.save(order); // Failure must not just log; enter compensation chain
}
});
Must-avoid pitfall: Kafka's
auto.commitcommits as soon as messages are pulled, even if business processing fails → message loss. Must setenable.auto.commit=falseand manually commit after business. In the rebalance listener,onPartitionsRevokedmust flush before committing.
7.3 Consumer-side Iron Rules + Reconciliation Fallback
Consumer-side three moves are indispensable: manual ACK + idempotency check + fail to dead letter. In RocketMQ, don't wrap async logic with CONSUME_SUCCESS — if async hasn't finished when you tell the broker success, a crash loses the message.
RabbitMQ consumer Spring config:
@Bean
public SimpleRabbitListenerContainerFactory ackContainerFactory(ConnectionFactory cf) {
SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
factory.setConnectionFactory(cf);
factory.setAcknowledgeMode(AcknowledgeMode.MANUAL); // Manual ACK
factory.setPrefetchCount(50); // Flow control, avoid overwhelming consumers
return factory;
}
@RabbitListener(queues = "order.queue", containerFactory = "ackContainerFactory")
public void consume(OrderMessage msg, Channel channel, Message message) throws Exception {
try {
orderService.process(msg);
channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
} catch (Exception e) {
// requeue=false, don't return to original queue (avoid infinite loop), go to dead letter
channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
}
}
Finally, there's an ultimate fallback: deploy a reconciliation task that compares local message table and consumption records, compensating any inconsistency. For 50 million messages per day requiring no loss and no duplication? Sync dual-write + sync flush guarantee no loss, business unique ID idempotency table guarantees no duplication, transactional messages guarantee order and inventory consistency, plus reconciliation — done.
No loss solved, "no duplication" comes next — because MQ only guarantees at-least-once.
8. Duplicate Consumption: Idempotency Is Always Your Job
Remember this formula:
At-Least-Once + business idempotency = Exactly-Once business effect.
All MQ products only guarantee at-least-once, not exactly-once (unless you pay a 10x performance cost). Network glitches, rebalances, and timeout retries all cause duplicate delivery. Don't expect MQ to deduplicate.
Idempotency Scheme Comparison
| Scheme | Description | Applicability |
|---|---|---|
| Unique business key | Order number, payment transaction number + operation type | Foundation for all scenarios |
| Redis SETNX | Preempt before consumption, high performance | First line of defense |
| DB unique index | Most stable, duplicate insert errors | Final fallback |
| State machine CAS | update ... set status=2 where status=1 |
State transition business |
Generic Idempotency Template: Redis + Unique Key Double Insurance
public void onMessage(MessageExt msg) {
String msgId = msg.getMsgId();
// First line of defense: message ID dedup (prevent MQ duplicate delivery)
// setIfAbsent is atomic, no distributed lock needed, high performance
Boolean ok = redis.opsForValue()
.setIfAbsent("mq:idem:" + msgId, "1", 24, TimeUnit.HOURS);
if (Boolean.FALSE.equals(ok)) {
return; // Duplicate message, return success directly, let MQ not redeliver
}
try {
// Second line of defense: business unique key (prevent upstream duplicates like double clicks)
// Add unique index on biz_key at DB level; duplicate insert throws DuplicateKeyException
orderService.cancelOrder(msg);
} catch (DuplicateKeyException dup) {
// Idempotency hit, treat as success
} catch (Exception e) {
// Business failure must delete the marker, otherwise retried messages will be falsely blocked! (90% of people miss this step)
redis.delete("mq:idem:" + msgId);
throw e; // Throw exception to trigger retry
}
}
Several details worth expanding:
- SETNX must have TTL (e.g., 10min~24h) to prevent permanent lock from a stuck consumer;
- Release the marker on failure, otherwise all retries are blocked and messages are effectively swallowed;
- Redis jitter can cause penetration, so DB unique index/state machine is the final fallback; advanced use can be
INSERT ... ON DUPLICATE KEY UPDATE; - Kafka's idempotent producer reduces source duplicates, but consumer-side idempotency is still required.
Interview follow-up prediction: "Why use Redis instead of a Bloom filter?" Bloom filters have false positives and can't delete; message scenarios require 100% accuracy and the ability to roll back markers on failure.
Idempotency is defense; backlog is firefighting. The next chapter is the most practical part of the entire article.
9. Message Backlog: 3 Million Messages, Don't Panic, and Don't Restart
9.1 Position First, Then Act
Look at Consumer Lag to locate the bottleneck; don't just add machines.
9.2 Emergency Four Steps
- Stop the bleeding first: temporarily scale up consumer instances. But note consumer count ≤ queue/partition count; more is decoration, just adjusting
consumerThreadsis ineffective. - If queues aren't enough, expand: temporarily create a new topic with 10x queues, write a "conveyor" program to quickly read the backlog and forward messages unchanged to the new topic, then start 10x consumers to work hard.
- Batch whenever possible: change single insert to batch insert; DB is the big bottleneck; for heavy consumption logic, first transfer to a temporary queue to quickly release the flood, then process slowly later.
- Degrade non-core: marketing messages can be dropped or sampled, insignificant logs lose some history, protect the main chain.
Pitfall warning: don't panic, don't restart. Restart loses offsets and makes things worse. Before every major sale, we always: do full-link load testing at 3x peak + simulate backlog drills, and prepare "temporary expansion scripts" in advance, rather than typing them that night.
9.3 RabbitMQ Backlog Avalanche Special
When Erlang VM memory fills up, flow control triggers and blocks producers. Countermeasures:
- Set queue
x-queue-mode: lazy(messages directly to disk); - Lower
vm_memory_high_watermark 0.6; - Reduce
prefetch, setx-max-length; - ACK promptly, split queues, monitor
memory_alarm.
Root solution: switch high-traffic links to RocketMQ.
9.4 Kafka Rebalance Storm Special
Frequent consumer up/down or max.poll.interval.ms timeout causes rebalance storms, during which duplicate consumption and throughput collapse occur. Tuning directions:
- Increase
max.poll.interval.ms, decreasemax.poll.records; - Use CooperativeStickyAssignor to reduce partition migration;
- Match consumer count to partition count, avoid consumer thread blocking.
9.5 Dead Letter Handling Closed Loop
Poison messages that fail consumption can't infinitely retry and block queues; there must be a closed loop:
For RabbitMQ dead letter consumers, use exponential backoff based on retryCount; after 5 times, write to DB for manual intervention.
9.6 Monitoring: Don't Only Watch TPS
The monitoring blind spot many ignore: only watching TPS, not lag. Must instrument: send success rate, consumer lag, end-to-end latency, dead letter count, retry count; alert immediately on dead letter spike.
After the backlog fire is put out, there are several easy-to-overlook functional details that can save lives at critical moments.
10. Easy-to-Overlook Features and Details
Large messages (>1MB): MQ is not suitable for storing large bodies. The correct approach is transfer to object storage, MQ only passes the OSS key. Kafka's max.message.bytes adjustment has costs; not recommended.
Message trace: When customer service asks "where did this order's message go", you need to answer. RocketMQ enables traceTopicEnable=true (costs about 10% performance), combined with a self-built message trace dashboard for full-chain tracing by msgId/bizKey. Set msg.setKeys(orderId) when sending for easy query.
Message filtering: RocketMQ supports Tag / SQL92 attribute filtering, RabbitMQ relies on Exchange routing (strongest), Kafka only client-side filtering.
Broadcast consumption: When multiple services need to be aware of the same message, Kafka uses different Groups, RocketMQ uses BROADCASTING mode, RabbitMQ uses Fanout or multiple queues.
What if NameServer is fully down? This is a classic follow-up question. NameServer is stateless; producers/consumers cache routing info locally, so they can still send/receive normally in the short term. But they can't perceive broker up/down and new topic routing, so NameServer should also be deployed in cluster.
Cross-MQ consistency reconciliation: Under a dual-track architecture (Kafka data flow + RocketMQ business flow), cross-MQ consistency depends on local message table + scheduled reconciliation + dead letter manual fallback.
Details complete, finally wrap up to selection decision tree.
11. Selection Decision Tree and Implementation Recommendations
Selection looks at three numbers: TPS scale, latency sensitivity, consistency requirements. The order is: first match scale, then satisfy functionality, finally consider team and ops capability.
Our implementation conclusions:
- Transaction chain (order/payment/refund) → RocketMQ: transactional messages + 30min delayed cancellation + 16-level gradient retry;
- In-site notification/operation push → RabbitMQ: flexible routing, small traffic, easy ops;
- Tracking/log/data lake ingestion → Kafka: Flink direct connect, TB-level backlog without worry.
Closing quote: Kafka manages how data flows, RocketMQ manages how money moves, RabbitMQ manages how work is dispatched.
Memory card for everyone: throughput depends on zero-copy, reliability depends on callback, ordering depends on hashing, idempotency always on the consumer side.
Final Words
There's no silver bullet among the three MQs. The core is five things: no loss, no duplication, ordering, backlog, consistency. Selection only accounts for 20%; the remaining 80% is defense design.
Implementation advice: consumer-side idempotency and manual ACK are the bottom line, hold them first; use transactional messages and delayed messages based on business needs; don't skip pre-sale load testing and backlog drills; monitoring lag and dead letter count is more important than monitoring TPS.
If this article is useful to you, give a like and watching, and forward to colleagues who are doing selection. Follow me; next issue will break down RocketMQ CommitLog storage source code, and "how to expand partitions without stopping and without breaking ordering when 20 million messages are backlogged".
Interactive question: Which MQ is your team using now? Have you encountered an online incident with message backlog or loss, and how did you locate it? Leave a comment; I'll pick typical ones for analysis.