Skip to content

Checking your reading list…

Retry

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's Real Value: Native Delayed Messages, Transactions & Built-in Retry/DLQ

This article explains why RocketMQ is chosen for its native delayed messages, transaction messages, and built-in retry/dead-letter queues rather than throughput, covering architecture, Docker deployment, Spring Boot integration, delayed message patterns for order cancellation, transaction message flow with half-messages and broker check-back, and seven common pitfalls with solutions.

Why RocketMQ? Not for Throughput, But for Business Semantics

The article opens with a common requirement: cancel an order if not paid within 30 minutes. It compares implementations: RabbitMQ needs a TTL queue plus a dead-letter exchange and suffers from head-of-line blocking when queues grow; Kafka lacks delayed messages entirely, forcing consumers to pull messages and sleep while holding threads; RocketMQ solves it with a single API. This establishes RocketMQ's position: throughput loses to Kafka (hundreds of thousands vs millions), deployment is heavier than RabbitMQ (NameServer + Broker), but delayed messages and transaction messages are native — and these are exactly what business systems need most.

Architecture: Two Components, No Exchange

Producer → Broker (stores messages, master-slave deployment) ←→ Consumer
                 ▲
                 | reports routing info every 30s
                 NameServer (stateless registry, clusterable)

Core concepts:

NameServer : lightweight registry recording which topic resides on which broker (analogy: phone book).

Broker : actually stores and forwards messages (analogy: courier station).

Topic : logical message classification (analogy: courier category).

Tag : secondary label under a topic for consumer-side filtering (analogy: sub-category).

Consumer Group : a group of consumers sharing a topic (analogy: a team dividing work).

Two mental-model differences vs RabbitMQ:

No Exchange . Producers send directly to a topic using topic:tag syntax for simple filtering. Routing is simpler but less flexible: to route one event to five downstreams by different rules, RocketMQ needs five topics or five consumer groups, while RabbitMQ needs only one exchange. This is a limitation.

Retry and dead letter are built-in . On consumer exception, the broker auto-retries (default 16 times with increasing intervals), then moves the message to a dead-letter queue named %DLQ%consumerGroup. No manual dead-letter exchange config like RabbitMQ, no DefaultErrorHandler + dead-letter topic like Kafka. Value: less custom code, fewer production incidents.

Run a Stack with Docker Compose

Docker Compose for NameServer, Broker, and Dashboard:

services:
  namesrv:
    image: apache/rocketmq:5.3.1
    container_name: rmqnamesrv
    command: sh mqnamesrv
    ports:
      - "9876:9876"

  broker:
    image: apache/rocketmq:5.3.1
    container_name: rmqbroker
    command: sh mqbroker -n namesrv:9876 -c /home/rocketmq/conf/broker.conf
    depends_on:
      - namesrv
    ports:
      - "10911:10911"
      - "10909:10909"
    volumes:
      - ./broker.conf:/home/rocketmq/conf/broker.conf

  dashboard:
    image: apacherocketmq/rocketmq-dashboard:latest
    container_name: rmqdashboard
    depends_on:
      - namesrv
    ports:
      - "8180:8080"
    environment:
      - JAVA_OPTS=-Drocketmq.namesrv.addr=namesrv:9876

Key broker.conf settings:

brokerClusterName = DefaultCluster
brokerName = broker-a
brokerId = 0
fileReservedTime = 48
brokerRole = ASYNC_MASTER
flushDiskType = ASYNC_FLUSH
# Critical: tell clients the reachable broker address
brokerIP1 = 127.0.0.1
brokerIP1

is the most common local-debugging pitfall. Without it, NameServer returns the broker container's internal IP, causing client timeouts; the dashboard shows topics but sends fail. For local debugging use 127.0.0.1; for LAN use the host's real IP. After startup, visit http://localhost:8180 for topic view, message trace, and consumer lag.

Spring Boot Minimal Loop

Maven dependency:

<dependency>
  <groupId>org.apache.rocketmq</groupId>
  <artifactId>rocketmq-spring-boot-starter</artifactId>
  <version>2.3.1</version>
</dependency>

YAML config:

rocketmq:
  name-server: 127.0.0.1:9876
  producer:
    group: order-producer-group  # required
    send-message-timeout: 3000

Producer:

@Service
public class OrderProducer {
  @Autowired
  private RocketMQTemplate rocketMQTemplate;

  public void send(OrderDto order) {
    Message<OrderDto> message = MessageBuilder.withPayload(order)
      .setHeader(RocketMQHeaders.KEYS, order.getOrderNo())  // business unique key
      .build();
    SendResult result = rocketMQTemplate.syncSend("order-topic:order-create", message);
    if (result.getSendStatus() != SendStatus.SEND_OK) {
      throw new RuntimeException("Send failed: " + result.getSendStatus());
    }
  }
}

Note the "topic:tag" syntax — RocketMQ-specific, not a string concatenation error.

Consumer:

@Component
@RocketMQMessageListener(
  topic = "order-topic",
  consumerGroup = "order-consumer-group",
  selectorExpression = "order-create"  // consume only this tag
)
public class OrderCreateConsumer implements RocketMQListener<OrderDto> {
  @Override
  public void onMessage(OrderDto order) {
    // business logic
    // throwing exception = triggers broker built-in retry (default 16 times), then DLQ
  }
}

No try-catch needed to decide retry; throwing an exception triggers retry. Caveat: non-retryable errors (e.g., invalid parameters) will also be retried 16 times — handle them in code without throwing.

