Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 36 ยท MQTT and Messaging

MQTT Retained Messages, Last Will and Sessions

Learn the three MQTT features that make IoT reliable: retained messages for last known state, Last Will for offline detection, and persistent sessions.

Plain publish/subscribe has a weakness: a subscriber only sees what is published while it is connected. A dashboard opened at noon sees nothing until the next reading arrives. A sensor that loses power vanishes without telling anyone. A phone that goes through a tunnel misses commands. MQTT has three features to close these gaps: retained messages, Last Will and Testament and persistent sessions.

All three assume you know topics and QoS.

Retained messages

If a publisher sets the retain flag, the broker stores that message as the topic's last known value. Every new subscriber to a matching filter immediately receives it. Only one message is kept per topic; a newer retained message replaces it. To clear it, publish an empty payload with retain on.

Retained messages are ideal for state: "the door is closed", "firmware version 2.3", "heater is ON". They are wrong for events such as "button pressed", because a later subscriber would think the button was just pressed.

Node.js Retained state for late subscribers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The late dashboard got the current state at once but never saw the knock. Retained messages are the reason most IoT dashboards show something the moment they load.

Last Will and Testament

How does the rest of the system know that a device is dead? The device cannot say so after the fact. Instead, at connection time it hands the broker a will: a topic, a payload, a QoS and a retain flag. If the connection ends without a clean DISCONNECT (power loss, crash, network failure, keep-alive timeout), the broker publishes the will on the device's behalf.

A common pattern combines will and retain into an online/offline status:

  1. On connect, the device publishes online to plant/pump-14/status with retain.
  2. In its will it registers the payload offline, also retained, for the same topic.
  3. A clean shutdown publishes offline itself and disconnects normally.

Anyone subscribing to the status topic gets the current truth, whenever they arrive.

Node.js Last Will on a crashed device

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The broker detects a dead connection through the keep-alive: the client promises to send something (a PINGREQ if it has no data) at least every N seconds, and the broker declares it gone after about 1.5 times that interval. A shorter keep-alive finds failures sooner but costs battery.

Persistent sessions

By default a client connects with a clean session (MQTT 3.1.1) or session expiry of zero (MQTT 5): when it disconnects, the broker forgets its subscriptions and pending messages. With a persistent session (clean session off, or a session expiry interval in MQTT 5), the broker keeps:

  • the client's subscriptions,
  • QoS 1 and 2 messages that arrived while the client was offline,
  • in-flight acknowledgments that were not finished.

The session is identified by the client ID, so the client must reconnect with the same one. QoS 0 messages are not queued.

Node.js A persistent session queues QoS 1 messages

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Choosing among them

Need Feature
New subscriber must see the latest state Retained message
Others must learn that a device died Last Will (often retained)
A battery device sleeps and must not miss commands Persistent session with QoS 1
Forget everything on reconnect Clean session

Cautions: retained messages stay until cleared, so stale data from decommissioned devices accumulates; clear the topic or use MQTT 5 message expiry. Persistent sessions consume broker memory for clients that never return, so brokers limit queue sizes and expire sessions.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How many retained messages does a broker keep for one topic?

    A new retained message replaces the old one. Only the last known value is stored.
  2. 2. When does the broker publish a device's Last Will?

    An unclean loss of connection (crash, power cut, timeout) triggers the will; a clean DISCONNECT discards it.
  3. 3. How do you delete a retained message?

    An empty retained payload clears the stored message for that topic.
  4. 4. A sleeping device must receive commands sent while it is offline. What is required?

    The broker queues QoS 1 and 2 messages for a persistent session identified by client ID.

Summary

  • Retained messages store a topic's last value for future subscribers; use them for state, not events; an empty retained payload clears it.
  • Last Will is a message the broker sends if a client vanishes uncleanly; combined with retain it gives online/offline status.
  • Persistent sessions keep subscriptions and queue QoS 1/2 messages for an offline client with the same ID.
  • Keep-alive controls how fast a dead client is detected.

Next: Build a Toy MQTT Broker over TCP