MQTT Last Will and Testament (LWT) Explained

By | May 29, 2026

MQTT is built to run over networks that are not reliable, so it has to assume that clients will sometimes vanish without warning. A client can drop because its battery died, its radio lost signal, its host crashed, or anything else that prevents it from sending a normal disconnect. The rest of the system needs a way to find out. Last Will and Testament (LWT) is the mechanism MQTT provides for exactly that: a way for each client to leave a final message that the broker will publish on its behalf if it disconnects ungracefully.

This article explains what the will message is, where it is registered, the difference between graceful and ungraceful disconnects, exactly when the broker decides to publish a will, and the practical patterns built on top of LWT (including the canonical retained-status pattern). It is a technical reference; the connection handshake, keep alive, and retained messages have their own dedicated articles in this category.

Last Will and Testament at a glance

AspectDetail
Registered byThe client, inside the CONNECT packet
Published byThe broker, on the client’s behalf
WhenAfter the broker detects an ungraceful disconnect
Suppressed whenThe client sends a proper DISCONNECT before closing (in MQTT 3)
Will fieldsTopic, payload, QoS, retain flag
One active will per connectionA new CONNECT replaces any previous will for that client connection
MQTT 5 additionsWill Delay Interval, optional will on graceful DISCONNECT, will user properties, payload format

The problem LWT solves

In a publish/subscribe system, no other client has any visibility into whether a specific client is still online. They might subscribe to that client’s topics, but silence on a topic does not tell them whether the publisher is fine and simply has nothing new to say, or whether it has dropped offline mid-update. Without a mechanism that the protocol itself supplies, every system that cares about device status has to build one on top, usually with timeouts and heartbeats, and every device has to remember to update its own status, which it cannot do if it has crashed.

LWT solves this directly. The client tells the broker, “if I disappear unexpectedly, please publish this on my behalf.” The broker takes responsibility for noticing the disappearance and publishing the message. Other clients see the will message as an ordinary publish and react accordingly. The client itself does not have to be alive at the moment its will is published, which is the whole point: it is the message it leaves behind for when it cannot speak.

How LWT is set up

A client registers its will when it connects, inside the CONNECT packet. The relevant fields are part of the CONNECT itself (covered in the connection handshake article), and they are all optional; a client that does not want a will simply omits them. When a client does want a will, it provides four pieces of information:

  • Will Topic, the topic the will message will be published to.
  • Will Message (payload), the bytes that will be the message body.
  • Will QoS, the Quality of Service the broker will use when publishing the will.
  • Will Retain, whether the broker will publish the will with the retain flag set.

Together these describe a complete, normal MQTT publish: topic, payload, QoS, retain flag. Once the broker has these in hand, it has everything it needs to publish on the client’s behalf later, and it stores them as part of the connection state for that session.

A client can have at most one will at a time. The will is tied to the CONNECT and applies only for the lifetime of that session. If the client disconnects (gracefully or otherwise) and then later opens a new connection, it sends a fresh CONNECT, which may or may not register a new will. There is no separate “set will” packet; the will is established at connect time and that is its only entry point.

Graceful versus ungraceful disconnects

The whole point of the will is to distinguish two ways a client can leave: on purpose or not. Getting these two cases right is what makes LWT useful, so it is worth being precise about them.

A graceful disconnect is when the client deliberately closes the session by sending a DISCONNECT packet before closing the TCP connection. The DISCONNECT tells the broker “I am leaving on purpose.” In MQTT 3.1.1, the response is unambiguous: the broker discards the stored will and does not publish it. A clean, intentional exit is exactly the case the will is not meant to announce.

An ungraceful disconnect is any departure that is not announced with a DISCONNECT. The underlying network connection is closed, reset, or becomes half-open without a DISCONNECT having been sent. The causes are varied: a network drop, a device crash, a power loss, a protocol violation that the broker reacted to by closing the connection. From the broker’s point of view, what matters is that no DISCONNECT preceded the loss. This is the case the will exists for, and the broker publishes the will message on behalf of the absent client.

So the rule, in MQTT 3.1.1, is simple: the will is published on ungraceful disconnects and suppressed on graceful ones. A well-behaved client therefore always sends a DISCONNECT when it intends to leave cleanly, both to free broker resources promptly and to prevent its will from being published when there is no real loss to report.

When the broker actually publishes the will

The harder question is when the broker decides that an ungraceful disconnect has happened, because the answer is not “immediately.” The MQTT 3.1.1 specification lists the situations that trigger the will:

  • The broker detects an I/O error or network failure on the connection.
  • The client fails to communicate within the negotiated Keep Alive period.
  • The client does not send a DISCONNECT before its network connection closes.
  • The broker closes the network connection because of a protocol error.

