In a regular IoT system built using MQTT protocol, the MQTT broker lively routes messages between clients. Once a client is disconnected, the broker grants the client’s last will, which looks like this:
In case of disconnection, publish this message on this topic
It’s an elementary explanation of the
lastWill parameter. At the same time, you have much to discover to understand what it is, why it’s used, and how it works. So, keep reading to get the answers to all these questions about MQTT Last Will and Testament.
What is MQTT Last Will?
Let’s unpack what underlies the last will and testament (LWT) term first. ‘Last will and testament’ is a legal document that determines how the person’s possessions will be distributed in the event of death. ‘Will and testament’ is the full legal phrase to describe the document, and ‘last’ means that it was the final one. ‘Will’ on its own is commonly used in non-legal speech to mean the same document. The full phrase Last Will and Testament was also used in the MQTT context because otherwise “will” on its own could be confusing.
lastWill is a set of parameters meant to inform the subscribers of a particular topic about the abnormal disconnection of a specific client. The client cannot send a message when it disconnects unexpectedly, so it asks the broker to send it on its behalf.
Note: According to MQTT 5.0 specification and 3.1.1 as well, this set of parameters is just called Will: Will Message, Will Topic, Will QoS, and Will Retain.
Once the broker detects a connection break, it publishes a predefined message, so-called lastWillMessage, to the predefined topic, s.c. lastWillTopic, so that the subscribers are informed about the disconnection.
MQTT Last Will parameters
lastWillMessage– a message that will be sent to the subscribers of a particular topic in case of a client’s reconnection.
lastWillTopic– an MQTT topic to publish the Last Will message.
lastWillRetain– a boolean value indicating whether the Last Will message is to be retained or not. If retained, the Last Will message will be sent to all the new subscribers of the
lastWillTopic. If not, the new subscribers won’t receive the Last Will message.
lastWillQoS– an MQTT Quality of Service level to use when sending the Last Will message.
What is MQTT Last Will and Testament for?
The main idea of MQTT Last Will, also known as MQTT Last Will and Testament or LWT, is to provide an appropriate way to notify clients of unexpected disconnections.
The Last Will message sent to subscribers indicates that the client’s connection was broken unexpectedly, i.e. the client has not sent an MQTT DISCONNECT message. This information allows you to respond accordingly to the requirements or needs of your IoT system. We’re going to observe the value of MQTT Last Will in the example below. But first, let’s see how it works.
How MQTT Last Will works
MQTT Last Will basically has two milestones:
- Last Will Message configuration when connecting a client to the MQTT broker.
- The actual sending of the Will Message when the client broke off.
MQTT Last Will is set at the CONNECT request
Everything starts with establishing an MQTT connection between a client and an MQTT broker. As you know, the client sends a CONNECT packet that contains the three required fields:
keepAlive. The optional fields include username, password, and a set of MQTT Last Will Testament values:
lastWillQos. Check out our MQTT connection guide to refresh your knowledge about this. In addition, feel free to read our MQTT packet tutorial to learn about its types, format, size, etc. And here is what the CONNECT message may look like:
clientID "sensor-2" cleanSession true keepAlive 120
Optional information: username "mark" password "3ri82hp84r" lastWillTopic "myhome/sensor” lastWillQos 2 lastWillMessage "sensor lost" lastWillRetain false
In the context of MQTT Last Will, the client asks the MQTT broker about the following:
If you detect that the connection with me is broken, send the message “
sensor lost“ once only (QoS 2) to all the subscribers of the “
myhome/sensor” topic. And do not retain the Last Will message, please. The latter means that new subscribers to the “
myhome/sensor” topic won’t receive the message.
The MQTT broker shall respond with a CONNACK packet to approve the connection.
A CONNECT packet contains the
LastWill Flag boolean value, which you do not see. If the
lastWillMessage parameter is specified, then
LastWill Flag is TRUE. Correspondingly, the absence of the MQTT Last Will message in the CONNECT request switches the
LastWill Flag to FALSE.
When does the MQTT broker send the Last Will message?
The connection between the MQTT broker and the client is established, and they start their conversation.
We are sure that you use the world’s fastest MQTT broker, Pro Edition for Eclipse Mosquitto that can provide you with a reliable and secure service. It implements the open standards of the Mosquitto broker, which is open-source, and complements it with a bunch of actionable features in terms of optimized performance, high availability, and others. Sign up for Mosquitto Pro’s free 14-day trial to check it out.
The Last Will message will be sent in one of the following cases:
- The client has not sent any packet within the defined MQTT Keep Alive interval, time interval during which a client must send at least one packet to the broker. The MQTT broker waits for one and a half keepAlive periods before disconnecting the client and then sending the LastWillMessage. In our case, the set keepAlive interval is 120 seconds, so the MQTT broker will wait 180 seconds.
- The client ended the conversation without first sending a DISCONNECT packet.
- The MQTT broker ended the conversation without first receiving a DISCONNECT packet.
- The MQTT broker detected a network failure or an input/output error.
- A client using MQTT v5.0 sent a DISCONNECT packet and set the return code to “disconnect-with-will-message”.
MQTT Last Will example
The logic of MQTT Last Will and Testament is clear from the technical perspective. However, you may still be unsure about the application of MQTT Last Will in real life. So, let’s take a look at the following example.
We have a sensor, the data from which is infrequently sent to a smartphone app. When connecting the sensor to the MQTT broker, Pro Edition for Mosquitto, of course 😉, we specified the LWT message – ‘sensor went offline’.
During normal operation, the sensor maintains the connection to the MQTT broker by sending PUSH messages with its readings. These messages can be interspersed with periodic keepAlive messages (PINGREQ), if necessary, to notify the MQTT broker not to disconnect the sensor.
In case of any failure on the sensor’s side, it won’t send messages to the MQTT broker, which will eventually disconnect it. Since we’ve set the MQTT Last Will message, the MQTT broker will publish ‘sensor went offline’, so our smartphone app, which is a client subscribed to the Last Will topic, can get the notification.
If we have not set the Last Will message, the MQTT broker would have closed the connection without any notification. We wouldn’t even know that the sensor went offline and ceased sending data. This could be very harmful if the sensor’s reading were crucial.
Why you should use MQTT Last Will and Testament
Do you still have any more doubts about the value of the MQTT Last Will message? This feature allows you to keep clients of your IoT system informed of any unexpected disconnections. It will be useful in many scenarios and it’s even difficult to think of a scenario when you need to avoid MQTT Last Will. So, keep your Will Flags true by setting LWT messages when connecting your devices. This will ensure that you do not miss any fell-offs.
About the author
Zakhar is a content manager at Coupler.io, tasked with the important role of ensuring that readers love and enjoy the content created by the company. With over 5 years of experience as a skilled writer in the SaaS industry, Zakhar can craft texts that resonate with the audience's queries.
Despite not being a developer, Zakhar sees this as an advantage in effectively explaining complex technical concepts to the readers using simple and accessible language. Zakhar's content expertise spans various areas, such as working with REST APIs, data automation, reporting and analytics, MQTT, email testing, and more.