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 “firstname.lastname@example.org” and critical alarms notifications to “email@example.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 “firstname.lastname@example.org” otherwise to “email@example.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.
- To test this feature I have created one test topic and subscribed “firstname.lastname@example.org” and “email@example.com” to the topic.
2. Let us define 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.
5. This message is not delivered to “firstname.lastname@example.org”.
6. Similarly, test with a non-critical message and verify that it is only delivered to “normal-alerts” but not “critical-alerts”.
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.