MQTT/Sorting and keeping/Retained messages

Retained messages

A broker forgets a message once it has passed it on, so a phone that opens late shows a dash. Post with the retain flag and the broker keeps the last one for each topic, and hands it over the moment someone subscribes.

The broker passes a message to whoever is subscribed and then forgets it. A dashboard that opens a minute later has nothing to show until the sensor posts again — thirty seconds away, or an hour, depending on the sensor.

The retain flag

Post a message with retain set and the broker does two things: it delivers it as usual, and it keeps a copy for that topic. When anything subscribes to the topic later, the broker sends it the kept copy straight away, marked as a retained message so the reader can tell it is not new.

The broker keeps one retained message per topic. The next retained message on the same topic replaces it.

A post-office display window at night with one newspaper on show
Retain keeps the latest issue on show for whoever comes by later.Generated illustration

State, not events

Retain what something is: a temperature, whether a lamp is on, whether a device is online. A reader that arrives late should know it at once.

Do not retain what happened. A retained home/door/bell tells every phone that opens tomorrow that somebody is at the door. Commands are the same: a retained home/lamp/set = on is sent to the lamp every time the lamp reconnects, so a lamp that loses power at night switches itself on when the power comes back. The usual pattern is two topics: the lamp reports what it is doing on home/lamp/state, retained, and takes orders on home/lamp/set, not retained.

Deleting one

A retained message stays until it is replaced. To delete it, post a retained message with an empty payload to the same topic. The broker removes the kept copy and keeps nothing in its place.

Common mistakes

  • A retained message nobody can remember posting. It sits on the broker and greets every new subscriber. Post an empty retained message to clear it.
  • Retaining a command. The device obeys it again on every reconnect.
  • Thinking retain stores history. It keeps one message per topic, the last. A log of readings needs a program that subscribes and writes them down.

Edit this page — content/fundamentals/mqtt/retained-messages.mdx

Discuss this article

Ask about this page. The answer stays here, on the page it belongs to, for whoever hits the same wall next.

Browse Fundamentals on the forum →