Amazon SNS via SDK: Your First Topic
Amazon SNS is a pub/sub service: publish one message to a topic and it fans out to every subscriber.
Busca en todas las páginas de la documentación
Amazon SNS is a pub/sub service: publish one message to a topic and it fans out to every subscriber.
This page creates a topic, subscribes two different endpoints to it, publishes a message that reaches both, then cleans up. It is the push half of AWS messaging - SQS is the pull half.
Quick-reference recipe card - copy-paste ready.
# --- Python (boto3) ---
import boto3
sns = boto3.client("sns", region_name="us-east-1")
arn = sns.create_topic(Name="order-events")["TopicArn"]
sns.publish(TopicArn=arn, Subject="Order", Message="order o-100 placed")
print("published to", arn)// --- TypeScript (AWS SDK v3) ---
import { SNSClient, CreateTopicCommand, PublishCommand } from "@aws-sdk/client-sns";
const sns = new SNSClient({ region: "us-east-1" });
const { TopicArn } = await sns.send(new CreateTopicCommand({ Name: "order-events" }));
await sns.send(new PublishCommand({ TopicArn, Subject: "Order", Message: "order o-100 placed" }));
console.log("published to", TopicArn);When to reach for this:
Create a topic, subscribe an email address and an SQS queue, publish a message that fans out to both, list the subscriptions, then delete the topic.
# --- Python (boto3) ---
import boto3
sns = boto3.client("sns", region_name="us-east-1")
# 1. Create the topic (idempotent - same name, same ARN).
arn = sns.create_topic(Name="order-events")["TopicArn"]
# 2. Subscribe two endpoints. Email must be confirmed by the recipient;
# SQS is confirmed automatically.
sns.subscribe(TopicArn=arn, Protocol="email", Endpoint="ops@example.com")
sns.subscribe(TopicArn=arn, Protocol="sqs",
Endpoint="arn:aws:sqs:us-east-1:111122223333:order-queue")
# 3. Publish once; SNS delivers a copy to every confirmed subscriber.
sns.publish(TopicArn=arn, Subject="Order placed",
Message="order o-100 placed",
MessageAttributes={"eventType": {"DataType": "String", "StringValue": "placed"}})
# 4. Inspect subscriptions, then clean up.
subs = sns.list_subscriptions_by_topic(TopicArn=arn)["Subscriptions"]
print([(s["Protocol"], s["SubscriptionArn"]) for s in subs])
sns.delete_topic(TopicArn=arn)// --- TypeScript (AWS SDK v3) ---
import {
SNSClient, CreateTopicCommand, SubscribeCommand, PublishCommand,
ListSubscriptionsByTopicCommand, DeleteTopicCommand,
} from "@aws-sdk/client-sns";
const sns = new SNSClient({ region: "us-east-1" });
// 1. Create the topic (idempotent - same name, same ARN).
const { TopicArn } = await sns.send(new CreateTopicCommand({ Name: "order-events" }));
// 2. Subscribe two endpoints. Email must be confirmed by the recipient;
// SQS is confirmed automatically.
await sns.send(new SubscribeCommand({ TopicArn, Protocol: "email", Endpoint: "ops@example.com" }));
await sns.send(new SubscribeCommand({ TopicArn, Protocol: "sqs",
Endpoint: "arn:aws:sqs:us-east-1:111122223333:order-queue" }));
// 3. Publish once; SNS delivers a copy to every confirmed subscriber.
await sns.send(new PublishCommand({ TopicArn, Subject: "Order placed",
Message: "order o-100 placed",
MessageAttributes: { eventType: { DataType: "String", StringValue: "placed" } } }));
// 4. Inspect subscriptions, then clean up.
const out = await sns.send(new ListSubscriptionsByTopicCommand({ TopicArn }));
console.log((out.Subscriptions ?? []).map((s) => [s.Protocol, s.SubscriptionArn]));
await sns.send(new DeleteTopicCommand({ TopicArn }));What this demonstrates:
CreateTopic is idempotent, so re-running returns the existing topic's ARN.email, sqs, lambda, https) subscribe to the same topic.Publish fans out to every confirmed subscriber.PendingConfirmation until the recipient confirms; SQS and Lambda subscriptions confirm automatically.A filter policy lets one subscriber receive only messages whose attributes match, so you do not need a topic per event type.
# --- Python (boto3) ---
import json
# This subscription only receives messages where eventType == "placed".
sns.set_subscription_attributes(
SubscriptionArn="arn:aws:sns:us-east-1:111122223333:order-events:sub-id",
AttributeName="FilterPolicy",
AttributeValue=json.dumps({"eventType": ["placed"]}),
)// --- TypeScript (AWS SDK v3) ---
import { SetSubscriptionAttributesCommand } from "@aws-sdk/client-sns";
// This subscription only receives messages where eventType == "placed".
await sns.send(new SetSubscriptionAttributesCommand({
SubscriptionArn: "arn:aws:sns:us-east-1:111122223333:order-events:sub-id",
AttributeName: "FilterPolicy",
AttributeValue: JSON.stringify({ eventType: ["placed"] }),
}));With filter policies, one topic serves many event types and each subscriber gets only its slice.
The classic design is SNS to multiple SQS queues: one publish, several durable queues, each drained by its own worker at its own pace. This combines SNS fan-out with SQS buffering and is the backbone of many event-driven systems.
PendingConfirmation until confirmed. Fix: have the recipient click the confirmation link before publishing.sns.amazonaws.com permission to SendMessage.| Alternative | Use When | Don't Use When |
|---|---|---|
| SNS (this page) | Push one message to many subscribers | One worker should pull and process each message |
| SQS | Durable buffering for a single consumer group | You need immediate fan-out to many endpoints |
| SNS + SQS fan-out | Many durable consumers of one event | A single simple notification |
| EventBridge | Rich event routing, schemas, many AWS sources | Simple pub/sub to a few endpoints |
| Kinesis / Kafka | High-throughput ordered streaming and replay | Low-volume notifications |
SNS pushes a copy of each message to every subscriber (fan-out). SQS holds messages in a queue for a worker to pull when ready (buffering). They are complementary, not substitutes.
Yes. It is idempotent: calling it with the same name returns the existing topic's ARN rather than erroring or creating a duplicate.
Email subscriptions must be confirmed first and stay in PendingConfirmation until the recipient clicks the confirmation link. Messages published before confirmation are not delivered to them.
No. Unlike email and HTTPS, SQS and Lambda subscriptions confirm automatically when created, so they can receive messages right away.
Set a FilterPolicy on the subscription and publish messages with matching MessageAttributes. Each subscriber then receives only the messages whose attributes satisfy its policy.
Publishing to an SNS topic that has several SQS queues subscribed. One publish reaches all queues, and each queue's worker processes at its own pace with durable buffering.
The queue needs a policy allowing the SNS service (sns.amazonaws.com) to SendMessage to it. Without that permission, SNS delivery to the queue is denied.
Standard topics do not. If you need strict ordering and exactly-once delivery, use a FIFO topic paired with a FIFO queue.
It is best-effort with retries. For durability and replay, subscribe an SQS queue so messages persist until a worker processes and deletes them.
Yes. Set the alarm's AlarmActions to a topic ARN. When the alarm fires, CloudWatch publishes to the topic, which then notifies all subscribers.
Stack versions: This page was written for boto3 1.43.x (Python 3.10+) and the AWS SDK for JavaScript v3 (Node.js 18+).
Revisado por Chris St. John·Última actualización: 24 jul 2026