MQTT – Retained Messages

With MQTT protocol if a client publish a message there has no guarantee (instead of message QoS level) that the subscribing client has got the message. Normally, if a message is subscribed and no client is subscribed to that topic the message is simply discarded by the broker.

If you want to make sure that the message is important to the new client subscribed to that topic (even later) you can set a message “Retained” flag to be true. This is useful if you have a new client connected to the broker and want to make sure that client got the last message on that topic (for example a sensor last measurement, or any other client last status message). This will prevent new connected devices to wait for every other client to send the next status messages and receive the last messages from the automatically.

To send a retained message is pretty easy. All you need to do is to set the message “is Retained” status to TRUE. Tipically any client library make it easy to set a client published message to be reatined by the broker.

If you want to modify the retained message all you need to do is to send a new retained message to that topic with the new message payload. In this case the broker owerwrite the retained message to the new payload value.

If you want to delete a retained message from a topic all you need to do is to send a retained message with zero byte of payload to the topic where you want to delete the retained message.