Why a Decommissioned Sensor Still Shows a Value: MQTT Retained Messages and QoS in SCADA
Clear a stale MQTT retained message with one zero-byte publish, then set QoS, Retain Handling, Session Expiry and Message Expiry on purpose — with MQTT 5.0 clause numbers, property IDs and reason codes.
The decommissioned sensor still reads 4.82 bar
The transmitter on site/line1/press/pt101/pv came off the pipe two months ago. A freshly opened HMI screen shows 4.82 bar anyway. The gateway is dead. Nobody is publishing.
That is a retained message the broker is still holding. Clearing it is one line:
# zero-length payload, retain 1 -> delete the retained message on this topic
mosquitto_pub -h broker -t 'site/line1/press/pt101/pv' -r -n
A zero-byte payload with RETAIN=1 meaning "discard the stored value" is written into §3.3.1.3 RETAIN of both MQTT 3.1.1 and 5.0. The clearing message itself is not stored, and it is delivered to subscribers already connected. So the HMI has to survive an empty payload without throwing. That is where you get caught the first time.
Raising QoS does not make this go away. QoS, retain, session lifetime, and the timestamp and quality you put in the payload are four separate decisions.
QoS is a delivery guarantee, not a data-quality one
QoS is a contract for one hop between a client and the broker. It says nothing about whether the value is current, whether the PLC accepted it, or whether the instrument is healthy. The cost shows up directly as packet count (MQTT 5.0 §4.3).
| QoS | Packets | Flow | Where it fits in SCADA |
|---|---|---|---|
| 0 | 1 | PUBLISH | Fast telemetry where the next sample is seconds away |
| 1 | 2 | PUBLISH → PUBACK | State changes and events. Assumes the receiver handles duplicates |
| 2 | 4 | PUBLISH → PUBREC → PUBREL → PUBCOMP | Rare in the field. 4× the packets, and it does not buy command safety |
Most equipment data is finished at QoS 0 or 1. QoS 2 is tempting for a motor start because of the words "exactly once", but the guarantee covers the MQTT hop only. A start command needs a command ID, an interlock check, feedback, a timeout and an operator audit trail. QoS does not supply any of them.
Some brokers refuse QoS 2 outright. In MQTT 5.0 they say so with the Maximum QoS property (0x24) in CONNACK, and publishing above it returns reason code 0x9B QoS not supported. 3.1.1 has no such channel, so you read the broker's documentation instead.
Do not use the DUP flag to detect duplicates
At QoS 1 the same message arrives twice. That is the design, not a fault. The party re-sending sets the DUP flag — bit 3 of the first fixed-header byte (§3.3.1.1). At QoS 0 DUP must always be 0.
The trap is what happens next. The DUP value is not propagated to subscribers. When the broker takes a publisher's retransmission and sends its own PUBLISH onward, DUP can be 0. That behaviour is stated in the same §3.3.1.1. So deduplication has to key off a sequence number or a command ID inside the payload. Dedup code that trusts DUP lets the duplicate through silently.
Build the receiving side like this:
- Put a source timestamp in the payload.
- Put a per-source increasing
sequencenumber in it if order matters. - Make historian and event writes idempotent — the same message twice gives the same result.
- Never increment a production count or a stop count just because the same MQTT message came back.
The thing that breaks most often is the event table. The network drops for two seconds. The subscriber reconnects. QoS 1 messages are redelivered. The event handler writes them as new events and the daily report is wrong. MQTT did exactly what the spec says; only the business data broke.
Use Response Topic and Correlation Data for commands
Hand-rolling a command ID and a reply topic into the payload is common, but MQTT 5.0 already has the slots: Response Topic (property 0x08) and Correlation Data (0x09). Send both on the request; the receiver copies the Correlation Data verbatim and answers on the Response Topic. Prefer this over your own convention — another vendor's client understands it with no agreement needed.
3.1.1 has neither property, so the fields go in the payload. When they do, their names belong in the project document, not in one gateway's source.
Retain only what a new subscriber should be shown
A retained message is the one message per topic the broker stores and hands to every new subscriber immediately. One per topic. Convenient for state, and dangerous the moment a screen cannot tell a stored value from a live one.
Reasonable to retain:
- Edge device birth information.
- Static facts — model number, firmware version.
- Current mode or recipe name, provided a timestamp and device state travel with it.
- Anything a screen explicitly labels "last known state".
Bad to retain:
- Momentary commands. They re-execute on every client restart.
- Alarm acknowledgement requests.
- Fast-changing analogue samples.
- Batch events that must be processed once.
MQTT 5.0 gives the receiver control too, in the SUBSCRIBE subscription options (§3.8.3.1) — the 2-bit Retain Handling field.
| Retain Handling | Behaviour |
|---|---|
| 0 | Send retained messages at subscribe time (default, and what 3.1.1 always does) |
| 1 | Send them only if the subscription did not already exist |
| 2 | Do not send retained messages |
For a live HMI screen, 2 is the right answer: the stale value never arrives at all. The Retain As Published bit in the same §3.8.3.1 decides whether the RETAIN flag survives on forwarded PUBLISH packets. At its default of 0 the broker clears it, which is what lets a subscriber treat "RETAIN=1 right after subscribe" as the signal that a value came out of storage.
Some brokers disable retain entirely. If the Retain Available property (0x25) in CONNACK is 0, you cannot publish with retain=1, and trying gets you disconnected with reason code 0x9A Retain not supported.
mosquitto_sub -R is none of these three. It is a client-side filter that declines to print what it already received — the bytes crossed the wire. To stop them at the protocol level you need Retain Handling 2 from a library client.
Split telemetry, state and command topics
One policy for every topic will tangle eventually.
| Topic kind | Example | Usual setting |
|---|---|---|
| Telemetry | site/line1/press/pt101/pv | QoS 0–1, not retained, source timestamp required |
| State | site/line1/filler/state | QoS 1, retained only when a last state is genuinely needed |
| Birth/death | site/line1/gw01/status | QoS 1, retained birth plus a Will message |
| Event | site/line1/filler/events | QoS 1, not retained, event ID required |
| Command | site/line1/filler/cmd/start | QoS 1, never retained, Correlation Data + Response Topic |
It makes fault-finding easier as well. A retained command sitting in the broker means the topic policy is wrong, and the -r -n line above clears it.
Session and backlog: the numbers are specified
What the broker stores while a subscriber is down is what decides your operations. MQTT 5.0 names the values.
| Item | Value | Notes |
|---|---|---|
| Session Expiry Interval (0x11) | 32-bit seconds; absent means 0 | 0 = session ends when the connection closes. 0xFFFFFFFF = never expires |
| Clean Start (CONNECT flag, §3.1.2.4) | 1 = discard any existing session and start fresh | A different job from 3.1.1's Clean Session; lifetime is Session Expiry's business |
| Keep Alive (§3.1.2.10) | 16-bit seconds, max 65535 s (about 18 h 12 min) | 0 disables it. The broker disconnects if nothing arrives within 1.5 × Keep Alive |
| Receive Maximum (0x21) | 65535 if absent | Caps in-flight QoS 1/2 messages — the slow-subscriber guard |
| Message Expiry Interval (0x02) | Per-PUBLISH TTL in seconds | An expired message is not delivered, and the remaining time is rewritten when it is forwarded |
Message Expiry Interval is the spec's own answer to "hours of stale process values arrive in one burst". Put 30 s on a 1 s PV and a ten-minute outage no longer dumps 600 dead samples into the HMI. An event collector is the opposite case: no expiry, and store what arrives under its original source timestamp.
Client ID belongs in this section too. Give two gateways the same Client ID and they evict each other. The loser gets reason code 0x8E Session taken over, reconnects, and evicts the other one. The reconnect loop runs for minutes and the data comes out as a sawtooth. That is not a broker setting; it is a Client ID naming mistake.
What to check at commissioning:
- What Clean Start and Session Expiry your client library actually sends. Plenty of libraries default to both meaning "keep no session".
- Which subscribers may receive a backlog and which must not.
- Whether anyone watches the broker's queued-message and dropped-message counters.
- Whether you have dropped and restored a subscriber during live publishing and looked at the ordering and timestamps.
A design that is only correct while every client is up is not a field design. It is a demo.
What has to be in the payload
MQTT does not define payload content. The metadata 5.0 gives you is Payload Format Indicator (0x01, 0 = bytes / 1 = UTF-8) and Content Type (0x03). There is no timestamp field in the protocol. Broker receive time is unusable — on a reconnect backlog it can sit tens of minutes away from when the value was measured.
So the payload carries it:
value: the measurement, state or event.sourceTimestamp: when the device or gateway produced it. UTC, ISO 8601.quality: good / uncertain / bad / simulated / forced.sequence: per-source increasing number.source: gateway, PLC or equipment ID.
A command response carries accepted or rejected, the rejection reason, and the equipment state after evaluation. Correlation Data handles the matching. Without this you are reading broker logs after the incident instead of records.
Tests worth running at commissioning
- Start a fresh subscriber while a publisher is already running and see which retained values arrive. Run it a second time with Retain Handling 2.
- Kill the publisher and confirm the Will message or offline state appears. On 5.0, check nothing has set Will Delay Interval (0x18) — if it has, the Will is late by that much.
- Reconnect the publisher and confirm the offline state is replaced by a normal birth.
- Take a subscriber down long enough to build a backlog, bring it up, and look at ordering and timestamps. Repeat with Message Expiry Interval set.
- Break the network just before PUBACK to force a QoS 1 duplicate, and confirm dedup keys off
sequencerather than the DUP flag. - Confirm command topics are not retained and do not re-fire after a client restart.
- Confirm the HMI renders live, stale, bad and last-known differently.
Sources
- MQTT Version 5.0, OASIS Standard, 2019-03-07. The clause numbers and property IDs above are from this document.
- MQTT Version 3.1.1, OASIS Standard, 2014-10-29, also published as ISO/IEC 20922:2016. RETAIN behaviour (§3.3.1.3) matches 5.0; Retain Handling, Message Expiry, Session Expiry and Response Topic do not exist in it.
Check which version your broker speaks before you design against it. A drawing that uses 5.0 properties on a 3.1.1 broker is a drawing.
MQTT moves messages. Whether a message is fresh, trustworthy, or fit to control anything is decided by the payload and by the SCADA side.