SNS

SNS stands for Simple Notification Service, it's a fully managed messaging service that allows you to send messages to various endpoints, including mobile devices, email, SMS, and HTTP endpoints. It can also deliver messages to SQS queues or invoke Lambda functions.

Topics, Subscriptions, and Publishing

SNS works like a message queue, which has topics, subscribers, and publishers.

Creating a Topic

To create a topic via awscli:

aws sns create-topic --name topic0

This will return an ARN:

arn:aws:sns:us-east-1:<account>:topic0

Subscribing

First, install the SDK:

bun add @aws-sdk/client-sns

Next, create a file named subscribe.ts with the following content:

import { SNSClient, SubscribeCommand } from "@aws-sdk/client-sns"

const sns = new SNSClient({})

const params = {
  TopicArn: "arn:aws:sns:us-east-1:Software Engineer:topic0",
  Protocol: "email",
  Endpoint: "<youremail>",
}

const command = new SubscribeCommand(params)

const data = await sns.send(command)
console.log("Subscription created successfully:", data.SubscriptionArn)

Run it using bun subscribe.ts.

You will receive an "AWS Notification - Subscription Confirmation" email, and you need to confirm it.

Publishing Messages

Next, create a file named publish.ts with the following content:

import { SNSClient, PublishCommand } from "@aws-sdk/client-sns"

const client = new SNSClient({})

const params = {
  TopicArn: "arn:aws:sns:us-east-1:112233445566:topic0",
  Message: "Hello from SNS!",
}

const data = await client.send(new PublishCommand(params))
console.log("Message published successfully:", data.MessageId)

Run it using bun publish.ts.

You should receive an email with the expected content.

This really saved a lot of trouble in managing subscriptions and the need to adapt to different transports, not to mention other benefits like scalability and reliability.