Simple AWS: Using SNS to Decouple Components
What is SNS and how it's used to decouple components. Some cool tips for SNS, a fantastic tool, and a haiku.

Guille Ojeda
December 26, 2022
AWS Service: Amazon SNS
tl;dr: SNS is a managed publish-subscribe service. The whole idea of the publish-subscribe model is that producers send messages to topics and consumers subscribe to those topics to receive the messages. In SNS you create a topic, subscribe to it, and when a producer publishes a message to it, SNS automatically delivers the message to all of the subscribers of that topic. Subscribers can be email addresses, phone numbers (using SMS), HTTPS endpoints, application endpoints (other protocols), Lambda functions (directly invoked), SQS queues, Kinesis streams or ECS services.
In the last issue we discussed a bit about event-driven architectures. SNS fits in there too, acting as a central hub over which different components communicate. Publishers don't know anything about consumers, so those components are decoupled. Also, since multiple consumers can subscribe to a topic, SNS is used to "fan out" a message (i.e. get it to many subscribers).

Cool things that you can do with SNS:
Filter messages based on attributes
Use separate topics for different delivery policies
Set up message retries
Actionable tips
SNS can be used to send SMS messages to phones. It's not the cheapest option ($0.00847/message (US) vs $0.0079/message (US) of Twilio), but it's super simple to set up.
You can trigger Lambda functions when messages are published to a topic. Great for serverless workflows and event-driven architectures!
Use SNS to fan out messages to multiple recipients. For example, instead of having Service A send a message to Service B and to Service C, you can send the message to an SNS topic where Services B, C and maybe others are subscribed to. Every subscriber gets a copy of the message.
You can send cross-account messages!
If some consumers are not guaranteed to be able to handle the message right away, you should add an SQS queue between the SNS topic and the consumer. The queue is subscribed to the topic, and the consumer reads from the queue. Like this: Producer --> SNS topic --> SQS queue --> Consumer. Why use SNS then? To fan out the message to multiple consumers (maybe multiple queues!).
Did you like this issue? |