Three of these are immediate from the broker’s perspective; the second one is not. Detecting that a client has gone silent depends on the keep alive mechanism, because TCP itself often fails to report a broken connection promptly on unreliable links (a problem covered in detail in the keep alive article). If a client has gone silent on a half-open connection, the broker will only conclude that it is gone after one and a half times the keep alive interval has elapsed without a packet from it. That delay is the reason will messages do not always appear instantly when a client vanishes; the broker has to be sure the client is actually gone before publishing the will.

The same article explains why setting a sensible keep alive interval matters for LWT to be useful. A keep alive of, say, ten minutes means the broker may not publish a will for fifteen minutes after a client actually drops, which is too long for many applications. The will mechanism is only as responsive as the keep alive that drives the broker’s detection.

What the broker publishes

When the broker publishes the will, it does so as a normal MQTT publish using exactly the four fields the client registered: the will topic, the will payload, the will QoS, and the will retain flag. From the perspective of any subscribed client, the will is indistinguishable from any other publish on that topic. There is no special “this is a will” flag on the delivered message in MQTT 3.1.1; subscribers see only the publish itself.

This is important to understand because it means the will inherits all the normal behaviors of a PUBLISH. It is delivered to current subscribers at the per-subscriber QoS downgrade rules (the minimum of the will QoS and each subscriber’s subscription QoS). It is matched against wildcards just like any other publish. And if the will retain flag was set, the broker stores it as the retained message for the will topic, replacing whatever retained value was there before. That last point is the basis of the retained-status pattern, covered below.

A will is published once per ungraceful disconnect. The broker publishes the will once and applies the normal QoS delivery rules for that publish. Once it has been published, it is gone, and the next time the client connects it starts fresh with whatever will (if any) the new CONNECT registers.

MQTT 5 changes: Will Delay and willful goodbyes

MQTT 5 keeps LWT but refines it in three useful ways, each of which addresses a real limitation of the MQTT 3.1.1 design.

Will Delay Interval. In MQTT 3, the will is published as soon as the broker decides the client is gone. That is sometimes wrong, because brief network glitches and quick reconnects are common. A client that drops, reconnects within a few seconds, and resumes its session probably did not want every subscriber to receive a misleading “Offline” message in the interim. MQTT 5 adds the Will Delay Interval, a number of seconds the broker waits after detecting the disconnect before actually publishing the will. If the client reconnects with the same ClientId before the Will Delay Interval expires, the broker cancels the pending will publication, subject to the session rules in MQTT 5. This converts the will from a thing that fires on every blip into a thing that only fires on genuine, sustained disappearances. The session and message expiry article covers this and related expiry mechanisms.

Will on graceful DISCONNECT. In MQTT 3, a graceful DISCONNECT always suppresses the will. MQTT 5 lets a client choose: the DISCONNECT packet now carries a Reason Code, and MQTT 5 allows a DISCONNECT with Reason Code 0x04 (“Disconnect with Will Message”), which tells the broker to publish the will even though the disconnect itself was graceful. This is useful when an application wants to announce a planned departure under specific circumstances rather than silently leaving.

More structure on the will itself. MQTT 5 adds properties to the will, including a Will Delay Interval as above, but also user properties, payload format indicator, content type, response topic, correlation data, and a message expiry interval. These let the will carry the same kinds of metadata as any other MQTT 5 publish, so a will can describe its payload, identify itself, or expire if it has not been delivered within a configured window. The MQTT 5 articles in this category cover these properties in their respective contexts.

These changes do not alter the basic model. The will is still registered in CONNECT, still belongs to one session, still inherits PUBLISH behavior on delivery. MQTT 5 simply makes it more controllable, more responsive to brief disconnects, and more expressive.

The retained-status pattern: LWT plus retained

The single most useful pattern built on LWT, and one of the most useful idioms in MQTT overall, is combining a retained will with a regular retained publish to track whether a device is currently online. It works as follows.

  1. The client connects with a CONNECT that registers a will. The will topic is the client’s status topic, say client1/status. The will payload is Offline. The will retain flag is set to true.
  2. Immediately after connecting, the client itself publishes a message to the same topic, client1/status, with payload Online and the retain flag set to true.

While the client stays connected, the broker holds the retained Online message on the topic, so every new subscriber to client1/status immediately learns that the client is currently online. If the client disconnects ungracefully, the broker publishes the will, which carries payload Offline and retain = true. That publish becomes the new retained message on the topic, replacing the Online value. From that moment forward, anyone subscribing to client1/status learns the client is currently offline.

