Retained messages

By default, after a message is published to a topic and is received by the subscribers, the message is discarded. However, a publisher can specify that a copy of the message is retained so that it is sent to future subscribers of the topic.

Deleting messages after they are sent to the subscribers is suitable for event information, but it is not always suitable for state information. By retaining a message, new subscribers do not have to wait for information to be published again before they receive initial state information. For example, a subscriber with a subscription to a stock price can immediately receive a retained message that contains the current price. Without a retained message, the subscriber must wait for the stock price to change before any information about the stock price is received.

There are times when you might not want to retain messages:
  • If all subscriptions to a topic are made before any messages are published, and you do not expect, or do not allow, new subscriptions, you do not need to retain messages. The messages that are published are delivered to all subscribers the first time that they are published.
  • If messages are published frequently, such as every second, a new subscriber, or a subscriber that is recovering from a failure, receives the current state almost immediately. Therefore, retained messages are not necessary.
  • If large messages are published, storing the retained messages uses a large amount of storage space. Therefore, you might not want to retain large messages.

When a retained message is published to a topic, a flag is set by the publishing application to indicate that the message is a retained message. IBM® IoT MessageSight immediately delivers the message to existing subscribers of the topic. For these messages, the retain flag is not set. If there is already a retained message stored for the topic, IBM IoT MessageSight deletes the existing message, and stores a copy of the new message for future subscriptions. When applications subscribe to the topic after the message is published, IBM IoT MessageSight delivers the message with the retain flag set. Therefore, the subscribing application is aware that the message is not a newly published message. For more information about setting the flags in MQTT and JMS applications, see Developing retained message applications.

Retained messages can be received from or forwarded to IBM MQ. For more information, see MQ Connectivity retained messages.