top of page

What is Last Will Message?

Oct 26
11 min read

Updated: Oct 27

MQTT broker forwarding a stored Last Will message after an IoT client disconnects unexpectedly.

 

A Last Will Message is a predefined MQTT publication that a client registers with a broker when it connects. If the connection later ends under conditions that require the Will, the broker publishes that message on the client’s behalf. The failing client does not need to send a final warning at the moment of failure.

 

For example, a greenhouse gateway can register an offline status for home/gateway-01/status. While connected, it can separately publish an online status. If its MQTT connection subsequently disappears without a normal shutdown, the broker can publish the registered Will. The resulting message is evidence about that connection under the configured rules, not proof that the physical device has stopped working.

 

Last Will and Testament, often shortened to LWT, is the broader name for this MQTT feature. Its useful details are who registers the message, who publishes it, when publication becomes due and what subscribers can infer. Retention, delivery quality and MQTT 5 delay settings affect different parts of that process.

 

How is a Last Will Message registered?

 

The client supplies its Will information in CONNECT, before the failure it wants other applications to notice. The broker stores the Will as part of the relevant MQTT session state. Registering it does not immediately publish the payload to subscribers, and it does not automatically create an online status for the device.

 

The MQTT guide explains the wider connection and publish/subscribe model. A Will uses that same messaging infrastructure, but its eventual publication is triggered by the connection and session rules rather than by a normal publish call from the failed client.

 

Will setting

What it determines

Will Topic

The concrete topic name on which the broker will publish the message.

Will Payload

The application bytes registered in advance, such as an offline status.

Will QoS

The protocol delivery level used for the Will publication.

Will Retain

Whether publication also updates the retained latest value for that topic.

MQTT 5 Will properties

Additional controls, including Will Delay and Message Expiry, where supported.

 

Choose a concrete topic name, rather than a subscription filter containing wildcards. The Topic guide separates publication names from filters and permissions. A name such as home/gateway-01/status is an application convention; MQTT does not assign a universal meaning to the word status or the payload offline.

 

In Eclipse Paho Python, will_set must be called before connect to affect the connection being established. Changing a local object after the connection has started should not be treated as an update already accepted by the broker. Plan the configuration and reconnection behaviour using the client’s supported API.

 

Who actually publishes the message after a failure?

 

The broker publishes the Will. That is the feature’s central advantage: a disconnected gateway does not need a working network path to send its last message. The message was already supplied while the connection could communicate, so the broker can act when it detects the relevant connection ending.

 

  1. Configure the Will Topic, payload, QoS and retention behaviour before connecting.

  2. Establish the MQTT connection so that the broker receives the Will information.

  3. Publish ordinary application data and any deliberate online status separately.

  4. If the connection ends in a way that requires a Will, the broker applies the applicable timing and session rules.

  5. The broker publishes the stored message to qualifying destinations under matching subscriptions, permissions and delivery settings.

 

It is misleading to describe this as a guaranteed broadcast to every observer. A consumer still needs an applicable subscription and permission to receive the publication. Its delivery also depends on the relevant MQTT state and QoS. A dashboard that is offline or subscribed to another topic cannot be assumed to have received it.

 

The message broker guide distinguishes acceptance, routing, delivery and completed application work. Those boundaries apply to a Will too. Receiving an offline message does not prove that an alert was displayed, an operator acted or an automated recovery completed.

 

Which disconnections cause a Will to be published?

 

The MQTT rules cover connection endings such as detected network errors, failure to communicate within Keep Alive and a connection closing without the normal client DISCONNECT that removes the Will. The broker may also close a connection itself. The details need the protocol version and, for MQTT 5, the disconnect reason and session settings.

 

A loss can take time to detect. An explicit socket closure may be visible promptly, whereas an otherwise silent path failure can leave an endpoint waiting for evidence. The Keep Alive MQTT guide explains the client’s sending obligation, the broker’s 1.5-times silence limit and the separate missing-PINGRESP rule.

 

