Clearing retained messages in mosquitto
PurposeThe purpose of this tutorial is to present solutions to clear retained messages in the Eclipse Mosquitto MQTT Broker.
Retained messages can be troublesome and/or unwanted. Many mosquitto tutorials included a retain option in the configuration and setup of mosquitto. This is likely to create problems in the future.
This tutorial is created for Linux users with a package installation on mosquitto.
Other users will have to find the files and paths relevant to their system.
Clearing ALL retained messages
First we have to stop the mosquitto broker.
sudo systemctl stop mosquitto.service
sudo service mosquitto stop
mosquitto.dbcontaining all the stored message data in the persistence. By default, located in
sudo rm /var/lib/mosquitto/mosquitto.db
Restart the mosquitto service
sudo systemctl start mosquitto.service
sudo service mosquitto start
Clearing SPECIFIC retained messages
In some cases some retained messages can be wanted and we don’t want to clear all the retained messages.
The messages will have to be cleared one by one using the topic
To clear a specific message:
mosquitto_pub -h hostname -t the/topic -n -r -d
If your broker is setup with a username and password then use:
mosquitto_pub -h hostname -t the/topic -u username -P password -n -r -d
- Replace the hostname with the hostname or IP address of your broker (e.g.
- Replace the/topic with the topic that you want the retained messages cleared for
- Replace the username and password with… Well you know…
Options used in the mosquitto_pub command:
-n= Send a null (zero length) message
-r= Retain the message as a “last known good” value on the broker
-d= Enable debug messages
I hope this is useful.
I have made this thread a wiki so please don’t hesitate to make changes if you see a glaring error or you want to add other operating system instructions.