Skip to content

Tutorial

MQTT Retained Messages and Last Will with ESP32: Online/Offline Status

Use MQTT retained status and Last Will and Testament (LWT) to show whether an ESP32 is online. Configure status topics safely, test unexpected disconnects, and separate availability from sensor freshness and retained commands.

  • 4 min read
  • Updated November 1, 2026
MQTT Retained Messages and Last Will with ESP32: Online/Offline Status

A dashboard that shows 23.4 °C is only useful if you know the sensor is still alive. MQTT has two features built for exactly this: retained messages, so a dashboard that opens later immediately gets the last known value, and the Last Will and Testament (LWT), a message the broker publishes for a device when it disappears without warning.

Quick answer: when the ESP32 connects, register a Last Will of offline, retained, on a status topic such as home/garage/status. Right after connecting, publish online, retained, to the same topic. Every subscriber now always sees the device's real availability. In PubSubClient that's client.connect(id, user, pass, "home/garage/status", 1, true, "offline") followed by client.publish("home/garage/status", "online", true). To delete a retained message, publish an empty retained message to its topic.

Retained Messages in One Minute

Normally the broker forwards a message to whoever is subscribed at that moment, then forgets it. A message published with the retain flag is also kept: the broker stores the last retained message for each topic and sends it straight away to every new subscriber.