When the client comes back online (and reconnects, and again publishes the Online retained message), the cycle continues. The retained value on the topic always reflects the device’s current state, set automatically by three MQTT features working together: the retain flag making the value visible immediately to new subscribers, LWT making sure the offline transition is published even when the device cannot do it itself, and the broker’s per-topic retained storage carrying state across all the comings and goings of subscribers.

A subtle but important point: the pattern depends on both messages being marked retain. If the Online message is published without retain, new subscribers do not see it; if the will is registered without retain, the offline transition is published live but not stored, and new subscribers after the disconnect learn nothing. Both legs of the pattern need the retain flag for it to work properly. The retained messages article covers the retained side of this idiom in detail.

A will firing across a disconnect: a worked timeline

It helps to trace what actually happens, second by second, when a will fires. Suppose a sensor connects with the following:

  • ClientId sensor-42
  • Keep alive: 60 seconds
  • Will topic: sensors/sensor-42/status
  • Will payload: Offline
  • Will QoS: 1
  • Will retain: true

After connecting, the sensor publishes a retained Online message to the same topic, so any current and future subscriber sees Online. A monitoring client is subscribed to sensors/+/status.

  1. T+0s. The sensor sends a reading. The connection is healthy. The monitoring client sees Online as the retained value on sensor-42/status.
  2. T+10s. The cellular link drops. The sensor cannot send anything; it does not know yet that it cannot.
  3. T+30s. Roughly mid-keep-alive. The broker has not received a packet from the sensor for 30 seconds, but has not yet decided it is gone. From the broker’s perspective the connection still looks alive, because TCP has not reported it broken.
  4. T+90s. Roughly 1.5× the keep alive interval has elapsed without a packet from the sensor or a PINGREQ. The broker concludes the client is gone, closes its side of the connection, and publishes the will: a PUBLISH to sensors/sensor-42/status with payload Offline, QoS 1, retain = true.
  5. T+90s (continued). The broker delivers the will to the monitoring client at the per-subscriber downgraded QoS (here, whatever the monitoring client subscribed at). The retained value on sensor-42/status is now Offline, replacing the previous Online.
  6. T+90s onward. Any new subscriber to sensors/+/status or sensors/sensor-42/status receives the retained Offline value immediately on subscribe, learning that the sensor is offline.
  7. T+300s. The sensor’s link returns. It reconnects, registers a new will, and publishes a fresh retained Online message. The retained value on the topic flips back to Online. The monitoring client sees the live publish.

A few practical points fall out of this timeline. First, the gap between the actual disconnect (T+10s) and the will being published (T+90s) is roughly 80 seconds, set entirely by the keep alive interval. Reducing keep alive to 15 seconds would cut that to about 23 seconds, at the cost of more PINGREQ traffic; raising it to five minutes would push it to over seven minutes. Second, the retained flag on the will is what carries the offline status forward to new subscribers; without it, only clients subscribed at T+90s would have learned about the loss. Third, none of the other clients needed any custom logic; they simply subscribed and read the topic.

This is the will-plus-retained pattern in its plainest form, with the timing made concrete.

A few more LWT patterns

The status pattern is the most common, but it is not the only thing LWT is good for.

Generating alerts on unexpected loss. A will with a non-retained payload and a topic the alerting system subscribes to is a cheap way to fire an alert when a critical client disappears. The will is published once, the alerting system gets it, and there is no leftover retained value to clean up.

Announcing context on departure. A will payload can be more than a simple flag. It can include the device’s identifier, its last known state, a reason hint, or any other metadata that helps the receiver understand what just left. Because the payload is opaque to the protocol, the application chooses what to put in it. (MQTT 5’s user properties and content type on the will make this more disciplined.)

Coordinating between peers. In systems where multiple instances cooperate, a will can be used to notify peers that one of them has dropped, so the others can take over its responsibilities. Combined with shared subscriptions (MQTT 5) or backend coordination, this is a building block for failover behavior, though the heavy lifting still lives in the application, not the protocol.

Authorization and the will

A point that is easy to miss because the will is published by the broker rather than the client: the broker still has to authorize that publish, and brokers vary in how strictly they enforce it. The CONNECT registers the will with a topic and payload, but the broker is the one that will eventually emit the PUBLISH, and most brokers check the client’s authorization to publish to the will topic before they will accept the will at all.

Two failure modes are worth knowing about. First, a CONNECT may be rejected because of an unauthorized will topic. If the client’s permissions do not let it publish to the will topic, the broker can refuse the connection outright (or accept the connection and silently drop the will, depending on the broker and its configuration). A client that finds its CONNECT mysteriously rejected with a “not authorized” code, even though its credentials are correct, may be hitting this case. Always check that the will topic is one the client is allowed to publish to.

