Retained messages, in plain terms
A retained message is the broker’s memory of the last known value on a topic. When a new subscriber joins, the broker immediately sends that last value, even if the publisher is offline.
This is ideal for state topics: device status, configuration, or last known reading. It makes dashboards feel instant because you do not wait for the next publish.
When to use retained
Use retained messages for slow-changing state and “current value” facts. Examples include mode, availability, or the last temperature reported.
Avoid retaining high-frequency telemetry unless you really need it. It can be misleading to display a retained value that is already stale.
Clearing a retained value
To clear a retained message, publish an empty payload with the retained flag set. The broker then removes the retained value for that topic.
This is useful when a device is decommissioned or when a topic no longer represents valid state.
Last Will and Testament (LWT)
The Last Will is a message that the broker publishes on behalf of a client if it disconnects unexpectedly. It is a safety net that signals “this device vanished.”
LWT is essential for presence. Without it, downstream systems can’t distinguish “silent but alive” from “offline.”
Retained + LWT together
A common pattern is to publish a retained “online” state and set an LWT to publish “offline.” When a device connects, it publishes online (retained). If it drops, the broker publishes offline.
Subscribers then always have an accurate view of presence even when devices disconnect unpredictably.
Designing the topics
Keep retained state topics separate from event topics. State topics should be stable and reflect the current value, while event topics represent point-in-time events.
For example, `/devices/42/state` can be retained, while `/devices/42/events` should not be retained.
Operational pitfalls
Retained values can become stale if devices disappear. Use LWT to update the state or expire data on the consumer side.
Document which topics are retained. Otherwise, new subscribers may misinterpret retained data as live events.
