MQTT Retained Messages and Last Will Explained (with a .NET Demo)
MQTT Retained Messages and Last Will Explained (with a .NET Demo)
MQTT & AI Systems, episode 2. Video: 📹MQTT Retained Messages and Last Will Explained · Code:
mqtt-presence-benchat tagmq02· New to MQTT? Start with episode 1: MQTT Explained.
My AI agent says line 3 is fine: 71 °C, all good. That sensor died an hour ago, and the broker still says online.
MQTT isn't broken. The problem is one retained message and one setting I didn't use. This post walks through both, then measures them on a real broker: a crashed process is reported as offline within a tenth of a second, but a power cut leaves the agent trusting a dead sensor for 15.6 seconds.
Table of Contents
- The setup: one sensor, one broker, one agent
- Retained means current state
- The trap: an "online" that outlives its sensor
- The Last Will: four lines in MQTTnet
- When the Will fires, and when it doesn't
- Crash vs power cut
- Will Delay and Session Expiry
- The agent rule: presence before value
- The measurements
- Key takeaways
The setup: one sensor, one broker, one agent
A sensor publishes two topics:
line3/temp, the reading, every 2 seconds;line3/sensor/status,onlineoroffline.
An AI agent subscribes to line3/# and answers operators. In the demo it's a plain C# subscriber with no model behind it, on purpose: the bug lives in the data the agent is given, and an LLM would trust the same online just as confidently. Everything in this post serves one question: can the agent trust the value it holds?
The demo is .NET 10 with MQTTnet 5.2, against Mosquitto 2.1.2 in a container, over MQTT 5.
Retained means current state
Publish with the retain flag and the broker keeps that message, one per topic. The next retained publish on the same topic replaces it. Every publish in the demo goes through one helper:
Task Publish(IMqttClient client, string topic, string payload) => client.PublishAsync(new MqttApplicationMessageBuilder() .WithTopic(topic) .WithPayload(payload) .WithRetainFlag() // current state, not history .Build());
A subscriber that arrives later gets the retained message the moment it subscribes, with the retain flag set, so it knows it's reading a stored copy, not a live reading.
To delete a retained message, publish an empty payload, retained, on the same topic. That's how the demo resets between runs:
await Publish(client, "line3/temp", ""); await Publish(client, "line3/sensor/status", "");
Retained is current state, not history. Which is exactly the problem.
The trap: an "online" that outlives its sensor
When the sensor starts, it publishes online, retained. Then it dies. Nothing overwrites that message, so the broker hands online to every new subscriber, forever.
Here's the real run with no Last Will: the sensor is killed, and an agent joins 5 seconds later.
10:33:01.0 sensor | connected, NO Last Will, status = online
10:33:03.1 sensor | process killed, the OS closes the socket
10:33:08.5 agent | subscribed to line3/#
10:33:08.5 agent | line3/sensor/status = online (retained)
10:33:08.5 agent | line3/temp = 71.0 (retained)
10:33:08.5 agent | >> Line 3 is at 71.0 °C. All good.
Every step is correct and the answer is wrong. A retained online needs something that can overwrite it when the sensor can't. That's what the Last Will is for.
The Last Will: four lines in MQTTnet
The Last Will is a message the client hands to the broker at CONNECT. The broker holds on to it, and publishes it on the client's behalf if the connection dies without a clean goodbye. It has four fields: topic, payload, retain and QoS.
var builder = new MqttClientOptionsBuilder() .WithTcpServer("127.0.0.1", 1884) // through the cable, so we can cut it .WithClientId("line3-sensor") .WithProtocolVersion(MqttProtocolVersion.V500) .WithKeepAlivePeriod(TimeSpan.FromSeconds(10)); builder .WithWillTopic("line3/sensor/status") // the same topic as "online" .WithWillPayload("offline") .WithWillRetain() // so a late subscriber sees it too .WithWillQualityOfServiceLevel(MqttQualityOfServiceLevel.AtLeastOnce);
Two rules make it work:
- Same topic as
online. The Will'sofflinereplaces the retainedonlineinstead of sitting next to it. - Retained. An agent that subscribes tomorrow still sees
offline.
When the Will fires, and when it doesn't
The broker publishes the Will on a network error, on a keep-alive timeout, or when the connection closes without a DISCONNECT packet ([MQTT-3.1.2-8]).
A clean DISCONNECT discards the Will ([MQTT-3.1.2-10]). So when a service stops politely, it has to publish offline itself before it disconnects:
await Publish(sensor, "line3/sensor/status", "offline"); await sensor.DisconnectAsync(new MqttClientDisconnectOptionsBuilder() .WithReason(MqttClientDisconnectOptionsReason.NormalDisconnection) .Build());
MQTT 5 has a second option: disconnect with reason code 0x04, Disconnect with Will Message. The client leaves cleanly and the broker still publishes the Will.
Crash vs power cut
This is the part most tutorials skip: how fast does the Will arrive?
- The process crashes. The operating system closes the socket and sends a FIN. The broker sees it and fires the Will at once.
- The power is cut. Nothing is sent: no FIN, no reset. On the broker, the socket still looks alive.
In the second case the broker only finds out through the keep-alive. If no packet arrives for one and a half keep-alive periods, it closes the connection ([MQTT-3.1.2-22]). With a 10-second keep-alive, that's up to 15 seconds where the agent trusts a dead sensor. And the timer counts from the last packet, not from the outage.
You can't pull a power plug from a unit test, so the demo puts a small TCP relay, Cable, between the sensor and the broker. Cutting it stops forwarding bytes but leaves both sockets open, which is exactly what a power cut looks like from the broker's side:
while ((read = await from.GetStream().ReadAsync(buffer)) > 0 && !_cut) await to.GetStream().WriteAsync(buffer.AsMemory(0, read)); if (!_cut) to.Client.Shutdown(SocketShutdown.Send); // a normal close still goes through
A shorter keep-alive detects the cut sooner, at the cost of more pings from every device.
Will Delay and Session Expiry
MQTT 5 adds the Will Delay Interval: the broker waits that long before publishing the Will, and if the client reconnects in time, there's no Will at all. That's how you stop a flaky Wi-Fi link from flapping your alerts (offline, online, offline).
There's a catch. The spec publishes the Will when the delay ends or when the session ends, whichever comes first ([MQTT-3.1.3-9]). The default Session Expiry is 0, so on paper, a Will Delay without a Session Expiry does nothing.
On my Mosquitto 2.1.2, it waited the full delay anyway:
| Flags | Will published after the kill |
|---|---|
--will-delay 30 --session-expiry 60 |
≈ 30 s |
--will-delay 30, Session Expiry 0 (MQTTnet) |
≈ 30 s |
mosquitto_sub, Session Expiry 0, Will Delay 30 |
30 s |
Mosquitto's own test, 07-will-delay-session-expiry-0.py, expects the immediate behaviour, so treat this as one version in one container, not a general claim. The safe setting doesn't depend on it: set Session Expiry at least as long as Will Delay, and measure your broker.
The agent rule: presence before value
The fix on the agent side is one line of ordering. Read the status first; if it says offline, the value means nothing:
// Presence first, then the value. var answer = status == "offline" ? $"Line 3: I don't know. The sensor is offline, so {temp} means nothing." : $"Line 3 is at {temp} °C. All good.";
"I don't know" is a correct answer. A confident wrong one is the bug.
The measurements
Same setup for every run: keep-alive 10 s, a reading every 2 s, Mosquitto 2.1.2 in Podman, MQTTnet 5.2, .NET 10, MQTT 5. These are numbers from my machine, not broker benchmarks.
Process killed: offline arrives 0.1 s after the kill.
10:33:40.8 agent | line3/temp = 71.0
10:33:42.8 sensor | process killed, the OS closes the socket
10:33:42.9 agent | line3/sensor/status = offline
10:33:42.9 agent | >> Line 3: I don't know. The sensor is offline, so 71.0 means nothing.
Power cut: 13.7 s after the cut, 15.6 s after the last reading.
10:34:17.8 agent | line3/temp = 71.0
10:34:19.8 sensor | power cut: the socket stays open, nothing crosses it
10:34:32.8 sensor | the client itself just noticed the connection is gone
10:34:33.5 agent | line3/sensor/status = offline
10:34:33.5 agent | offline arrived 15.6 s after the last reading
For 13.7 seconds after the cut, the agent kept answering "All good". Three earlier runs gave 15.6, 15.8 and 15.2 s after the last reading. Mosquitto logged exceeded timeout, and MQTTnet's own keep-alive ping noticed about 0.7 s before the broker did.
Clean goodbye: the offline is the sensor's own publish, and the broker drops the Will.
10:35:17.6 agent | line3/sensor/status = offline
10:35:17.6 sensor | clean goodbye, the broker drops the Will
One more thing about this demo: the broker runs with allow_anonymous true, so any client could publish a retained offline or online on line3/sensor/status. In production, restrict who can publish to status topics with topic ACLs, or presence is something anyone can forge.
Key takeaways
- Retained is current state. One message per topic; an empty retained payload deletes it.
- Put the Last Will on the same retained status topic as
online, soofflineoverwrites it for current and future subscribers. - A clean DISCONNECT drops the Will. Publish
offlineyourself, or use MQTT 5 reason code0x04. - A power cut costs up to 1.5 × keep-alive, counted from the last packet. Here: 15.6 s against 0.1 s for a crash.
- Agents read presence before value. "I don't know" beats a confident wrong answer.
Next up: one sensor, one Will, easy to watch. But when a whole line loses power, does the broker fire 500 Wills on time, and how long is the agent blind? Starting next week, we build a .NET tool to measure it, in public: Simulate 1000 MQTT Clients in C# (mqtt-churn, Part 1).
Resources
- Code for this post: github.com/Romain-OD/mqtt-presence-bench/tree/mq02
- MQTT 5.0 specification (OASIS): Will Flag §3.1.2.5, Keep Alive §3.1.2.10, Will Delay Interval §3.1.3.2.2, RETAIN §3.3.1.3, DISCONNECT reason codes §3.14.2.1
- MQTTnet
- Mosquitto configuration (
mosquitto.conf)
