Help Center/ Distributed Message Service for RabbitMQ/ Best Practices/ Deduplicating Messages Through Message Idempotence
Updated on 2024-10-16 GMT+08:00

Deduplicating Messages Through Message Idempotence

Overview

In RabbitMQ service processes, an idempotent message process refers to a situation where a message is re-sent and consumed for multiple times and each consumption result is the same, having no negative effects on services. Idempotent messages ensure consistency in the final processing results. Services are not affected no matter how many times a message is re-sent.

Take paying as an example. Assume that a user selects a product, makes payment, and receives multiple bills due to unstable Internet connection. The bills are all paid. However, the billing should take place only once and the merchant should generate only one order placement. In this case, idempotent messages can be used to avoid the repetition.

In actual applications, messages are re-sent because of intermittent network disconnections and client faults during message production or consumption. Message repetition can be classified into two scenarios.

  • A producer repeatedly sends a message:

    If a producer successfully sends a message to the server but does not receive a successful response due to an intermittent network disconnection, the producer determines that the message failed to be sent and tries resending the message. In this case, the server receives two messages of the same content. Consumers consume two messages of the same content.

  • A consumer repeatedly consumes a message:

    A message is successfully delivered to a consumer and processed. If the server does not receive a response from the consumer due to an intermittent network disconnection, the server determines that the message failed to be delivered. To ensure that the message is consumed at least once, the server retries delivering the message. As a result, the consumer consumes two messages of the same content.

Implementation

A globally unique ID can be used to determine whether a message is consumed repeatedly. If yes, the consumption result is returned. If no, consume the message and record the global ID.

  • Producers set a unique ID for each message. Sample code is as follows:
    // The message is persisted with a globally unique ID which is randomly generated.
    AMQP.BasicProperties.Builder builder = new AMQP.BasicProperties().builder();
    builder.deliveryMode(2);
    builder.messageId(UUID.randomUUID().toString());
    
    // The custom message.
    String message = "message content";
    
    // Produce messages. Set exchangeName and routingKey to the actual values.
    channel.basicPublish("exchangeName", "routingKey", false, builder.build(), message.getBytes(StandardCharsets.UTF_8));
    String messageId = builder.build().getMessageId();
    System.out.println("messageID: " + messageId);
    System.out.println("Send message success!");
    // Close the channel.
    channel.close();
    // Close the connection.
    connection.close();
  • Consumers deduplicate messages based on their IDs. Sample code is as follows:
    // Create a table with message ID as the primary key. Unique primary keys of databases can be used to process RabbitMQ idempotence.
    // Before consumption, query the message from the database. If the message exists, it is consumed. Otherwise, consume it.
    //queueName: Use the actual queue name.
    channel.basicConsume("queueName", false, new DefaultConsumer(channel) {
        @Override
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                //Obtain the message ID and check whether it is null.
                String messageId = properties.getMessageId();
                if (StringUtils.isBlank(messageId)){
                    logger.info("messageId is null");
                    return;
                }
                // Query the database by primary key "message ID". If records exist, the message is consumed. Otherwise, consume the message and write it into the database.
                // Database querying logic ...
                //todo
    
                // If no record exists, consume the message. Or notify that the message is consumed.
                if (null == "{Found in the database}"){
                    // Obtain the message.
                    String message = new String(body,StandardCharsets.UTF_8);
                    // Manual response.
                    channel.basicAck(envelope.getDeliveryTag(),false);
                    logger.info("[x] received message: "  + message + "," + "messageId:" + messageId);
    
                    // Save the message to the database table, indicating that the message has been consumed.
                    // The database input operation ...
                    //todo
                } else {
                    // If the message is consumed, skip it.
                    logger.error("The message is already consumed.");
                }
        }
    });