MQTT – LWAT, Last Will and Testament

MQTT protocol often used in network, where bandwith or signal is limited between the clients and the broker. These limitations can cause unexpected disconnections of clients from the network and the broker. It can cause trouble if we rely on the messages in our application and can not tell if the client is disconnected. There are several good practice to prevent unnoticed client disconnection:

  • Keep record of every last message time so we can recognize if there is a problem with the client or the connection.
  • Use automatic reconnect at the client and send a new status message to our application, so we can detect if there was a network outage.

What happens when there was an unexpected event of disconnection and the client can not reconnect. This is where the client’s LWAT (Last Will And Testament) message takes place.

LWAT is a special message defined by the client when connected to a broker. This message is like a normal message. We define a Topic (path), a message Payload, a QoS (Quality of Service) level and a Retained flag.
LWAT message send by the broker at the event of unexpected client disconnection. These events are:

  • The Broker detects a network failure
  • The Client failed to communicate between the defined Keep Alive Intervall
  • The Client failed to send the DISCONNECT package to the broker before the disconnection

Good practice of LWAT is to store the status of the client. Even the Client is disconnected by any failure the new status message send to the path (where every other client can check) with a message payload of “Offline”. In This case the other clients will know that the client is currently not online. If the message is retained that will tell every new connected client that the client host is not reachable currently.