MQTT 3.1.1 normally removes the pending Will when the client sends DISCONNECT. MQTT 5 makes a crucial distinction: Normal disconnection, reason code 0x00, removes the Will, while reason code 0x04 is explicitly Disconnect with Will Message. A general statement that “every DISCONNECT suppresses the Will” would therefore be wrong for MQTT 5.

 

Connection event

Will implication

Ordinary normal client shutdown

The normal DISCONNECT removes the pending Will.

Client connection vanishes without normal DISCONNECT

The broker applies Will publication rules after detecting the ending.

MQTT 5 DISCONNECT reason 0x04

The client requests disconnection with its Will, subject to relevant timing rules.

Broker shutdown or failure

Will publication may be deferred until a subsequent restart; an immediate alert is not assured.

 

The MQTT 5.0 standard specifies these distinctions and permits deferred Will publication after a server failure. A monitoring design should therefore not depend on the failed broker instantly announcing its own loss to every consumer through that same broker.

 

What is Last Will Message infographic explaining the mechanism, key stages and practical limits.

 

How do retained online and offline statuses work?

 

A common pattern combines a retained online publication with a retained offline Will on the same topic. The retained value and the registered Will are different things. One is the latest published value available to a later matching subscriber; the other is a message waiting for a qualifying connection ending.

 

When the gateway connects successfully, the application publishes online with retention enabled. If its connection later ends abnormally and the broker publishes the retained offline Will, that publication replaces the retained online value. A matching subscriber that subscribes afterwards can then obtain the retained offline status, subject to the broker and subscription rules.

 

Stage

Stored or delivered state

CONNECT registers offline Will

Pending Will exists; no offline publication solely because it was registered.

Client publishes retained online

The topic’s retained latest value becomes online.

Broker publishes retained offline Will

Current qualifying subscribers can receive it; the retained value becomes offline.

A subscriber joins afterwards

It can receive the retained offline value rather than a full history of earlier status changes.

 

A non-retained Will can notify current recipients without creating a retained status for a future subscription. Retention is not an event archive. It does not automatically preserve every transition, and an application that needs historical evidence must choose and verify an appropriate storage design.

 

There is a practical shutdown trap. A normal DISCONNECT removes the Will, but it does not automatically replace a previously published retained online status. If a planned shutdown should leave an offline value, the application should publish the appropriate status itself, verify the required completion and then disconnect normally. That is an ordinary publication, not a Will firing.

 

A retained status is also not necessarily fresh physical truth. A connection can be broken before its loss is detected, a broker can be unavailable, or an application can publish misleading state. Include an appropriate observation time or generation identifier where the design needs it, and distinguish observed connectivity from the device’s actual work.

 

What did our local Will experiment show?

 

We tested MQTT 3.1.1 with aMQTT 0.12.1 and Eclipse Paho Python 2.1.0 on Python 3.12.14. Four isolated broker instances listened only on 127.0.0.1 using ephemeral ports, anonymous local access, clean sessions and QoS 1. The test closed a client socket without sending MQTT DISCONNECT; it did not physically cut power or interrupt a broadband service.

 

The final experiment passed 35 checks. In the retained case, the current observer received online from the client, then will-offline from the broker after the abrupt closure. The existing observer saw a normal live delivery, while a later subscription received will-offline with its retained flag set. This directly illustrates the difference between registering a Will, publishing it and retrieving the retained latest value.

 

For the non-retained case, the current observer received will-offline, while the later subscription received no message during a 750-millisecond observation window. That is a bounded negative result, not proof that a message could never appear under every future condition. In the normal-disconnection case, no Will was observed during the same window and a later subscription still received the retained online value.

 

In the fourth case, the client deliberately published retained manual-offline before disconnecting normally. The current observer received that publication, no additional Will was observed in the bounded window, and a later subscription received the retained manual-offline value. Each broker was shut down and its listener confirmed closed.

 