Normal messageRetained message
Subscriber connected when it's sentReceives itReceives it
Subscriber that connects laterGets nothing until the next messageGets the last value immediately
Stored by the brokerNoYes, one per topic, the latest
Survives a broker restart—Yes, if persistence is on (Mosquitto's default on Raspberry Pi OS)

Retain state, not events. lamp/state = ON, garage/temperature = 21.4 and status = online are good retained topics: they describe how things are now. doorbell/pressed and lamp/toggle are events; retaining them replays the event to anyone who connects later, including the device itself after a reboot.

The Last Will in One Minute

When a client connects it can hand the broker a will: a topic, a message, a QoS and a retain flag. If the client later vanishes without a clean DISCONNECT (power cut, crash, Wi-Fi gone), the broker publishes the will for it. If the client disconnects properly, the will is discarded.

The broker notices a silent client by its missed keep-alive pings, and waits about 1.5 × the keep-alive before acting. PubSubClient's default keep-alive is 15 seconds, so "offline" appears roughly 20–25 seconds after the plug is pulled.

Choosing the Status Topic

Give every device its own status topic at the top of its branch, and keep it separate from readings and commands:

Output
home/garage/status          online / offline   (retained, also the Last Will)
home/garage/temperature     21.4               (retained: current value)
home/garage/door/state      closed             (retained: reported state)
home/garage/door/set        open               (NOT retained: a command)

With that layout, one subscription to home/+/status gives a dashboard the availability of every device in the house, and the topic naming stays predictable as you add boards. Use the same two payloads everywhere, online and offline. That's what Home Assistant expects by default, and the same convention used by Tasmota and many other firmwares, so mixed systems agree.

The online message is often called the birth message: the counterpart to the will. Publishing it retained on every connect is what makes the pattern self-healing: the moment a board reconnects, the retained offline left by its will is replaced.

Use QoS 1 for both, so subscribers receive them at least once even over a patchy connection. More on structuring topics in MQTT topic naming best practices.

The ESP32 Code

This is the connect function from a PubSubClient sketch. It registers the will, announces online, and restores subscriptions. The complete sketch around it, with non-blocking reconnects, is in ESP32 MQTT auto-reconnect without blocking.

sketch.ino
const char* STATUS_TOPIC = "home/garage/status";

bool connectMqtt() {
  String id = "esp32-" + WiFi.macAddress();   // unique per board
  id.replace(":", "");

  bool ok = mqtt.connect(
    id.c_str(),
    "esp32-garage", "YOUR_MQTT_PASSWORD",     // broker login
    STATUS_TOPIC,   // will topic
    1,              // will QoS
    true,           // retain the will
    "offline"       // will message
  );
  if (!ok) return false;

  mqtt.publish(STATUS_TOPIC, "online", true);   // retained "online" replaces the old "offline"
  mqtt.subscribe("home/garage/cmd/#");
  return true;
}

Planned shutdowns. Because a clean mqtt.disconnect() cancels the will, publish offline yourself before any deliberate disconnect, reboot or OTA update:

sketch.ino
mqtt.publish(STATUS_TOPIC, "offline", true);
mqtt.disconnect();
ESP.restart();

Clearing and Inspecting Retained Messages

Retained messages stay on the broker until replaced. To see every retained message under a topic, connect a subscriber: the retained ones arrive immediately.

terminal
mosquitto_sub -h 192.168.1.20 -u USER -P PASS -t 'home/#' -v --retained-only

To delete one, publish an empty message with the retain flag (-n sends a zero-length payload):

terminal
mosquitto_pub -h 192.168.1.20 -u USER -P PASS -t 'home/garage/status' -r -n

From an ESP32, mqtt.publish(topic, "", true) does the same. Clear the status topic when you retire a device, or dashboards keep showing a board that no longer exists. MQTT Explorer also has a delete button for retained topics.

Using the Status Topic

Home Assistant. In an MQTT sensor or switch, point availability_topic at the status topic, with payload_available: "online" and payload_not_available: "offline". Entities then show Unavailable instead of a frozen value when the board disappears. Discovery and full examples are in MQTT with ESP32 and Home Assistant.

Node-RED. An mqtt in node on home/+/status feeds a dashboard text widget or an alert: a switch node routes offline to a Telegram or email notification. The dashboard side is in Node-RED Dashboard 2.0.

Availability isn't freshness. A board can be online while its sensor has failed and it publishes nothing. Track the time of the last valid reading separately (Node-RED can timestamp each message), and show a reading as stale after a sensible timeout, for example three missed reporting intervals.

Test It in Two Minutes

  1. On a PC or the broker, watch the status topic: mosquitto_sub -h BROKER -u USER -P PASS -t 'home/garage/status' -v.
  2. Power the ESP32. home/garage/status online appears.
  3. Pull its USB cable. After about 20–25 seconds, home/garage/status offline appears: that's the broker publishing the will.
  4. Stop the subscriber and start it again. It immediately prints offline: the will was retained.
  5. Plug the ESP32 back in. online appears again.

You can also try a will without any hardware: mosquitto_sub -t test/x --will-topic test/status --will-payload offline --will-retain, then kill that terminal's process (closing the window, not Ctrl+C, which disconnects cleanly) and watch test/status in another window.

Deep Sleep and Last Will Don't Mix

A battery sensor that wakes, publishes and goes back to deep sleep drops its connection without a clean disconnect every time, so the broker publishes offline after every reading. Two better options for sleeping devices:

  • No will at all. Publish each reading with a timestamp (or retained), and let the dashboard mark the sensor stale if no reading arrives within, say, two wake intervals.
  • Disconnect cleanly before sleeping. Call mqtt.disconnect() before esp_deep_sleep_start(). The will is cancelled, and the last retained online stays, so pair it with the staleness check above.

Never Retain One-Shot Commands

A retained UNLOCK, OPEN or TOGGLE is delivered again every time the device reconnects or reboots, and it repeats the action. Send commands without retain, and retain the reported state the device publishes after acting. If you deliberately want a retained "desired state" (for example heating/target = 21), make sure the firmware treats it as a setting to apply, not an action to perform once.

Troubleshooting

ProblemCauseFix
offline never appearsWill not registered, or the device disconnected cleanlyCheck the connect() call includes the will; graceful disconnects cancel it
offline takes minutesLong keep-alivemqtt.setKeepAlive(15); the delay is about 1.5 × that
Status stuck on offline while the board worksonline published without retain, or to a different topicPublish online retained to the exact will topic
New subscribers see nothingNot retained, or a typo or case difference in the topicUse -r; compare topics character by character
Old devices still listedTheir retained status was never clearedmosquitto_pub -t TOPIC -r -n
Retained values gone after a broker rebootPersistence offpersistence true in mosquitto.conf
Two devices overwrite each other's statusShared topic or client IDOne status topic and one client ID per device
Sleeping sensor flips offline every cycleDeep sleep looks like a crashDrop the will, or disconnect cleanly before sleeping

FAQ

What is an MQTT Last Will? A message the client registers when it connects, which the broker publishes on its behalf if the client disappears without disconnecting properly.

Should the Last Will be retained? For status topics, yes: otherwise a dashboard that opens after the device died never learns it's offline.

How do I delete a retained MQTT message? Publish a zero-length message with the retain flag to the same topic: mosquitto_pub -t TOPIC -r -n.

Does disconnect() send the Last Will? No. A clean disconnect cancels it, so publish offline yourself first.

What QoS should the will use? QoS 1 is the usual choice, so the broker makes sure subscribers receive it.

Next Steps

Continue learning

Related articles

All articles

Signal In

Built from what makers search for

The lookups piling up in SolderHub's search bar every day shape what we publish next — new component pages, board guides, and firmware notes, sent out as they go live.

By subscribing you agree to our Privacy Policy. Unsubscribe anytime.