Sub topic 10
Amazon SNS topics and publishing messages
This chapter assumes you know basic AWS concepts (accounts, regions, IAM), can read JSON, and can follow Python with boto3. It also assumes you have met SQS queues from the earlier chapters.
What a topic is
Amazon SNS (Simple Notification Service) is a publish/subscribe service. A topic is a named channel. A producer publishes a message to the topic, and SNS pushes a copy to every subscriber of that topic. The producer does not know who the subscribers are or how many there are.
This differs from SQS. An SQS queue holds messages until a consumer pulls them, and each message goes to one consumer. An SNS topic does not store messages for later pickup. It delivers them to subscribers right away, so a topic with no subscribers drops the message.
Creating a topic
Create a topic with create_topic. The call is idempotent: if a topic with the same name and attributes exists, SNS returns its ARN (Amazon Resource Name, the unique identifier) instead of failing.
import boto3
sns = boto3.client("sns")
topic_arn = sns.create_topic(Name="order-events")["TopicArn"]
print(topic_arn)Topic names can contain letters, numbers, hyphens, and underscores. A FIFO topic needs a name ending in .fifo. Standard topics are the default and are the focus here.
Publishing a message
Use publish with the topic ARN and a message. A message can be up to 256 KB. The message body is a string, so JSON must be serialized first.
import json
import boto3
sns = boto3.client("sns")
topic_arn = sns.create_topic(Name="order-events")["TopicArn"]
response = sns.publish(
TopicArn=topic_arn,
Subject="Order created",
Message=json.dumps({"orderId": "1001", "total": 25}),
MessageAttributes={
"eventType": {"DataType": "String", "StringValue": "order_created"}
},
)
print(response["MessageId"])The parts of a publish call:
| Field | Purpose |
|---|---|
| `Message` | The payload, delivered to every subscriber. |
| `Subject` | Optional. Used as the subject line for email subscribers. |
| `MessageAttributes` | Typed key-value metadata. Filter policies match on these. |
| `MessageId` | Returned by SNS. It identifies the published message. |
Put routing information, such as an event type, in message attributes and not in the body. SNS can filter on attributes without parsing your payload.
Publishing in batches
publish_batch sends up to 10 messages in one request, which reduces the number of API calls. Each entry needs an Id that is unique within the batch. The response lists successes and failures separately, so check Failed.
import json
import boto3
sns = boto3.client("sns")
topic_arn = sns.create_topic(Name="order-events")["TopicArn"]
entries = [
{"Id": str(i), "Message": json.dumps({"orderId": str(1000 + i)})}
for i in range(3)
]
result = sns.publish_batch(TopicArn=topic_arn, PublishBatchRequestEntries=entries)
if result["Failed"]:
print("failed:", result["Failed"])Common errors
- Message published but nobody receives it. The topic has no subscriptions yet, or a filter policy excludes the message.
AuthorizationError. The caller's IAM identity lackssns:Publishon the topic.- Wrong region. A topic ARN includes its region, and the client must use the same region.
- Invalid parameter on publish. Message attribute
DataTypeis missing or the string value is empty.
Exercise
A producer publishes a message to an SNS topic that has no subscriptions. What happens to the message, and how does this differ from sending a message to an SQS queue with no consumers?
Show answer
SNS accepts the publish but has nobody to deliver to, so the message is dropped. SNS does not store it for later subscribers. An SQS queue keeps the message until a consumer receives it or the retention period ends.