Amazon SNS

I want to read more about Amazon's SNS because I need to use it to implement push notifications for this site.

Date Created:
1 31

References



Notes


Fully managed Pub/Sub service for A2A and A2P messaging.
Amazon Simple Notification Service (Amazon SNS) is a managed service that provides message delivery from publishers to subscribers (also known as producers and consumers). Publishers communicate asynchronously with subscribers by sending messages to a topic, which is a logical access point and communication channel. Clients can subscribe to the Amazon SNS topic and receive published messages using a supported endpoint type, such as Amazon Data Firehose, Amazon SQS, AWS Lambda, HTTP, email, mobile push notifications, and mobile text messages.

Amazon SNS

Benefits

  • Application-to-Application (A2A) Notifications
    • Deliver A2A notifications to integrate and decouple distributed applications.
  • Application-to-Person (A2P) notifications
    • Distribute A2P notifications to your customers with SMS texts, push notifications, and email
  • Simplify Your Architecture
    • Simplify your architecture and reduce costs with message filtering, ordering, and deduplication
  • Increase Message Durability
    • Increase message durability with archiving, replay, delivery retries, and dead-letter queues (DLQs)

Use Cases

  • Integrate Your Applications with FIFO Messaging
    • Deliver messages in a strictly-ordered, first in, first out (FIFO) manner to maintain accuracy and consistency across independent applications
  • Securely Encrypt Notification Message Delivery
    • Encrypt messages with AWS Key Management Service (KMS), ensure traffic privacy with AWS PrivateLink, and control access with resource priorities and tags.
  • Capture Fan Out Events form over 60 AWS Services
    • Fan out events across AWS categories, such as analytics, compute, containers, databases, IoT, machine learning (ML), security, and storage
  • Send SMS texts to Customers Across 240 Countries
    • Use worldwide SMS, with redundancy across providers. Set SMS origination identify with sender ID, long code, short code, TFN, or 100LC.

Features


Typic Types

Standard Topics

Standard topics can be used in many scenarios, as long as your application can process messages that arrive more than once and out of order, for example: fanning out messages to media encoding, fraud detection, tax calculation, search index, and critical alerting applications.

  • Maximum Throughput: Standard topics support a nearly unlimited number of messages per second
  • Best-effort ordering: Occasionally, messages might be delivered in an order different from which they were published
  • Best-effort deduplication: A message is delivered at least once, but occasionally more than one copy of a message is delivered
  • Multiple subscription types: Messages can be delivered to A2A endpoints as well as S2P endpoints
  • Message format: Each account can support 100,000 Standard topics and each topic supports up to 12.5M subscriptions

FIFO Topics

FIFO topics are designed to enhance messaging between applications when the order of operations and events is critical, or where duplicates can't be tolerated, for example: fanning out messages to bank transaction logging, stock monitoring, flight tracking, inventory management, and price update applications.

  • High throughput: FIFO topics support up to 3,000 messages per second or 10 MB per second per FIFO topic (whichever comes first)
  • Strict ordering: The order in which messages are published and delivered is strictly preserved (FIFO)
  • Strict deduplication: Duplicate messages aren't delivered. Duplication happens within a 5-minute interval, form the message publish time.
  • SQS subscriptions: Messages can be delivered to Amazon SQS queues.
  • Message format: Each account can support 1,000 DIDO topics and each topic supports up to 100 subscriptions.

Event sources and Destinations

Event-driven computing is a model in which subscriber services automatically perform work in response to events triggered by publisher services. This paradigm can be applied to automate workflows while decoupling the services that collectively and independently work to fulfill these workflows. Amazon SNS is an event-driven hub that has native integration with a wide-variety of AWS event sources and event destinations.

Event Driven Computing

Message Publishing and Batching

Message publishing enables you to send data, in the form of messages, to an Amazon SNS topic which delivers the messages asynchronously to the applications that are subscribed to the topic. You can publish 1 to 10 messages per API request. You may choose to batch messages together to reduce your Amazon SNS costs. Each message can contain up to 256 kB of data.

Message Filtering

Message filtering empowers your subscriber applications to create filter policies, so that these applications can receive only the notifications that they are interested in, as opposed to receiving every message published to the topic. This enables you to simplify your architecture, offloading the message filtering logic from subscriber applications as well as the message routing logic from publisher applications.

Message Fanout and Delivery

When you publish a message to a topic, Amazon SNS replicates and delivers the message to applications subscribed to the topic. Amazon SNS supports A2A and A2P message delivery. Amazon SNS also supports cross-region and cross-account message delivery, in addition to message delivery status logging with Amazon CloudWatch.

