MQTT Retain Message: What It Is and How It Works
MQTT retain message is a special message that the broker saves and delivers immediately to any new subscriber of a topic. It ensures the latest message on that topic is always available, even if the subscriber connects after the message was originally sent.How It Works
Imagine you have a bulletin board where the latest weather update is always pinned. When someone new arrives, they see the current weather without waiting for a new update. In MQTT, a retain message works like that pinned note.
When a publisher sends a message with the retain flag set, the MQTT broker keeps that message stored. Any new client subscribing to that topic immediately receives this stored message, so they get the latest information right away.
This is useful because normally, MQTT only sends messages to clients that are connected at the time of publishing. Retain messages solve the problem of late subscribers missing important data.
Example
This example shows how to publish a retained message using the paho-mqtt Python client. The message "Hello, MQTT!" is retained on the topic home/greeting.
import paho.mqtt.client as mqtt broker = "test.mosquitto.org" client = mqtt.Client() client.connect(broker, 1883, 60) # Publish a retained message client.publish("home/greeting", "Hello, MQTT!", retain=True) client.disconnect()
When to Use
Use retained messages when you want new subscribers to get the latest important data immediately without waiting for the next update. Common use cases include:
- Device status updates (e.g., online/offline state)
- Configuration settings that should be known by all clients
- Last known sensor readings like temperature or humidity
This helps devices or apps start with the current state and avoid delays or missing critical info.
Key Points
- A retained message is stored by the broker and sent to new subscribers immediately.
- Only the last retained message per topic is saved.
- Retained messages help keep clients updated with the latest state.
- Use retain flag carefully to avoid sending outdated or irrelevant data.