Second, the will may be silently discarded at publication time. Some brokers re-check authorization when the will is about to fire, rather than only at CONNECT. If the client’s permissions changed in the meantime, or the broker enforces stricter rules at publish time than at connect time, the will simply does not get published and no error is delivered to anyone, because there is no one to deliver an error to. Behavior here is implementation-specific.

Both pitfalls argue for the same discipline: design your topic structure so that the will topic is naturally within the same permission set as the client’s normal publishes. The conventional way to do this is to put a client’s will topic alongside its other topics, for example clients/<id>/status next to clients/<id>/data, so that any policy granting the client publish access to its own topic tree automatically covers the will. Setting wills on topics outside that tree is technically possible but invites the authorization mismatches above.

Common pitfalls with LWT

A few mistakes recur.

Forgetting to send DISCONNECT. A client that intends to leave cleanly but does not send a DISCONNECT will trigger its own will, which is generally not what was intended and can confuse subscribers. Always send a DISCONNECT for intentional exits.

Setting the keep alive too high. Because the broker only realizes a silent client is gone after one and a half keep alive intervals, a long keep alive translates directly into a long delay before a will is published. If you need timely will delivery, choose a keep alive appropriate to that timeliness.

Confusing the will with the client’s own publishes. The will is published by the broker, not the client, and is one shot. A client that needs to keep something updated must publish it itself; the will is only for the case where the client can no longer do that.

Misusing retain on the will. A retained will leaves a value on the topic that persists until something explicitly overwrites or clears it. If you set a retained will and the client never reconnects, the retained “Offline” value stays on the topic indefinitely. This is desirable when you want the status pattern; it is undesirable when the topic was meant for short-lived event-style messages.

Assuming the will fires immediately. As covered, detection depends on keep alive on silent disconnects. A will is not an instantaneous alarm; it is a deferred publish, with the delay determined by how quickly the broker can be confident the client is gone.

How LWT connects to the rest of MQTT

LWT sits at the intersection of several MQTT features:

  • The CONNECT packet is where the will is registered, as covered in the connection handshake article.
  • The keep alive mechanism is what makes the broker eventually conclude that a silent client is gone, and so triggers the will.
  • DISCONNECT is the packet that suppresses the will in MQTT 3, and in MQTT 5 can optionally trigger it.
  • Retained messages combine with LWT to produce the standard device-status pattern.
  • MQTT 5 Will Delay Interval and the will properties refine when and how the will is published, covered in the session and message expiry article and related MQTT 5 articles.

Used carefully, LWT lets MQTT applications observe the comings and goings of clients without any of the polling or heartbeat machinery that other protocols would require.

Frequently asked questions

What is the Last Will and Testament in MQTT?

LWT is a message a client registers with the broker at connect time, which the broker publishes on the client’s behalf if the client disconnects ungracefully. It is the protocol’s mechanism for letting other clients know when a client has vanished without a clean exit.

Where is the will message set?

In the CONNECT packet. The will topic, will payload, will QoS, and will retain flag are all CONNECT fields. There is no separate “set will” operation; the will is registered at connection time and applies for the lifetime of that session.

When does the broker publish the will?

On an ungraceful disconnect: when the broker detects an I/O error or network failure, when the client fails to communicate within the keep alive interval, when the client closes the network connection without a DISCONNECT, or when the broker closes the connection because of a protocol error. A graceful DISCONNECT suppresses the will in MQTT 3.1.1.

Why does my will not fire immediately when a client drops?

Because silent disconnects are detected via the keep alive mechanism. The broker waits up to roughly one and a half keep alive intervals before concluding that a quiet client is gone. A shorter keep alive gives faster will delivery at the cost of more PINGREQ traffic.

Can a will be retained?

Yes. The will retain flag in CONNECT controls whether the broker publishes the will with the retain flag set. A retained will is the basis of the standard online/offline status pattern.

What changes about LWT in MQTT 5?

MQTT 5 adds a Will Delay Interval (the broker waits before publishing the will, so brief reconnects do not trigger spurious wills), allows certain graceful DISCONNECTs to still trigger the will via reason codes, and adds will properties such as user properties, payload format indicator, content type, response topic, correlation data, and a message expiry interval.

How do I make sure my will is not published when I leave intentionally?

Send a DISCONNECT packet before closing the TCP connection. In MQTT 3.1.1 a DISCONNECT always suppresses the will. In MQTT 5, the will is also suppressed by default on a normal DISCONNECT, unless a reason code explicitly requests it.

Author: Zakaria El Intissar

I'm an automation and industrial computing engineer with 12 years of experience in power system automation, SCADA communication protocols, and electrical protection. I build tools and write guides for Modbus, DNP3, IEC 101/103/104, and IEC 61850 on ScadaProtocols.com to help engineers decode, analyze, and troubleshoot real industrial communication systems.