Message Durability

Amazon SNS uses a number of mechanisms that work together to provide message durability. To start, published messages are stored across multiple, geographically-separated servers and data centers. If a subscribed endpoint isn't available, Amazon SNS executes a message delivery retry policy. To preserve any messages that aren't delivered before the delivery retry policy ends, you can use a dead-letter queue powered by Amazon SQS.

Message Encryption

Amazon SNS provides encryption topics to protect your messages from unauthorized and anonymous access. When you publish messages to encrypted topics, Amazon SNS immediately encrypts your messages.

Mobile Push Notifications

Amazon SNS mobile notifications make it simple and cost effective to fan out mobile push notifications to iOS, Android, Fire, Windows, and Baidu devices. Mobile notifications can be triggered from user-driven actions or business logic.


Pricing


With Amazon Simple Notification Service (SNS), there are no upfront fees, no required minimum commitments, and no long-term contracts. You pay only for what you use, based on type of topic used.

Notification Delivery Prices

Standard Topic API Requests

Every publish, publish batch, topic owner operation, and subscription owner operation counts as a request.

FIFO Topic API Requests

API requests for publishing messages to FIFO topics are charged at FIFO rates. All other API requests are charged at standard rates.

Payload Size

For Standard topics, each 64 KB chunk of a payload is billed as 1 request. For FIFO topics, each message up to 256 KB is billed as one message with a minimum of 1 KB, in addition to the charge per GB of payload data.

Extending Payload Size with Amazon S3

For Standard topics, when using the Amazon SNS Extended Client Library to send payloads using Amazon Simple Storage Service (Amazon S3), you incur Amazon S3 charges for any Amazon S3 storage you use to send message payloads.

Interaction with AWS KMS

For Standard and FIFO topics, when using the AWS Key Management Service (AWS KMS) to manage keys for Amazon SNS server-side encryption, you incur AWS KMS charges. For more information see AWS KMS pricing and How Do I Estimate My AWS KMS Usage Costs in the Amazon SNS Developer Guide.


Creating an Amazon SNS Topic


Topic Creation

An Amazon SNS topic is a logical access point that acts as a communication channel. A topic lets you group multiple endpoints (such as AWS Lambda, Amazon SQS, HTTP/S, or an email address). To broadcast the messages of a message-produced system working with multiple other services that require its messages, you can create a topic for your producer system.

The first and most common Amazon SNS task is creating a topic. Suring creation, you can choose the topic type and name the topic. After creating the topic, you can't change the topic type or name. All other configuration choices are optional during topic creation, and you can edit them later.

Creating a topic in Amazon SNS establishes the foundation for message distribution, enabling you to publish messages that can be fanned out to multiple subscribers. This step is essential to configure the topic's type, encryption settings, access points, ensuring the topic meets the organization's security, compliance, and operational requirements.

import { SNSClient } from "@aws-sdk/client-sns";
import { CreateTopicCommand } from "@aws-sdk/client-sns";
import { snsClient } from "../libs/snsClient.js";

// The AWS Region can be provided here using the `region` property. If you leave it blank
// the SDK will default to the region set in your AWS config.
export const snsClient = new SNSClient({});

/**
* @param {string} topicName - The name of the topic to create.
*/
export const createTopic = async (topicName = "TOPIC_NAME") => {
const response = await snsClient.send(
new CreateTopicCommand({ Name: topicName }),
);
console.log(response);
// {
// '$metadata': {
// httpStatusCode: 200,
// requestId: '087b8ad2-4593-50c4-a496-d7e90b82cf3e',
// extendedRequestId: undefined,
// cfId: undefined,
// attempts: 1,
// totalRetryDelay: 0
// },
// TopicArn: 'arn:aws:sns:us-east-1:xxxxxxxxxxxx:TOPIC_NAME'
// }
return response;
};

Subscribing an Endpoint to an Amazon SNS Topic

Subscribing an endpoint to an Amazon SNS topic enables message delivery to the specified endpoint, ensuring the right systems or users receive notifications when a message is published to the topic. This step is essential for linking the topic to consumers - whether they are applications, email recipients, or other services - allowing for seamless communication across systems.

Publishing a Message

After you create an Amazon SNS topic and subscribe an endpoint to it, you can publish messages to the topic. When a message is published, Amazon SNS attempts to deliver the message to the subscribed endpoints.

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

