AWS IoT remove a Retained Message

The retained messages feature of AWS IoT is a great tool for making sure that your messages reach offline recipients whenever they come online. We’ve already seen how to send retained messages from a thing in a previous post. However, this feature has limitations. The max number of retained messages per account (as per the AWS IoT quotas) is 5000. While this limit is adjustable (by contacting AWS IoT support), it may still be a good practice to remove retained messages after their purpose is fulfilled.

How do you remove retained messages? It is quite simple. All you need to do is send an empty message/ null payload (with the retained flag) on the same topic. Let’s try this out. You can go to the MQTT Test Client on the AWS Console, and publish a retained message to test/topic.

You should be able to see this message in the ‘Retained messages’ tab under ‘Manage’.

Now, go back to the MQTT Test Client, and send a retained message to the same topic, with an empty (or null) payload (make sure that there is no space as well).

If you now check the Retained messages tab, you’ll see that the retained message on the particular topic has been removed.

The sending of null payload can also be done programmatically. For example, here’s how you’d do it in Nodejs, using the AWS IoT Device SDK.

let awsIot = require('aws-iot-device-sdk');

let HOST = 'your_aws_iot_url'
let TOPIC = 'topic_on_which_you_want_to_removed_retained_message'

let device = awsIot.device({
            host: HOST,
            protocol: 'wss',
        });

 device
.on('connect', async function () {
                console.log('connected. publishing to topic...');

                let pub_payload = null;
 //Null payload for removing retained message
                if(pub_payload == null){
                    await device.publish(TOPIC, pub_payload, { "qos": 0, "retain": true });
                }
                else{
                    await device.publish(TOPIC, JSON.stringify(pub_payload), { "qos": 0, "retain": true });
                }
                console.log('published!');
            });

I hope you liked this article. For more tutorials on AWS, check out https://iotespresso.com/category/aws/. Also, if you are planning to become a certified AWS Solutions Architect, I’d recommend that you check out this course on Udemy. I took this course and found the lectures to be lucid, to-the-point, and fun. I hope they will help you as well.

Leave a comment

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