Sub topic 3
The Fan-Out Pattern: One Event, Many Queues
Assume you know basic AWS, JSON, IAM, and Python. Amazon SNS sends an event to multiple subscribers. When each subscriber is an SQS queue, every service gets its own durable copy and can process it independently.
Fan-out, filtering, and message format
Create one subscription for each queue. The queue policy must allow sns.amazonaws.com to call sqs:SendMessage, and its aws:SourceArn condition should name only your topic.
A subscription filter policy limits delivery. For example, a subscriber can accept only messages whose eventType attribute is order_created. SNS does not deliver nonmatching messages to that subscriber.
By default, SNS places an envelope around the published message. The envelope contains fields such as the topic ARN, message ID, timestamp, and message body. Enable raw message delivery when the consumer should receive only the original body. Choose one format deliberately because consumers must parse the selected format.
Retries and failed subscribers
SNS retries delivery when an endpoint returns an error or cannot be reached. Configure a subscription dead-letter queue for messages that remain undeliverable. This queue is separate from an SQS consumer’s dead-letter queue. Inspect both when investigating failures.
Lambda consumers and partial failures
Lambda can poll an SQS queue through an event source mapping. Enable ReportBatchItemFailures, then return only failed message IDs:
def handler(event, context):
failures = []
for record in event["Records"]:
try:
process(record["body"])
except Exception:
failures.append({"itemIdentifier": record["messageId"]})
return {"batchItemFailures": failures}Successful messages are removed. Failed messages are retried. Make process idempotent because retries and duplicates remain possible.
Security and monitoring
Use server-side encryption for SQS queues and SNS topics. Use AWS-managed keys for simple setups or customer-managed KMS keys when you need key policies and audit control.
Monitor ApproximateNumberOfMessagesVisible, oldest-message age, Lambda errors, and dead-letter queue depth in CloudWatch. A growing age indicates that consumers cannot keep up. Any dead-letter activity needs investigation.
| Design | Use it when |
|---|---|
| SQS | Work must be buffered and processed by workers |
| SNS | One notification must reach many subscribers |
| SNS plus SQS | Each subscriber needs independent buffering, retries, and scaling |
Exercise
Why should billing and shipping use separate queues?
Show answer
Each service can process, retry, scale, and investigate its copy without blocking the other service.