// The AWS Region can be provided here using the `region` property. If you leave it blank
// the SDK will default to the region set in your AWS config.
export const snsClient = new SNSClient({});


/**
* @param {string | Record<string, any>} message - The message to send. Can be a plain string or an object
* if you are using the `json` `MessageStructure`.
* @param {string} topicArn - The ARN of the topic to which you would like to publish.
*/
export const publish = async (
message = "Hello from SNS!",
topicArn = "TOPIC_ARN",
) => {
const response = await snsClient.send(
new PublishCommand({
Message: message,
TopicArn: topicArn,
}),
);
console.log(response);
// {
// '$metadata': {
// httpStatusCode: 200,
// requestId: 'e7f77526-e295-5325-9ee4-281a43ad1f05',
// extendedRequestId: undefined,
// cfId: undefined,
// attempts: 1,
// totalRetryDelay: 0
// },
// MessageId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
// }
return response;
};

async publishMessages() {
const message = await this.prompter.input({
message: MESSAGES.publishMessagePrompt,
});

let groupId;
let deduplicationId;
let choices;

if (this.isFifo) {
await this.logger.log(MESSAGES.groupIdNotice);
groupId = await this.prompter.input({
message: MESSAGES.groupIdPrompt,
});

if (this.autoDedup === false) {
await this.logger.log(MESSAGES.deduplicationIdNotice);
deduplicationId = await this.prompter.input({
message: MESSAGES.deduplicationIdPrompt,
});
}

choices = await this.prompter.checkbox({
message: MESSAGES.messageAttributesPrompt,
choices: toneChoices,
});
}

await this.snsClient.send(
new PublishCommand({
TopicArn: this.topicArn,
Message: message,
...(groupId
? {
MessageGroupId: groupId,
}
: {}),
...(deduplicationId
? {
MessageDeduplicationId: deduplicationId,
}
: {}),
...(choices
? {
MessageAttributes: {
tone: {
DataType: "String.Array",
StringValue: JSON.stringify(choices),
},
},
}
: {}),
}),
);

const publishAnother = await this.prompter.confirm({
message: MESSAGES.publishAnother,
});

if (publishAnother) {
await this.publishMessages();
}
}





Amazon SNS Message Filtering


By default, an Amazon SNS topic subscriber receives every message that's published to the topic. To receive only a subset of the messages, a subscriber must assign a filter policy to the topic subscription. A filter policy is a JSON object containing properties that define which messages the subscriber receives. Amazon SNS supports policies that act on the message attributes or on the message body, according to the filter policy scope that you set for the subscription. Filter policies for the message body assume that the message payload is a well-formed JSON object. If a subscription doesn't have a filter policy, the subscriber receives every message published to its topic. When you publish a message to a topic with a filter policy in place, Amazon SNS compares the message attributes or the message body to the properties in the filter policy for each of the topic's subscriptions.


Other Resources


Comments

You have to be logged in to add a comment

User Comments

Frank Frank

A good YouTube Playlist on Amazon SNS:


2

Insert Math Markup

ESC
About Inserting Math Content
Display Style:

Embed News Content

ESC
About Embedding News Content

Embed Youtube Video

ESC
Embedding Youtube Videos

Embed TikTok Video

ESC
Embedding TikTok Videos

Embed X Post

ESC
Embedding X Posts

Embed Instagram Post

ESC
Embedding Instagram Posts

Insert Details Element

ESC

Example Output:

Summary Title
You will be able to insert content here after confirming the title of the <details> element.

Insert Table

ESC
Customization
Align:
Preview:

Insert Horizontal Rule

#000000

Preview:


View Content At Different Sizes

ESC

Edit Style of Block Nodes

ESC

Edit the background color, default text color, margin, padding, and border of block nodes. Editable block nodes include paragraphs, headers, and lists.

#ffffff
#000000

Edit Selected Cells

Change the background color, vertical align, and borders of the cells in the current selection.

#ffffff
Vertical Align:
Border
#000000
Border Style:

Edit Table

ESC
Customization:
Align:

Upload Lexical State

ESC

Upload a .lexical file. If the file type matches the type of the current editor, then a preview will be shown below the file input.

Upload 3D Object

ESC

Upload Jupyter Notebook

ESC

Upload a Jupyter notebook and embed the resulting HTML in the text editor.

Insert Custom HTML

ESC

Edit Image Background Color

ESC
#ffffff

Insert Columns Layout

ESC
Column Type:

Select Code Language

ESC
Select Coding Language

Insert Chart

ESC

Use the search box below

Upload Previous Version of Article State

ESC