MQTT Retained Messages Explained with Examples

MQTT Retained Messages Explained with Examples

MQTT Retained Messages Explained with Examples

Introduction

As you build more MQTT-based IoT projects, you’ll eventually encounter a common problem.

Imagine an ESP32 publishes the current state of a smart light:

Light = ON

The message is successfully delivered and everything works as expected.

Now suppose a new device, dashboard or application subscribes to that topic a few minutes later.

What happens?

Nothing.

The new subscriber does not receive the last published message because MQTT normally delivers messages only to clients that are connected at the time the message is published.

This is where MQTT Retained Messages become incredibly useful.

A retained message allows the MQTT broker to store the most recent message for a topic. Whenever a new subscriber joins that topic, the broker immediately sends the stored message without waiting for the publisher to send data again.

In this tutorial, you’ll learn what retained messages are, how they work, when to use them, and how to implement them using Mosquitto, ESP32, and Node-RED.

What is an MQTT Retained Message?

A retained message is a normal MQTT message with an additional flag called the Retain Flag.

When a message is published with the retain flag enabled:

  1. The MQTT broker stores the message.
  2. The broker remembers the topic.
  3. New subscribers automatically receive the latest stored message.

Instead of waiting for the next update, subscribers immediately know the current state.

This feature is extremely useful in IoT systems where devices may connect and disconnect frequently.

Why Are Retained Messages Important?

Let’s consider a smart home example.

A relay controlling a living room light publishes:

Topic: home/livingroom/light/status

Message: ON

Without retained messages:

  • Light status is published.
  • Broker delivers the message.
  • Dashboard disconnects.
  • Dashboard reconnects later.
  • Dashboard shows no status.

The dashboard must wait until the ESP32 publishes again.

With retained messages:

  • Broker stores the latest state.
  • Dashboard reconnects.
  • Broker immediately sends “ON”.
  • Dashboard instantly displays the correct state.

The user sees the current status without delay.

How Retained Messages Work

MQTT Retained Messages Explained with Examples

The broker always keeps the most recent retained message for each topic.

Publishing a Retained Message Using MosquittoMQTT Retained Messages Explained with Examples

Mosquitto provides a simple way to publish retained messages.

Example:

mosquitto_pub -h localhost -t home/light/status -m "ON" -r

Notice the additional parameter:

-r

The -r option enables the retain flag.

Mosquitto stores:

Topic:
home/light/status

Message:
ON

as the latest retained message.

Testing Retained Messages

Let’s see retained messages in action.

Publish a retained message:

mosquitto_pub -h localhost -t home/light/status -m "ON" -r

Now subscribe:

mosquitto_sub -h localhost -t home/light/status

Immediately after subscribing, you’ll receive:

ON

Even though the message was published earlier.

This demonstrates the power of retained messages.

Retained vs Non-Retained Messages

MQTT Retained Messages Explained with Examples

Feature Normal Message Retained Message
Delivered to connected clients Yes Yes
Stored by broker No Yes
Sent to future subscribers No Yes
Useful for device state No Yes
Useful for sensor status No Yes

Using Retained Messages with ESP32

When building MQTT-based IoT systems, retained messages are commonly used for:

  • Relay status
  • Device state
  • Sensor availability
  • Configuration values
  • Last known readings

Example:

client.publish(
  "home/livingroom/light/status",
  "ON",
  true
);

The third parameter:

true

enables the retain flag.

Now every new MQTT subscriber immediately receives the current relay state.

Using Retained Messages with Node-RED

Node-RED also supports retained messages.

Open your MQTT Output node.

Enable:

Retain = true

Whenever Node-RED publishes a message:

ON

the broker stores it as the latest state.

This is especially useful when building dashboards for:

  • Smart homes
  • Industrial monitoring
  • Building automation
  • Environmental monitoring

Real-World Use Cases

Smart Home Automation

Store:

Light Status = ON
Fan Status = OFF
Door Lock = LOCKED

New dashboards immediately display the current state.

Environmental Monitoring

Store:

Temperature = 25°C
Humidity = 60%

New monitoring systems instantly display the latest readings.

Industrial IoT

Store:

Machine Status = Running

Operators immediately know equipment status after reconnecting.

Device Availability

Store:

Device = Online

Useful for monitoring large IoT deployments.

How to Clear a Retained Message

Sometimes you may want to remove a retained message.

Publish an empty retained message:

mosquitto_pub -h localhost -t home/light/status -n -r

Explanation:

-n

sends a null payload.

-r

marks it as retained.

The broker removes the stored retained message.

When Should You Use Retained Messages?

Use retained messages for:

✅ Device status

✅ Relay state

✅ Sensor availability

✅ Configuration values

✅ Last known readings

Avoid retained messages for:

❌ Rapid sensor streams

❌ Event notifications

❌ Temporary alerts

❌ High-frequency telemetry

Not every MQTT topic needs retention.

Common Mistakes

Retaining Every Message

Beginners often enable retention everywhere.

This can create unnecessary broker storage and confusion.

Forgetting to Clear Old Data

Old retained messages can mislead new subscribers.

Always clear obsolete retained messages when needed.

Using Retained Messages for Events

Events such as:

Motion Detected
Button Pressed
Alarm Triggered

should typically not be retained.

What to Learn Next

Now that you understand retained messages, continue with:

  • MQTT QoS Levels Explained (QoS 0, QoS 1, QoS 2)
  • MQTT Last Will and Testament (LWT)
  • ESP32 MQTT Temperature and Humidity Monitoring
  • MQTT Security with TLS
  • MQTT-Based Smart Home Automation Using ESP32 and Node-RED

Conclusion

MQTT retained messages are one of the most useful features of the MQTT protocol. By allowing the broker to store the latest message for a topic, new subscribers can immediately receive the current state without waiting for another update.

Whether you’re building smart home systems, industrial monitoring solutions, or ESP32-based IoT projects, retained messages help ensure that dashboards, devices, and applications always have access to the most recent information.

Understanding retained messages early will make your MQTT applications more reliable, responsive, and easier to manage.

Frequently Asked Questions

What is a retained message in MQTT?

A retained message is the last message stored by the MQTT broker for a topic. New subscribers automatically receive this message when they subscribe.

Does Mosquitto support retained messages?

Yes. Eclipse Mosquitto fully supports MQTT retained messages.

Are retained messages stored permanently?

They remain stored until a new retained message replaces them or the retained message is cleared.

Can ESP32 publish retained messages?

Yes. Libraries such as PubSubClient allow ESP32 devices to publish retained messages.

Should sensor data be retained?

Only if subscribers need the latest reading immediately after connecting.

How do I delete a retained message?

Publish an empty retained message using:

mosquitto_pub -t topic/name -n -r

Related MQTT Tutorials:


1 Comment

Leave a Reply

Your email address will not be published. Required fields are marked *