Although the publish-subscribe model fully decouples the publisher of the message from the subscriber, there is also an implicit problem that the subscriber cannot actively request the message from the publisher, and when the subscriber receives the message depends entirely on the publisher. This is inconvenient in some scenarios. For example, when a device periodically publishes its own GPS coordinates, it may take a few seconds for a subscriber to receive data from initiation of a subscription for the first time, or it may take ten minutes or more, which is not friendly. Therefore, MQTT introduces the retained message.
When the server receives a PUBLISH packet with a Retain flag of 1, it will conduct the following operations:
Whenever a subscriber establishes a subscription, the server will check if there is a retained message that matches the subscription, and if the retained message exists, it immediately forwards it to the subscriber. When a retained message is forwarded to the subscriber in this case, its Retain flag must remain at 1. Compared to MQTT v3.1.1, it makes a more detailed division of whether to send a retained message when the subscription is established in MQTT v5.0 , and provides a Retain Handling field in the subscription option. For example, some clients may only want to receive a retained message when they subscribe for the first time, or they may not want to receive a retained message when the subscription is established, which can be adjusted by the Retain Handling option.
Although retained message is stored in the server, it is not part of the session. That is to say, even if the session that published the retained message is terminated, the retained message will not be deleted. There are only two ways to delete a retained message:
With retained messages, new subscribers can get the most recent status immediately, without waiting for unpredictable times, which is very important in many scenarios.