Sub topic 14
The fan-out pattern: one event, many queues
This chapter assumes you can create an SQS queue and an SNS topic, and that you know visibility timeouts and dead-letter queues from earlier chapters. You also need an IAM identity that can call SNS and SQS in one account and region.
What fan-out solves
Suppose an order service must tell three systems that an order was created: billing, inventory, and a notification sender. If the order service calls each one, it needs to know all three. It also waits on the slowest one, and it must handle a failure in each. Adding a fourth consumer means changing the producer.
In the fan-out pattern, the producer publishes one message to an SNS topic. Each consumer owns an SQS queue subscribed to that topic. SNS copies the message into every subscribed queue. Each consumer then reads from its own queue at its own pace.
Why queues instead of direct subscribers
SNS can push to Lambda or an HTTP endpoint directly. Putting a queue between the topic and the consumer gives you several properties:
- Buffering. If the consumer is slow or down, messages wait in the queue up to the retention period.
- Isolation. Each queue has its own visibility timeout, retention, and dead-letter queue. A poison message in the billing queue does not affect inventory.
- Independent scaling. Each consumer controls its own batch size and concurrency.
- Easy additions. A new consumer creates a queue and subscribes it. The producer does not change.
The three pieces you must configure
A working fan-out needs three things for each queue:
- A queue that exists.
- A queue access policy that lets the topic call
sqs:SendMessage. - A subscription from the topic to the queue's ARN.
The second piece is the usual source of silent failure. SNS is a separate service, so it has no permission to write to your queue unless the queue's resource policy grants it. Scope the policy with an aws:SourceArn condition so that only your topic can send, not any SNS topic.
A complete example
The following script creates two queues and one topic. It attaches the access policy to each queue and subscribes each queue with its own filter. Billing receives only order_created events. Inventory receives both order_created and order_cancelled.
import json
import boto3
sqs = boto3.client("sqs")
sns = boto3.client("sns")
topic_arn = sns.create_topic(Name="order-events")["TopicArn"]
def make_queue(name):
url = sqs.create_queue(QueueName=name)["QueueUrl"]
arn = sqs.get_queue_attributes(
QueueUrl=url, AttributeNames=["QueueArn"]
)["Attributes"]["QueueArn"]
return url, arn
def allow_topic(queue_url, queue_arn):
policy = {
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Principal": {"Service": "sns.amazonaws.com"},
"Action": "sqs:SendMessage",
"Resource": queue_arn,
"Condition": {"ArnEquals": {"aws:SourceArn": topic_arn}},
}],
}
sqs.set_queue_attributes(
QueueUrl=queue_url, Attributes={"Policy": json.dumps(policy)}
)
def subscribe(queue_arn, event_types):
sns.subscribe(
TopicArn=topic_arn,
Protocol="sqs",
Endpoint=queue_arn,
Attributes={
"RawMessageDelivery": "true",
"FilterPolicy": json.dumps({"eventType": event_types}),
},
)
billing_url, billing_arn = make_queue("billing")
inventory_url, inventory_arn = make_queue("inventory")
for url, arn in [(billing_url, billing_arn), (inventory_url, inventory_arn)]:
allow_topic(url, arn)
subscribe(billing_arn, ["order_created"])
subscribe(inventory_arn, ["order_created", "order_cancelled"])
sns.publish(
TopicArn=topic_arn,
Message=json.dumps({"orderId": "1001"}),
MessageAttributes={
"eventType": {"DataType": "String", "StringValue": "order_created"}
},
)After this runs, each queue holds one message with the body {"orderId": "1001"}. Publish an order_cancelled event and only the inventory queue receives it.
What each queue receives
SNS delivers a separate copy to each subscription, so deleting a message from one queue has no effect on the others. Each copy has its own message ID in SQS and its own receive count.
Without raw message delivery, the SQS message body is a JSON envelope. The envelope has fields such as Type, MessageId, TopicArn, Message, and MessageAttributes. Your original payload is a string inside the Message field, so the consumer must parse twice. The example sets RawMessageDelivery to true, which puts your payload directly in the body. Message attributes are then passed through as SQS message attributes. If a consumer already expects the envelope, switching this flag later breaks its parsing.
Common errors
| Symptom | Likely cause |
|---|---|
| Publish succeeds, queue stays empty | The queue policy is missing, or its `aws:SourceArn` does not match the topic ARN |
| One queue gets nothing, others work | The filter policy does not match the message attributes, or the publisher did not set them |
| Consumer crashes on `KeyError` after enabling raw delivery | The consumer still reads the envelope's `Message` field |
| Queue stops receiving after you enable KMS encryption | The KMS key policy does not allow `sns.amazonaws.com` to use the key |
| Subscribing a FIFO queue to a standard topic fails | FIFO queues need a FIFO topic |
Design notes
- Delivery is at least once on both sides, so each consumer must be idempotent.
- Give each consumer queue its own dead-letter queue. A dead-letter queue on the topic subscription only covers SNS failing to deliver to the queue, not consumer failures.
- Choose each queue's visibility timeout from its own consumer's processing time. Queues do not need matching settings.
- Cost scales with the number of subscriptions, since each delivery counts separately.
Exercise
You publish an order event to a topic with three subscribed queues. The billing consumer fails on the message repeatedly and it ends up in the billing dead-letter queue. What happens to the copies in the inventory and notification queues, and which setting controls when the billing copy moves to the dead-letter queue?
Show answer
The inventory and notification copies are unaffected. Each queue holds an independent copy with its own receive count, so they are processed and deleted normally. The billing copy moves to the dead-letter queue when its receive count exceeds maxReceiveCount in the billing queue's redrive policy.
Exercise
A new queue is subscribed to the topic and the subscription shows as confirmed, but no messages arrive. The publisher sets the right message attributes. Name two things to check first.
Show answer
First, check the queue's access policy: it must allow sns.amazonaws.com to call sqs:SendMessage, with an aws:SourceArn condition that matches the topic's ARN. Second, check the subscription's filter policy against the attributes the publisher sets. If the queue uses KMS, also check that the key policy allows SNS.