How to filter AWS SNS messages while publishing to a topic

AWS SNS is a pub/sub service and widely used for sending notifications to people, machines and devices. You might have configured billing alerts or Cloud watch alarm notifications on your account; delivery of these notifications is handled by SNS. This service mainly consists of Topics and subscribers. One topic can have multiple subscribers and when we publish a message to a topic then all the subscribers will receive the message. Earlier if we wanted to send certain messages to only a set of subscribers then we needed to create separate topics for each set of subscribers; this was an additional complexity at the application layer to have the routing logic and also more topic to manage.

Let me illustrate the problem with an example: let us say we want to send normal alarm notifications to “normal-alerts@tensult.com” and critical alarms notifications to “critical-alerts@tensult.com” then we needed to create two separate topics and send messages respectively. But what if we want to send all the messages to a single topic and based on the message attributes we want to decide to whom this message should be delivered, this was earlier not possible with SNS but now possible as AWS SNS released a new feature called Message filtering, using this feature. In our example, we can add a message attribute called “critical” to all the Critical alert notifications and when the message has an attribute with name “critical” as true then we can deliver them to only “critical-alerts@tensult.com” otherwise to “normal-alerts@tensult.com”.

Ideally, if we can just use the message’s subject to filter then it would have been wonderful but currently, this feature only supports filtering based on the message attributes.

Experiment

  1. To test this feature I have created one test topic and subscribed “critical-alerts@tensult.com” and “normal-alerts@tensult.com” to the topic.
Topic details

2. Let us define subscription filter policy.

Click on Edit subscription filter policy
Set subscription filter policy

3. Similarly, we need to do other subscription by setting “critical” to false.

4. Test by sending one message with the “critical” attribute is true and other with false.

Publishing a critical message
critical-alerts@tensult.com got the critical message

5. This message is not delivered to “normal-alerts@tensult.com”.

6. Similarly, test with a non-critical message and verify that it is only delivered to “normal-alerts” but not “critical-alerts”.

Conclusion

You have learned how AWS SNS subscription filter works and we have performed a small experiment successfully. I hope this will help you to understand the concept well. In case you have any queries please leave a message to me and don’t forget to follow me for more updates.