Retained messages
A retained message is the last known value of a topic, kept by the broker. Any client that subscribes later receives it immediately, instead of waiting for the next publish.
How it works
- A client publishes with the retain flag set, for example
{"state":"running"}toacme/istanbul/assembly/line1/cnc-01/status. - The broker delivers it to current subscribers as usual, and stores it as the topic's retained message, replacing the previous one.
- A client that subscribes later (with a filter that matches the topic, wildcards included) receives the stored message at once, with the retain flag set.
There is at most one retained message per topic: the latest.
Use it for state, not for streams
| Good fit | Not a good fit |
|---|---|
Device status: online / offline, running / stopped | Every telemetry reading |
| Current configuration and set points | Events and alarms that must not be replayed |
| Last known value for dashboards that open later | Commands (a new subscriber would run an old command) |
A dashboard or digital twin that opens later shows the current state immediately when status topics are retained.
Publish and clear
bash
# Publish a retained status
mosquitto_pub -h broker.connectmq.com -p 8883 --capath /etc/ssl/certs \
-i "$CMQ_CLIENT_ID"_cli -u "$CMQ_USERNAME" -P "$CMQ_PASSWORD" \
-t acme/istanbul/assembly/line1/cnc-01/status -m '{"state":"running"}' -r -q 1
# Clear it: an empty retained message
mosquitto_pub ... -t acme/istanbul/assembly/line1/cnc-01/status -n -r -q 1In the console, tick Publish as retained on the topic page. Delete topic removes a topic's retained message as well.
Limits on ConnectMQ
| Free | Basic | Scale | |
|---|---|---|---|
| Topics with a retained message | 100 | 1,000 | 10,000 |
- When the limit is reached, a retained publish to a new topic is refused (0x97 Quota exceeded for QoS 1/2). Updating a topic that already has a retained message is always allowed.
- Clearing a retained message frees its slot.
- Publishing exactly the same retained payload to the same topic again within a few seconds is accepted but ignored, which protects against devices that resend their status in a loop.
- Retained messages are part of the broker's live state. Publish your status again when a device reconnects, so the retained value is always current.
Retained messages and Last Will
Combine both for reliable online/offline status: publish online retained after connecting, and register offline as a retained Last Will. The topic then always shows the truth, even for subscribers that join later.
Related
- QoS and Last Will
- Unified Namespace: retained state as the current picture of the plant