Sub topic 11
Amazon SNS topics and publishing messages
This chapter assumes you can call AWS APIs with boto3 and have credentials configured. You should also know what an SQS queue is from the earlier chapters. By the end you will be able to create a topic, publish single and batched messages with attributes, and diagnose the most common publishing errors.
What a topic is
An Amazon SNS topic is a named channel that accepts messages from publishers and delivers a copy to every subscriber. A queue holds each message until one consumer takes it. A topic pushes each message to all current subscribers right away. SNS does not store messages for later pickup.
Two consequences follow from this:
- If a topic has no subscriptions when you publish, the message is dropped. The publish call still succeeds.
- A subscriber that joins later does not see earlier messages.
The publisher knows only the topic ARN. It does not know how many subscribers exist or what they do with the message.
Standard and FIFO topics
You choose the topic type when you create it, and you cannot change it later.
| Property | Standard topic | FIFO topic |
|---|---|---|
| Name | Any valid name | Must end in `.fifo` |
| Ordering | Best effort | Kept within a message group |
| Duplicates | Possible, so consumers must be idempotent | Removed within a 5-minute deduplication window |
| Subscriber protocols | SQS, Lambda, HTTP/S, email, SMS, mobile push | SQS (FIFO and standard queues) and, in current releases, Lambda and HTTPS |
| Publish requirement | Message only | `MessageGroupId` required |
Use a FIFO topic when subscribers depend on order or when duplicate events are costly. Use a standard topic otherwise, because it has higher throughput and supports more protocols. Check the current SNS documentation for the protocol list on FIFO topics, because it has grown over time.
Creating a topic
create_topic is idempotent. If a topic with the same name and attributes already exists, SNS returns its ARN instead of failing. This makes it safe to call at application startup.
import boto3
sns = boto3.client("sns")
# Standard topic
topic_arn = sns.create_topic(Name="order-events")["TopicArn"]
print(topic_arn)
# FIFO topic: the name must end in .fifo
fifo_arn = sns.create_topic(
Name="payment-events.fifo",
Attributes={
"FifoTopic": "true",
"ContentBasedDeduplication": "true",
},
)["TopicArn"]
print(fifo_arn)With ContentBasedDeduplication enabled, SNS builds the deduplication ID from a hash of the message body. Without it, you must pass MessageDeduplicationId on every publish.
Publishing a message
publish takes a topic ARN and a message string. SNS has no schema for the body. JSON is the usual choice, and you serialize it yourself.
The maximum message size is 256 KB. This limit counts the body and the attributes together. For larger payloads, store the data in S3 and publish a pointer to it.
Message attributes are typed key-value pairs that travel with the message. Subscription filter policies match on them, so set them if any subscriber will filter by them.
import json
import boto3
sns = boto3.client("sns")
topic_arn = sns.create_topic(Name="order-events")["TopicArn"]
response = sns.publish(
TopicArn=topic_arn,
Message=json.dumps({"orderId": "1001", "total": 49.90}),
Subject="Order created", # used by email subscribers
MessageAttributes={
"eventType": {"DataType": "String", "StringValue": "order_created"},
"region": {"DataType": "String", "StringValue": "eu-west-1"},
"priority": {"DataType": "Number", "StringValue": "2"},
},
)
print(response["MessageId"])The returned MessageId means SNS accepted the message. It does not mean any subscriber received it. Delivery happens afterward, and each protocol has its own retry behavior. A later chapter covers that.
Publishing to a FIFO topic
A FIFO publish needs a group ID. Messages in the same group are delivered in order. Messages in different groups can be delivered in parallel.
import json
import boto3
sns = boto3.client("sns")
fifo_arn = sns.create_topic(
Name="payment-events.fifo",
Attributes={"FifoTopic": "true", "ContentBasedDeduplication": "true"},
)["TopicArn"]
sns.publish(
TopicArn=fifo_arn,
Message=json.dumps({"paymentId": "p-1", "amount": 25}),
MessageGroupId="customer-42",
)Publishing in batches
publish_batch sends up to 10 messages in one API call. The total payload of the batch is also capped at 256 KB. Batching reduces the number of requests, and requests are what you pay for.
A batch is not atomic. Some entries can succeed while others fail, so you must inspect the response.
import json
import boto3
sns = boto3.client("sns")
topic_arn = sns.create_topic(Name="order-events")["TopicArn"]
entries = [
{
"Id": f"msg-{i}", # unique within this batch
"Message": json.dumps({"orderId": str(1000 + i)}),
"MessageAttributes": {
"eventType": {"DataType": "String", "StringValue": "order_created"}
},
}
for i in range(10)
]
result = sns.publish_batch(TopicArn=topic_arn, PublishBatchRequestEntries=entries)
for ok in result["Successful"]:
print("sent", ok["Id"], ok["MessageId"])
for bad in result["Failed"]:
print("failed", bad["Id"], bad["Code"], bad["Message"], bad["SenderFault"])If SenderFault is True, the entry itself is invalid, and retrying it unchanged will fail again. If it is False, the failure is on the service side, and a retry is reasonable.
Common errors
| Error | Likely cause | Fix |
|---|---|---|
| `AuthorizationError` | The caller's IAM policy lacks `sns:Publish` on the topic ARN, or the topic policy denies it | Grant `sns:Publish` on that ARN |
| `NotFound` | Wrong region or a mistyped ARN | Check that the client region matches the topic's region |
| `InvalidParameter` on a FIFO publish | Missing `MessageGroupId`, or missing deduplication ID without content-based deduplication | Add the missing parameter |
| `InvalidParameter` on attributes | Wrong `DataType`, or a non-numeric `StringValue` for `Number` | Match the type to the value |
| Publish succeeds but nothing arrives | No subscriptions yet, or a filter policy excludes the message | List subscriptions and compare the policy to your attributes |
Exercise
You publish an order event to a standard topic from a new service. The call returns a MessageId, but the downstream queue stays empty. Name two things to check.
Show answer
First, check that the queue is actually subscribed to the topic and that the subscription is confirmed. A topic with no subscriptions drops messages without any error. Second, check whether the subscription has a filter policy that does not match the message attributes you set, for example an eventType value that differs or attributes missing from the publish call. If both are fine, check that the queue's access policy allows the topic to send messages.
Exercise
A publish_batch call returns HTTP 200, but one of ten entries appears in Failed with SenderFault set to True. What should your code do with that entry?
Show answer
Do not retry it unchanged. SenderFault True means the entry itself is invalid, such as a bad attribute type or a missing group ID on a FIFO topic. Log the Code and Message, fix the entry, and publish it again. Entries in Successful need no action.