Delayed Messages: One API for "30 Minutes Unpaid"

RocketMQ 5.x supports arbitrary delay via timestamp (milliseconds):

// 5.x: arbitrary duration, specify delivery timestamp (ms)
long deliverAt = System.currentTimeMillis() + 30 * 60 * 1000L;
rocketMQTemplate.syncSendDeliverTimeMills("order-topic:order-timeout", message, deliverAt);

// 4.x: only 18 fixed levels (1s, 5s, 10s, 30s, 1m ... 2h), level 14 = 10 minutes
rocketMQTemplate.syncSend("order-topic:order-timeout", message, 3000, 14);

Consumer:

@RocketMQMessageListener(topic = "order-topic", consumerGroup = "timeout-group",
  selectorExpression = "order-timeout")
public class OrderTimeoutConsumer implements RocketMQListener<OrderDto> {
  @Override
  public void onMessage(OrderDto order) {
    // 30 min later: check current status, cancel only if still UNPAID
    Order db = orderMapper.selectById(order.getId());
    if (db != null && db.getStatus() == OrderStatus.UNPAID) {
      // cancel order, rollback inventory
    }
    // already paid/cancelled -> skip — natural idempotency
  }
}

The re-check is critical: the user may have paid seconds before the delayed message arrives. This re-check also serves as idempotency protection. Comparison: RabbitMQ requires TTL + dead-letter exchange and worries about head-of-line blocking; Kafka has no delayed messages at all. This section alone justifies choosing RocketMQ.

Transaction Messages: Half Message + Check-back

Solves: local transaction succeeds but message send fails, or message sent but local transaction rolls back. Both must succeed or both fail.

Flow (high-frequency interview topic):

1. Producer sends "half message" to Broker — invisible to consumers
2. Broker acks, then Producer executes local transaction (e.g., order persist)
3. Local transaction success -> commit half message (consumers see it)
   Local transaction failure -> rollback half message (discard)
4. If Producer crashes after transaction but before commit/rollback —
   Broker periodically checks back: "Did your local transaction succeed?"

Code in three steps:

// 1. Send half message (third arg passed to listener)
rocketMQTemplate.sendMessageInTransaction("pay-topic:pay-success", message, orderId);
// 2. Local transaction + check-back
@Component
@RocketMQTransactionListener
public class PayTxListener implements RocketMQLocalTransactionListener {
  @Autowired
  private OrderMapper orderMapper;

  @Override
  public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object arg) {
    Long orderId = (Long) arg;
    try {
      orderMapper.updateStatus(orderId, OrderStatus.PAID);
      return RocketMQLocalTransactionState.COMMIT;
    } catch (Exception e) {
      return RocketMQLocalTransactionState.ROLLBACK;
    }
  }

  @Override
  public RocketMQLocalTransactionState checkLocalTransaction(Message msg) {
    // check-back: reverse-query using local transaction result
    Long orderId = Long.valueOf((String) msg.getHeaders().get(RocketMQKeys.KEYS));
    Order order = orderMapper.selectById(orderId);
    return (order != null && order.getStatus() == OrderStatus.PAID)
      ? RocketMQLocalTransactionState.COMMIT
      : RocketMQLocalTransactionState.ROLLBACK;
  }
}

Check-back logic must be able to reverse-query. If it returns UNKNOWN, the broker retries then discards the message — the most common transaction-message failure, usually because the local transaction left no traceable record (e.g., only wrote to cache).

Critical clarification: Transaction messages only guarantee atomicity between the local transaction and message send, not downstream consumption success. Downstream failures are handled by retry + dead letter; duplicates by idempotency. Assuming transaction messages solve the entire distributed transaction is a fifth anti-pattern.

Seven Pitfalls

Missing brokerIP1 : dashboard shows topics but sends time out. Fix: set brokerIP1 to host-reachable IP.

Producer group not configured : startup error producerGroup can not be empty. Fix: set rocketmq.producer.group.

Duplicate consumer group : two projects use same consumerGroup, messages stolen. Fix: unique group per business.

Transaction check-back finds nothing : returns UNKNOWN, message discarded after retries. Fix: check-back must query local table via keys.

4.x arbitrary delay : non-standard level ignored. Fix: 4.x only has 18 fixed levels; need 5.x for arbitrary delay.

Message ordering : same-order messages processed concurrently. Fix: syncSendOrderly + select queue by business key.

Duplicate consumption : payment callback processed twice. Fix: built-in retry causes duplicates; must implement idempotency.

Checklist

Architecture: NameServer (registry) + Broker (storage), no Exchange concept.

Minimal loop: syncSend("topic:tag", message) + @RocketMQMessageListener.

Delayed messages: 5.x syncSendDeliverTimeMills arbitrary duration; 4.x only 18 fixed levels.

Delayed cancellation must re-query status , never trust message content alone.

Transaction messages: half message (invisible) -> local transaction -> commit/rollback -> crash triggers broker check-back.

Retry & dead letter built-in: throw exception retries 16 times, then goes to %DLQ%group; non-retryable errors must be filtered in code.

Local debugging two must-configs: brokerIP1 and unique consumerGroup naming.

One-liner: RocketMQ sells business semantics, not performance. If your requirements don't include "delayed" and "transaction", it may not be more cost-effective than RabbitMQ.

About this article

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

Spring BootMessage QueueRocketMQdistributed transactionsDocker Composedelayed messagesdead letter queuetransaction messages

Discussion 0

Questions, practical examples and thoughtful responses.

Open full discussion