MQTT/Staying connected/Last will

Last will

Pull the plug on a sensor and its phone goes on showing the last reading, looking perfectly normal. A last will is a message the device leaves with the broker to be posted for it if it vanishes.

A sensor that loses power says nothing. The broker notices after one and a half keepalives and closes the connection, but the phone is not subscribed to the connection: it is subscribed to the temperature, and it goes on showing 21.4 °C from four hours ago, which looks like any other reading.

The will

When a device connects, it can give the broker a last will: a topic, a message, a QoS, and whether to retain it. For example home/kitchen/status, offline, retained. The broker holds on to it.

If the connection ends without a proper goodbye — the keepalive runs out, the network fails, the connection is simply closed — the broker posts the will for the device. Everything subscribed to home/kitchen/status sees offline.

A sealed envelope with an orange wax seal alone on a counter under a lamp
The will waits, sealed, at the counter, and is opened only if the device vanishes.Generated illustration

Online over the top

Retain the will, so that a dashboard that opens later sees offline too. Then, when the device connects again, its first message is online to the same topic, also retained, which replaces it. The status topic now always holds the truth, for anyone who looks.

A proper goodbye

A device that disconnects on purpose sends DISCONNECT, and the broker throws the will away unposted. So a device that is switching itself off — going into deep sleep, say — should post offline itself first, if the dashboard is to know.

MQTT 5 changed two things: a device can ask for its will to be posted after a delay, so a quick reconnect goes unnoticed, and it can ask for the will to be posted even when it does disconnect properly.

Common mistakes

  • A will that is not retained. Only the phones open at that moment see it.
  • Forgetting online. The retained offline stays after the device is back, until something replaces it.
  • Expecting the will at once. It waits for the keepalive to run out: with a 15-second keepalive, about 22 seconds.

Edit this page — content/fundamentals/mqtt/last-will.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 →