Our first shared-broker test exposed an implementation-specific retained-delivery anomaly when a new observer connected after another case had populated retained state. We recorded that failure and used a fresh broker for each final case. All final observers established their connections before retained values existed; the “later observer” subscribed later while already connected. These results do not validate a newly established post-failure connection or the broker’s general retained-message correctness.

 

We did not test MQTT 5 Will Delay, Message Expiry, broker restart, authorisation, TLS, a real access-line failure or a delivery service-level guarantee. The script, results and development notes are retained with the evidence. They support the specific local behaviours described here, while the MQTT 5 explanations below are grounded in the protocol standard.

 

How does MQTT 5 Will Delay change the timing?

 

MQTT 5 Will Delay gives a session a chance to resume after a temporary connection loss before the Will is published. Its default is zero when the property is absent. A non-zero delay is not a promise that the broker will always wait the full interval, because the session ending can bring publication forward.

 

The controlling rule is the earlier of the Will Delay interval elapsing and the session ending. Suppose the Network Connection has just closed at illustrated time zero, Will Delay is 30 seconds and Session Expiry permits the disconnected session to remain for 120 seconds. With no qualifying reconnection or other change, the illustrated Will publication becomes due at 30 seconds.

 

If Session Expiry instead ends the session after ten seconds, the session ending wins and publication becomes due at ten seconds. With a zero Session Expiry that ends the session at connection closure, a 30-second Will Delay does not by itself create a 30-second grace period. These are protocol arithmetic examples, not measured results from our MQTT 3.1.1 experiment.

 

Illustrative MQTT 5 settings

Publication boundary after connection closure

Will Delay 30 s; Session Expiry 120 s

30 s: the Will Delay elapses first.

Will Delay 30 s; Session Expiry 10 s

10 s: the session ends first.

Will Delay 30 s; session ends at closure

Session ending takes precedence over waiting 30 s.

Same session resumes before the pending deadline

The applicable resumption rule suppresses the pending Will.

 

Resuming the same session matters. A reconnect with settings that end the old session is not interchangeable with continuing it. A duplicate ClientID, Clean Start and whether state remains available can alter the outcome. Test the actual reconnect sequence instead of treating every new network connection as cancellation of every earlier offline notification.

 

Which clock starts when the physical link fails?

 

Physical loss, broker detection, Network Connection closure and Will publication are separate events. The Will Delay examples start after connection closure. They do not include however long the broker first takes to recognise a silent failure. An operator timing from a power cut can therefore observe more than the configured Will Delay before a subscriber receives anything.

 

Message Expiry is another MQTT 5 concept. For a Will, it concerns the published message’s lifetime under the relevant rules; it is not the delay before publication or the Keep Alive interval used to notice silence. Do not add or substitute these settings without understanding which stage each one governs.

 

A successful reconnect also cannot withdraw a Will that has already been published and acted upon. The application can publish a newer online status, but consumers may have already received the earlier offline event. Design alerts and recovery actions to handle legitimate state transitions and races rather than assuming the network supplies a perfect physical-presence oracle.

 

What do QoS, permissions and payload design change?

 

Will QoS selects the delivery level for the Will publication, and subscriber delivery has its own relevant state and negotiated limits. Our MQTT QoS guide explains why protocol delivery guarantees should not be expanded into claims that a business action happens exactly once. A repeated notification should be safe for the application to process.

 

Will Retain is independent of Will QoS. Choosing QoS 1 does not automatically retain the message, and enabling retention does not create an unlimited delivery guarantee. Check the actual values sent in CONNECT rather than inferring one setting from the other.

 

Use a status topic and permissions that suit the client’s identity and the intended consumers. A readable topic name is not an access-control boundary. Broker implementations and plugins can apply their own checks to Will configuration, publication, subscription and receipt. Verify the applicable policy with authorised test identities.

 

