LocalFirst Home
< Back to all guides
Published by Renan

MQTT retained messages: stop treating an old sensor reading as live data

Understand retained MQTT state, device availability and data freshness. Reproduce a stale reading safely and design a timeout that survives reconnects.

MQTT retained messages: stop treating an old sensor reading as live data

Understand retained MQTT state, device availability and data freshness. Reproduce a stale reading safely and design a timeout that survives reconnects.

The freezer sensor lost power an hour ago, but the dashboard still displays a reassuring temperature. Restarting the dashboard makes the number appear immediately. That can be a retained MQTT message doing its job while the application draws the wrong conclusion.

Retained state is useful for reconstructing a view of the system. It is not proof that the device is connected or that the measurement is recent. Give those questions separate answers before using a reading to trigger an automation.

By the end, you should be able to reproduce a replay on disposable topics and choose an explicit expiry policy for one sensor. The dashboard does not need more confidence. It needs a clock.

Keep value, connectivity and freshness separate

A useful sensor model has three independent pieces: the last measurement, the device’s connection status and the age of the measurement. A connected device can have a failed probe. A disconnected device can leave a valid historical reading behind. A broker connection can be healthy while the bridge that collects measurements has stopped.

The Mosquitto MQTT overview describes retained messages as values supplied to matching new subscriptions, and wills as messages associated with unexpected disconnection. Neither mechanism, by itself, establishes when the physical observation occurred.

Use topics with explicit roles, for example lab/freshness/temperature and lab/freshness/availability. For a real integration, document the units and include a measurement timestamp when the device has a trustworthy clock. If a bridge timestamps data, distinguish its reception time from the sensor’s actual measurement time.

A measurement reaches the broker and dashboard; the dashboard separately checks availability and measurement age
A replayed value can rebuild the display without establishing a new physical measurement. Open full-size image

Reproduce the retained-value surprise

Use disposable topics on a local test broker with the Mosquitto command-line clients installed. The commands below assume that broker is reachable at localhost and permits this local test connection. For an authenticated installation, configure credentials and TLS through the clients’ supported configuration files. Do not enable anonymous remote access just to run the exercise.

Publish one retained value:

mosquitto_pub -h localhost -t lab/freshness/temperature -m '18.5' -r

After the publisher exits, create a new subscription in another terminal:

mosquitto_sub -h localhost -t lab/freshness/temperature -v

The expected result is an immediate value even though no sensor is currently measuring anything. Stop the subscriber with Ctrl+C and subscribe again. Receiving the same value again is not a second measurement. These are expected lab observations, not results claimed from your installation.

Remove only that disposable retained value with a zero-length retained publication:

mosquitto_pub -h localhost -t lab/freshness/temperature -n -r

A fresh subscription should now wait for a new publication. Stop that waiting subscriber with Ctrl+C. The publisher manual documents the message and retain options. Do not clear production discovery or state topics indiscriminately while diagnosing one sensor.

Availability needs a device-side policy

Configure the actual publisher to register an offline will on its availability topic and publish online when it has connected and initialized successfully. The will can be retained so a newly connected consumer learns the last availability state. On an orderly shutdown, publish offline explicitly: a normal disconnect should not be treated as a test of an unexpected-disconnection will.

Detection is not instantaneous. Connection loss must be detected according to the connection’s behavior and timing. A broker outage is a different failure again: the consumer may have no broker from which to receive a will. Test these cases separately instead of promising that every power failure produces an immediate offline event.

Do not use connection availability as a substitute for probe health. If the publisher remains connected but stops obtaining valid measurements, it should report that condition or the consumer should time out the data.

Choose a freshness rule the consumer can enforce

For a noncritical example reporting every 60 seconds, you might start by marking data stale after 180 seconds without a valid new measurement. Those numbers are design examples. Choose a timeout based on expected intervals, tolerated gaps and what happens when an automation acts on missing data.

In Home Assistant’s MQTT sensor, expire_after marks a state unavailable after a configured interval without updates. The documentation warns against retaining state for that pattern: replay after a restart or reload can make an expired value appear available again. For a simple expiry-based entity, publish regular non-retained measurements instead of relying on retained state to rebuild it.

If your application genuinely needs retained measurements, make it evaluate the original timestamp on receipt, including after restart. Reject implausible future times and define what happens before clock synchronization. A new broker receipt time must not silently become the observation time of an old payload.

QoS is a delivery concern, not an age test. Increasing QoS cannot turn yesterday’s valid packet into today’s measurement. Similarly, an unchanged temperature still needs a heartbeat or another freshness signal if the publisher suppresses identical values.

Give one test entity an explicit expiry

For the simple non-retained approach, this Home Assistant configuration fragment uses the same disposable topic as the lab above:

mqtt:
  sensor:
    - name: "Lab freshness temperature"
      unique_id: lab_freshness_temperature
      state_topic: "lab/freshness/temperature"
      unit_of_measurement: "°C"
      device_class: temperature
      expire_after: 180

Merge the sensor into an existing mqtt: configuration rather than creating a duplicate top-level key. Validate the configuration through Home Assistant before restarting. Remove the old retained test value with the earlier cleanup command, then publish a new disposable value without -r:

mosquitto_pub -h localhost -t lab/freshness/temperature -m '18.5'

With the entity loaded and receiving the test message, expect the number to become unavailable after the configured period without another update. Repeat after a consumer restart and record the observed behavior; do not substitute an assumed result. For a real publisher, regular updates must represent fresh measurements or carry enough quality information to reject a cached replay.

Test failures against the automation, not just the card

First stop measurements while leaving the publisher connected. Then test abrupt publisher loss, orderly shutdown, consumer restart and broker interruption separately. Record the displayed value, availability and whether the automation runs in each case.

A useful automation rule requires acceptable age and valid quality in addition to a numeric threshold. For a missing freezer reading, send a sensor-unavailable notification rather than claiming the freezer itself is warm. Those are different problems requiring different actions.

Keep a short record of reporting interval, timeout, timestamp source and restart behavior beside the configuration. When expanding a property sensor network, carry that same freshness contract through every bridge. A successful radio or MQTT delivery is only one part of delivering a trustworthy reading.

Keep reading

Related guides

View all guides