
Amazon SQS and SNS Explained: Build a Fan-Out Messaging System with the Console and CLI
Learn how Amazon SQS queues and SNS topics work, and how to combine them in the fan-out pattern. Build a working setup step by step using the AWS Management Console and the AWS CLI, with dead-letter queues, filter policies, best practices, and troubleshooting tips.
What are Amazon SQS and Amazon SNS?
Modern applications are easier to scale and maintain when their parts do not depend on each other directly. If your order service has to call the email service, the billing service, and the shipping service one by one, a slowdown in any of them slows down the whole order. Amazon SQS and Amazon SNS solve this by letting services communicate through messages.
- Amazon SQS (Simple Queue Service) is a fully managed message queue. A producer puts messages in the queue, and a consumer pulls them out and processes them at its own pace.
- Amazon SNS (Simple Notification Service) is a fully managed publish/subscribe (pub/sub) service. A publisher sends one message to a topic, and SNS pushes a copy to every subscriber.
In this article you will learn the core concepts of both services, how they work together in the fan-out pattern, and how to build a working example with the AWS Management Console and with the AWS CLI.
SQS vs SNS at a glance
- Model: SQS is a queue where one message is processed by one consumer. SNS is a topic where one message is delivered to many subscribers.
- Delivery: SQS uses pull (consumers poll the queue). SNS uses push (SNS delivers to the endpoints).
- Storage: SQS stores messages until they are processed or the retention period ends. SNS does not store messages for later pickup. It delivers them to the subscribers it has at publish time.
- Best for: SQS is best for buffering work and smoothing traffic spikes. SNS is best for broadcasting events and notifications.
- Together: SNS fans out an event to several SQS queues, and each queue feeds its own consumer.
Core SQS concepts
- Standard queue: nearly unlimited throughput, at-least-once delivery, and best-effort ordering. Your consumers must be able to handle an occasional duplicate message.
- FIFO queue: first-in-first-out ordering and exactly-once processing. The queue name must end with
.fifo. Use it when order matters, such as processing account transactions.
- Visibility timeout: when a consumer receives a message, the message is hidden from other consumers for a period (default 30 seconds). If the consumer does not delete the message in time, it becomes visible again and is retried.
- Message retention period: how long SQS keeps a message (default 4 days, configurable from 60 seconds to 14 days).
- Long polling: the consumer waits up to 20 seconds for a message to arrive instead of returning immediately. It reduces empty responses and cost.
- Delivery delay: an optional delay before a new message becomes visible.
- Dead-letter queue (DLQ): a separate queue that receives messages that failed processing too many times, so a bad message does not block the main queue.
- Encryption: server-side encryption with SQS-owned keys (SSE-SQS) is on by default for new queues. You can use an AWS KMS key instead.
Core SNS concepts
- Topic: the channel that publishers send messages to.
- Publisher: any application or AWS service that sends messages to a topic.
- Subscription: a connection between a topic and an endpoint that receives the messages.
- Supported endpoints: Amazon SQS, AWS Lambda, HTTP/HTTPS endpoints, email, SMS, mobile push, and Amazon Data Firehose.
- Message attributes: key-value metadata sent with a message, which subscription filters can use.
- Subscription filter policy: a JSON rule on a subscription so it only receives the messages it cares about.
- Raw message delivery: by default, SNS wraps your message in a JSON envelope. With raw delivery enabled on SQS or HTTP subscriptions, the subscriber gets exactly the message you published.
- Standard and FIFO topics: standard topics offer very high throughput. FIFO topics (names ending in
.fifo) preserve order and support deduplication.
The fan-out pattern
The most common way to combine the two services is fan-out:
- A publisher sends one event, such as "order created", to an SNS topic.
- SNS delivers a copy of the event to every subscribed SQS queue.
- Each queue has its own consumer, such as billing, shipping, or analytics, which processes the message independently.
Why this works well:
- The publisher does not know or care how many consumers exist. You can add a new consumer by adding a subscription, with no change to the publisher.
- Each queue buffers messages, so a slow or failing consumer does not affect the others.
- Each consumer can retry and use its own dead-letter queue.
What you will build
- A standard SQS queue named
orders-queuewith a dead-letter queue namedorders-dlq
- A standard SNS topic named
orders-topic
- A subscription that delivers messages from the topic to the queue
- A filter policy so the queue only receives
order_createdevents
- A test that publishes a message and receives it from the queue
Prerequisites
- An AWS account and permissions to manage SQS and SNS
- AWS CLI v2 configured with
aws configure(for the CLI section)
- A Region of your choice (the examples use
us-east-1)
Both services have a free tier and charge per request, so this demo costs very little. Delete the resources when you finish anyway (see the cleanup step).
Implementation with the AWS Management Console
Step 1: Create the dead-letter queue
- Open the Amazon SQS console and choose Create queue.
- Choose type Standard and name it
orders-dlq.
- Leave the other settings at their defaults and choose Create queue.
Step 2: Create the main queue
- Choose Create queue again.
- Choose type Standard and name it
orders-queue.
- Under Configuration, set Visibility timeout to 30 seconds, Message retention period to 4 days, Delivery delay to 0 seconds, and Receive message wait time to 20 seconds (this enables long polling).
- Leave Encryption at its default (server-side encryption with SQS-owned keys).
- Under Dead-letter queue, choose Enabled, select
orders-dlq, and set Maximum receives to 3.
- Choose Create queue.
Step 3: Create the SNS topic
- Open the Amazon SNS console, go to Topics, and choose Create topic.
- Choose type Standard and name it
orders-topic.
- Leave the other settings at their defaults and choose Create topic.
Step 4: Subscribe the queue to the topic
The easiest way is from the queue side, because the console can set up the permission for you:
- Open the SQS console and select
orders-queue.
- Open the SNS subscriptions tab and choose Subscribe to Amazon SNS topic.
- Select
orders-topicand save.
You can also subscribe from the SNS side: open the topic, choose Create subscription, select protocol Amazon SQS, and choose the queue as the endpoint.
After subscribing, open the queue's Access policy tab and confirm there is a statement that allows
sns.amazonaws.com to perform sqs:SendMessage from your topic. If it is missing, messages will not arrive, so add it (the CLI section shows the exact policy).Step 5: Enable raw message delivery
- In the SNS console, open
orders-topicand select the subscription for your queue.
- Choose Edit.
- Enable Raw message delivery and save.
Without raw delivery, the message in SQS is a JSON envelope that contains your text in a
Message field. With it, the queue receives exactly what you published.Step 6: Add a filter policy
- In the same subscription, choose Edit.
- Expand Subscription filter policy, choose the Message attributes scope, and enter the policy below.
- Save the changes.
{ "eventType": ["order_created"]}Step 7: Publish a test message
- Open
orders-topicand choose Publish message.
- Subject:
New order. Message body:{"orderId": "1001", "total": 49.99}.
- Under Message attributes, add an attribute: type String, name
eventType, valueorder_created.
- Choose Publish message.
Step 8: Receive the message
- In the SQS console, open
orders-queueand choose Send and receive messages.
- Choose Poll for messages.
- Open the message to see its body and attributes.
- Select the message and choose Delete when you are done with it. In a real application, the consumer deletes the message after processing it successfully.
Step 9: Test the filter
Publish a second message with
eventType set to order_cancelled . Poll the queue again. The message should not arrive, because it does not match the filter policy.Implementation with the AWS CLI
SQS commands live under
aws sqs , and SNS commands live under aws sns . Set the variables first:export AWS_REGION=us-east-1export ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)Step 1: Create the dead-letter queue
DLQ_URL=$(aws sqs create-queue \ --queue-name orders-dlq \ --query QueueUrl --output text)
DLQ_ARN=$(aws sqs get-queue-attributes \ --queue-url $DLQ_URL \ --attribute-names QueueArn \ --query Attributes.QueueArn --output text)Step 2: Create the main queue with a redrive policy
cat > queue-attributes.json <<EOF{ "VisibilityTimeout": "30", "MessageRetentionPeriod": "345600", "ReceiveMessageWaitTimeSeconds": "20", "RedrivePolicy": "{\"deadLetterTargetArn\":\"$DLQ_ARN\",\"maxReceiveCount\":\"3\"}"}EOF
QUEUE_URL=$(aws sqs create-queue \ --queue-name orders-queue \ --attributes file://queue-attributes.json \ --query QueueUrl --output text)
QUEUE_ARN=$(aws sqs get-queue-attributes \ --queue-url $QUEUE_URL \ --attribute-names QueueArn \ --query Attributes.QueueArn --output text)The
maxReceiveCount of 3 means a message moves to the dead-letter queue after it has been received three times without being deleted.Step 3: Test the queue on its own
aws sqs send-message \ --queue-url $QUEUE_URL \ --message-body "hello from the CLI"
aws sqs receive-message \ --queue-url $QUEUE_URL \ --max-number-of-messages 1 \ --wait-time-seconds 10The output includes a
ReceiptHandle . Use it to delete the message once it is processed:RECEIPT=$(aws sqs receive-message \ --queue-url $QUEUE_URL \ --wait-time-seconds 10 \ --query 'Messages[0].ReceiptHandle' --output text)
aws sqs delete-message \ --queue-url $QUEUE_URL \ --receipt-handle "$RECEIPT"If you receive a message and do not delete it, it becomes visible again after the visibility timeout.
Step 3b: Create a FIFO queue (optional)
aws sqs create-queue \ --queue-name orders-queue.fifo \ --attributes FifoQueue=true,ContentBasedDeduplication=trueWhen sending to a FIFO queue, add
--message-group-id , for example --message-group-id customer-42 . Messages in the same group are delivered in order.Step 4: Create the SNS topic
TOPIC_ARN=$(aws sns create-topic \ --name orders-topic \ --query TopicArn --output text)Step 5: Allow the topic to send messages to the queue
SNS can only deliver to the queue if the queue's access policy allows it. This step is easy to forget. The console can handle it for you, but with the CLI you must set it yourself.
cat > queue-policy.json <<EOF{ "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\"}}}]}"}EOF
aws sqs set-queue-attributes \ --queue-url $QUEUE_URL \ --attributes file://queue-policy.jsonThe condition limits access to your specific topic, so no other topic can write to the queue.
Step 6: Subscribe the queue to the topic
SUB_ARN=$(aws sns subscribe \ --topic-arn $TOPIC_ARN \ --protocol sqs \ --notification-endpoint $QUEUE_ARN \ --query SubscriptionArn --output text)
echo $SUB_ARNStep 7: Enable raw message delivery and add a filter policy
aws sns set-subscription-attributes \ --subscription-arn $SUB_ARN \ --attribute-name RawMessageDelivery \ --attribute-value true
aws sns set-subscription-attributes \ --subscription-arn $SUB_ARN \ --attribute-name FilterPolicy \ --attribute-value '{"eventType":["order_created"]}'Step 8: Publish a matching message
aws sns publish \ --topic-arn $TOPIC_ARN \ --subject "New order" \ --message '{"orderId":"1001","total":49.99}' \ --message-attributes '{"eventType":{"DataType":"String","StringValue":"order_created"}}'Step 9: Receive the message from the queue
aws sqs receive-message \ --queue-url $QUEUE_URL \ --max-number-of-messages 1 \ --wait-time-seconds 10 \ --message-attribute-names AllYou should see the order JSON in the
Body field.Step 10: Test the filter
Publish a message that does not match the filter, then poll the queue:
aws sns publish \ --topic-arn $TOPIC_ARN \ --message '{"orderId":"1002"}' \ --message-attributes '{"eventType":{"DataType":"String","StringValue":"order_cancelled"}}'
aws sqs receive-message \ --queue-url $QUEUE_URL \ --wait-time-seconds 5The second command should return nothing, because the filter policy blocked the message.
Step 11: Add an email subscription (optional)
aws sns subscribe \ --topic-arn $TOPIC_ARN \ --protocol email \ --notification-endpoint you@example.comSNS sends a confirmation email. The subscription does not receive messages until you click the confirmation link.
Step 12: Clean up
aws sns unsubscribe --subscription-arn $SUB_ARNaws sns delete-topic --topic-arn $TOPIC_ARN
aws sqs delete-queue --queue-url $QUEUE_URLaws sqs delete-queue --queue-url $DLQ_URLAfter you delete a queue, wait at least 60 seconds before creating a queue with the same name.
Console or CLI: which should you use?
- Console: best for learning. You can poll messages, inspect attributes, and edit policies visually. It can also set up the queue access policy for you when you subscribe from the SQS side.
- CLI: best for repeatable setup and scripting. You must create the queue policy and wire up the ARNs yourself.
For production, define your queues, topics, and subscriptions in AWS CloudFormation, AWS CDK, or Terraform so every environment is identical.
Best practices
- Always design consumers to be idempotent. Standard queues can deliver a message more than once, so processing the same message twice must be safe.
- Use long polling. Set the receive wait time to 20 seconds to reduce empty responses and API costs.
- Set the visibility timeout above your processing time. If it is shorter than the time your consumer needs, the message reappears and gets processed twice.
- Always configure a dead-letter queue. Add an alarm on the DLQ so you know when messages fail repeatedly, and fix the cause before redriving them.
- Use fan-out with SNS and SQS. It keeps producers and consumers decoupled and lets each consumer fail and retry independently.
- Use filter policies. Filtering at the subscription saves cost and avoids processing messages a consumer does not need.
- Enable raw message delivery for SQS subscriptions unless you need the SNS envelope metadata.
- Apply least privilege. Restrict queue policies to specific topic ARNs and restrict IAM permissions to specific queues and topics.
- Delete messages only after successful processing. Deleting early can lose work if the consumer crashes.
- Batch where you can. Use
send-message-batch,receive-messagewith up to 10 messages, anddelete-message-batchto lower cost and improve throughput.
- Monitor with CloudWatch. Watch
ApproximateNumberOfMessagesVisibleandApproximateAgeOfOldestMessagefor queues, andNumberOfNotificationsFailedfor topics.
- Choose FIFO only when you need ordering. Standard queues and topics scale better.
Troubleshooting
- Messages published to the topic never reach the queue: check that the queue access policy allows
sns.amazonaws.comto performsqs:SendMessagewith the correct topic ARN in the condition. This is the most common cause.
- The queue receives nothing even with the correct policy: check the subscription's filter policy. A message without the required attribute is silently dropped.
- The message body contains a JSON envelope with
Type,MessageId, andMessagefields: raw message delivery is not enabled on the subscription.
- The same message is processed repeatedly: the consumer is not deleting it, or the visibility timeout is shorter than the processing time.
- Messages keep ending up in the dead-letter queue: the consumer is failing on them. Inspect the messages, fix the bug, and then redrive them to the source queue.
- An email subscription does not receive messages: the subscription is still pending confirmation. Click the link in the confirmation email.
-
AccessDeniedwhen sending or receiving: your IAM user or role is missingsqs:SendMessage,sqs:ReceiveMessage,sqs:DeleteMessage, orsns:Publishpermissions on that resource.
- A FIFO queue rejects messages: you must provide a
MessageGroupId, and either aMessageDeduplicationIdor content-based deduplication enabled.
- Cannot create a queue right after deleting it: wait 60 seconds before reusing the name.
Conclusion
Amazon SQS and Amazon SNS are simple building blocks for loosely coupled systems. SQS gives you a durable buffer so work is never lost and consumers can scale on their own schedule. SNS gives you broadcast delivery so one event can trigger many reactions. Combined in the fan-out pattern, they let you add new features by adding a subscription instead of changing existing services. Start with one topic and one queue, add a dead-letter queue and a filter policy, and then extend the design to more consumers as your application grows.
Console labels, quotas, and pricing change over time, so confirm current details in the Amazon SQS and Amazon SNS documentation before building.
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article