DEV Community

Cover image for MQTT: Retained Messages | Part 8

Posted on • Originally published at

MQTT: Retained Messages | Part 8

In MQTT, the client that publishes a message has no guarantee that a subscribing client actually receives the message. The publishing client can only make sure that the message gets delivered safely to the broker. Basically, the same is true for a subscribing client. The client that connects and subscribes to topics has no guarantee on when the publishing client will publish a message in one of their topics of interest. It can take a few seconds, minutes, or hours for the publisher to send a new message in one of the subscribed topics. Until the next message is published, the subscribing client is totally in the dark about the current status of the topic. This situation is where retained messages come into play.

Retained Messages

A retained message is a normal MQTT message with the retained flag set to true. The broker stores the last retained message and the corresponding QoS for that topic. Each client that subscribes to a topic pattern that matches the topic of the retained message receives the retained message immediately after they subscribe. The broker stores only one retained message per topic.

If the subscribing client includes wildcards in the topic pattern they subscribe to, it receives a retained message even if the topic of the retained message is not an exact match. Here’s an example: Client A publishes a retained message to myhome/livingroom/temperature. Sometime later, client B subscribes to myhome/#. Client B receives the myhome/livingroom/temperature retained message directly after subscribing to myhome/#. Client B (the subscribing client) can see that the message is a retained message because the broker sends retained messages with the retained flag set to true. The client can decide how it wants to process the retained messages.

Retained messages help newly-subscribed clients get a status update immediately after they subscribe to a topic. The retained message eliminates the wait for the publishing clients to send the next update.

In other words, a retained message on a topic is the last known good value. The retained message doesn’t have to be the last value, but it must be the last message with the retained flag set to true.

It is important to understand that a retained message has nothing to do with persistent sessions. Once a retained message is stored by the broker, there’s only one way to remove it. Keep reading to find out how.

To learn how to send or delete a retained MQTT message, read this article and watch this video.

Get your copy of MQTT Essentials eBook to understand the protocol in detail without you having to read the entire specification.

Top comments (0)