The payload was registered in advance. If it contains a timestamp generated when the client connected, that timestamp is not automatically rewritten to the eventual failure time. Likewise, a registered text such as battery-empty does not prove why a connection later vanished. Prefer a precise meaning such as “this MQTT connection ended under the Will rules”, with application context that consumers can interpret correctly.

 

How should you implement a reliable status pattern?

 

Choose the status contract before adding an alert. Identify which connection it describes, what online means, how a planned shutdown is represented and how consumers distinguish a new generation of the device’s session. Keep those meanings narrower than physical availability or successful sensor operation unless additional evidence supports them.

 

  1. Choose a concrete Will Topic, explicit payload, QoS and retention policy, and configure them before connecting.

  2. Verify connection acceptance and publish the intended online state through the normal application path.

  3. Subscribe authorised observers to the correct status topic and verify live and later-subscription behaviour separately.

  4. For planned shutdown, publish the desired final status and verify the required completion before normal DISCONNECT.

  5. For MQTT 5, test Will Delay, Session Expiry and same-session resumption together.

  6. Test failure, reconnect and consumer actions with recorded evidence, including duplicate and stale-status handling.

 

The Eclipse Paho client API documents will_set and its requirement to configure the Will before connecting. The Mosquitto publishing-client manual lists the Will Topic, payload, QoS and retention options and MQTT 5 property controls. Check the installed tool version before turning an example into an operational command.

 

Why might an expected Will message be missing?

 

First establish whether the client actually registered an accepted Will on the connection being tested. Then distinguish absence of publication from failure to receive or process it. A wrong subscription filter, rejected permissions, an observer connecting too late for a non-retained message or an application callback problem can look like a missing Will.

 

  • Check whether normal DISCONNECT removed the Will, including the MQTT 5 reason code where available.

  • Confirm that the broker has detected and closed the connection; do not time only from the apparent physical fault.

  • Inspect MQTT 5 Will Delay, Session Expiry and whether the same session resumed before publication became due.

  • Verify the exact topic, applicable permissions, retention and the observer’s subscription and delivery state.

  • Check broker availability and logs, then verify the consumer’s actual application outcome separately.

 

A local broker and a cloud broker also observe different boundaries. A broadband outage can break the gateway’s cloud connection while the greenhouse continues running locally. A Will on the cloud side may correctly report the connection loss without establishing that local control stopped. If the broker itself fails, the same messaging path may be unable to deliver an immediate warning.

 

A useful Last Will design delegates a specific notification to the broker and makes its interpretation explicit. Register it while connected, treat retained status as a latest value, and test normal shutdown as carefully as failure. Combine connection evidence with application evidence when deciding what recovery or alert is justified.

 

Frequently asked questions

 

What is a Last Will Message in MQTT?

 

It is a message a client registers during connection establishment for the broker to publish when the connection and session conditions require it. The failed client does not send it at the moment of failure.

 

Is a Last Will published immediately when the client connects?

 

No. CONNECT registers the Will. The client must publish any intended online status separately, and the broker publishes the Will only under the applicable later conditions.

 

Does a normal MQTT disconnect send the Will?

 

A normal disconnect removes the pending Will. MQTT 5 also defines reason code 0x04, Disconnect with Will Message, which explicitly requests the Will instead.

 

Does Last Will automatically retain the offline status?

 

No. Will Retain is an explicit setting. A non-retained Will can reach current recipients without creating a retained latest value for a later subscription.

 

Does MQTT 5 Will Delay always wait its full interval?

 

No. The session ending can bring publication forward. The earlier of Will Delay elapsing and session ending governs, while an applicable same-session resumption can suppress the pending Will.

 

Does a Will prove that a device has lost power?

 

No. It reflects the broker’s connection and session rules using a predefined payload. A path failure, administrative closure or other condition can produce similar evidence without proving a physical power loss.

 
 
UK Techie Broadband Providers
bottom of page