AWSBeginner
SNS → SQS fan-out and dead-letter queues: decoupling services with Terraform
Key results
- One publish to SNS and both the billing and shipping queues get the message, independently of each other.
- A message received 3 times without being deleted is moved to the dead-letter queue by SQS automatically.
- On real AWS, a missing queue policy for SNS is the most common mistake: SNS reports success but the queue stays empty.
What you need
- No prior SNS, SQS or Terraform knowledge: the guide explains it from scratch.
- A machine with Docker, Terraform and AWS CLI v2. Setup is in the "Lab setup" guide.
- No AWS account needed: Moto (open source) mocks the AWS APIs on your own machine.
- Time
- 35 min
- Cost
- $0, mocked with Moto
- Amazon SNS
- Amazon SQS
- Terraform
- Moto
An online shop receives a new order. Several things must happen right away: charge the customer, prepare shipping, send a confirmation email. The obvious approach is for the order service to call each of those services in turn. That works, until the day one service is slow or down and drags the whole shop down with it.
This guide builds the common AWS pattern that avoids it: SNS publishes once, and every service has its own SQS queue, plus a queue that holds failing messages. Everything runs on your own machine at zero cost.
The problem: services calling each other directly
On the left, the services are tightly coupled: the order service has to wait for billing before it can answer the customer. On the right they are decoupled: the order service just publishes a message and answers the customer immediately.
A few concepts first
- Message
- A small piece of data describing something that just happened, usually JSON.Example: {"order_id":1001} means "order 1001 was placed".
- SNS topic
- A loudspeaker: you publish to the topic once and every subscriber gets its own copy.Example: The "orders" topic announces new orders.
- SQS queue
- A mailbox for one service: messages wait here until that service takes them out and processes them.Example: The "billing" queue only serves the billing service.
- Subscription
- The wire between a topic and one receiver. Each message is copied once per subscription.Example: The billing queue subscribes to the orders topic.
- Visibility timeout
- When a service takes a message, SQS hides it so no other consumer takes it too. If it is not deleted in time, it reappears.Example: This guide uses 30 seconds.
- Dead-letter queue (DLQ)
- Where messages that failed too many times go, so they stop blocking the main queue and you can inspect them later.Example: A message that still fails after 3 receives moves to billing-dlq.
Lab architecture
| Component | Name in this guide | Why you need it |
|---|---|---|
| SNS topic | orders |
Where the order service publishes. Adding a new service only needs a new subscription, not a change to the order service. |
| Billing queue | billing |
The billing service reads from here at its own pace. |
| Shipping queue | shipping |
Independent from billing: if billing breaks, shipping keeps working. |
| Error queue | billing-dlq |
Isolates messages that keep making billing fail. |
Step 1: Run Moto to mock AWS
What you are doing: starting a “fake AWS” on your machine. Moto is open-source software that answers API calls like real AWS (create a queue, send a message…), but everything lives only in your machine’s memory.
docker run -d --name moto -p 127.0.0.1:4566:5000 motoserver/motoexport AWS_ACCESS_KEY_ID=test AWS_SECRET_ACCESS_KEY=test AWS_DEFAULT_REGION=us-east-1 # fake keysalias awsl='aws --endpoint-url http://localhost:4566'| Command | Meaning | Why |
|---|---|---|
-p 127.0.0.1:4566:5000 |
Opens port 4566 on your machine, mapped to Moto’s port 5000 | Bound to 127.0.0.1 only, so other machines on your network cannot reach it. |
export AWS_ACCESS_KEY_ID=test ... |
Sets fake access keys | The AWS CLI refuses to run without keys. Moto accepts any key. Never put real keys here. |
alias awsl=... |
Creates a shortcut awsl = AWS CLI pointed at Moto |
Type awsl instead of aws --endpoint-url ... every time, and never hit real AWS by mistake. |
Step 2: Write the Terraform
What you are doing: describing the whole infrastructure in one file. Terraform reads it and creates exactly what is described. Create main.tf and fill in the 4 parts below in order.
Part 1: Point Terraform at Moto
terraform { required_providers { aws = { source = "hashicorp/aws", version = "~> 5.0" } }}
provider "aws" { region = "us-east-1" access_key = "test" # fake key for Moto secret_key = "test" skip_credentials_validation = true skip_metadata_api_check = true skip_requesting_account_id = true endpoints { sns = "http://localhost:4566" sqs = "http://localhost:4566" sts = "http://localhost:4566" iam = "http://localhost:4566" }}| Line | Meaning | Why it is set this way |
|---|---|---|
version = "~> 5.0" |
Use the AWS provider 5.x | Pinning the version means a later re-run does not change behaviour unexpectedly. |
skip_credentials_validation and the 2 other skip_* lines |
Skip checking the keys and account against real AWS | The keys are fake; without these, Terraform tries to verify them with real AWS and fails. |
endpoints |
Sends SNS, SQS, STS and IAM calls to Moto | By default Terraform calls the real AWS endpoints. This block points them at Moto on your machine. |
Part 2: The topic and the queues
resource "aws_sns_topic" "orders" { name = "orders"}
resource "aws_sqs_queue" "billing_dlq" { name = "billing-dlq"}
resource "aws_sqs_queue" "billing" { name = "billing" visibility_timeout_seconds = 30 redrive_policy = jsonencode({ deadLetterTargetArn = aws_sqs_queue.billing_dlq.arn maxReceiveCount = 3 })}
resource "aws_sqs_queue" "shipping" { name = "shipping"}| Line | Meaning | Why it is set this way |
|---|---|---|
resource "aws_sns_topic" "orders" |
Creates a topic called orders |
The second "orders" is Terraform’s internal name, used by other parts to reference it. |
billing_dlq declared first |
Creates the error queue | The billing queue needs the DLQ’s address (ARN), so the DLQ must exist first. Terraform orders this itself thanks to the aws_sqs_queue.billing_dlq.arn reference. |
visibility_timeout_seconds = 30 |
Hides a message for 30 seconds after it is received | Must be longer than the time to process one message. Too short and the message reappears mid-processing and gets handled twice. |
redrive_policy |
The rule that moves messages to the DLQ | Without it, a failing message is received, fails, reappears forever and wastes resources. |
maxReceiveCount = 3 |
More than 3 receives without a delete moves it to the DLQ | High enough to survive temporary errors (a network blip), low enough to see the result quickly in this guide. |
Part 3: Allow SNS to send into the queues
data "aws_iam_policy_document" "allow_sns" { for_each = { billing = aws_sqs_queue.billing.arn, shipping = aws_sqs_queue.shipping.arn } statement { effect = "Allow" actions = ["sqs:SendMessage"] resources = [each.value] principals { type = "Service" identifiers = ["sns.amazonaws.com"] } condition { test = "ArnEquals" variable = "aws:SourceArn" values = [aws_sns_topic.orders.arn] } }}
resource "aws_sqs_queue_policy" "billing" { queue_url = aws_sqs_queue.billing.id policy = data.aws_iam_policy_document.allow_sns["billing"].json}# aws_sqs_queue_policy "shipping" is identical, with billing replaced by shipping| Line | Meaning | Why it is set this way |
|---|---|---|
for_each |
Write once, create a policy for both queues | Avoids copying two identical blocks and forgetting to edit one. |
actions = ["sqs:SendMessage"] |
Only allows sending | Least privilege: SNS only needs to send, not read or delete. |
principals ... sns.amazonaws.com |
The allowed caller is the SNS service | By default only the account owner can send to an SQS queue. SNS is another service, so it must be allowed explicitly. |
condition ... aws:SourceArn |
Only your orders topic may send |
Without this condition any SNS topic, even in another account, could send into your queue. |
Part 4: Subscribe the queues to the topic
resource "aws_sns_topic_subscription" "billing" { topic_arn = aws_sns_topic.orders.arn protocol = "sqs" endpoint = aws_sqs_queue.billing.arn raw_message_delivery = true}# subscription "shipping" is identical, with billing replaced by shipping
output "topic_arn" { value = aws_sns_topic.orders.arn }output "billing_url" { value = aws_sqs_queue.billing.id }output "shipping_url" { value = aws_sqs_queue.shipping.id }output "dlq_url" { value = aws_sqs_queue.billing_dlq.id }| Line | Meaning | Why it is set this way |
|---|---|---|
protocol = "sqs" |
The receiver is an SQS queue | SNS can also deliver to email, HTTP or Lambda; SQS is chosen so messages have somewhere to wait. |
raw_message_delivery = true |
Deliver the original body as-is | By default SNS wraps the message in its own JSON envelope. With this on, the service receives exactly {"order_id":1001} and does not have to unwrap anything. |
output |
Prints the topic and queue addresses after creation | The commands in step 3 need these; reading them from outputs means no copy and paste. |
Create the resources:
terraform init # downloads the AWS provider into .terraformterraform apply -auto-approveThe last line should be Apply complete! Resources: 8 added: 1 topic, 3 queues, 2 queue policies, 2 subscriptions.
Step 3: Publish and watch
What you are doing: playing the order service and publishing one message, then playing each downstream service and reading it.
TOPIC=$(terraform output -raw topic_arn); BILL=$(terraform output -raw billing_url)SHIP=$(terraform output -raw shipping_url); DLQ=$(terraform output -raw dlq_url)
awsl sns publish --topic-arn "$TOPIC" --message '{"order_id":1001}'awsl sqs receive-message --queue-url "$SHIP" --query "Messages[].Body" --output textshipping: {"order_id":1001}How to read it: you published to the topic once and the shipping queue already has the message. The billing queue has its own copy too: that is fan-out.
Now simulate a broken billing service: it receives the message but never finishes, so it never deletes it. Repeat 4 times:
for i in 1 2 3 4; do awsl sqs receive-message --queue-url "$BILL" --visibility-timeout 0 \ --query "Messages[].Body" --output textdoneawsl sqs receive-message --queue-url "$DLQ" --query "Messages[].Body" --output textReal output:
billing receive 1: {"order_id":1001}billing receive 2: {"order_id":1001}billing receive 3: {"order_id":1001}billing receive 4: Nonedlq: {"order_id":1001}How to read it: the first three times, the message is still in billing because nobody deleted it. SQS counts receives in the ApproximateReceiveCount attribute. On the 4th attempt the count would exceed maxReceiveCount = 3, so SQS moves the message to billing-dlq instead of delivering it again, and that receive returns None. The failing message is isolated, and the other messages in billing are not blocked by it.
Applying this on real AWS
- Remove the fake
access_keyandsecret_key, the threeskip_*lines and theendpointsblock from the provider; use a separate AWS account for experiments and turn on AWS Budgets. - Keep part 3 (the queue policy) exactly as is. It is the part people forget most.
- Set
visibility_timeout_secondslonger than the time to process one message, or messages reappear and get processed twice. - If a queue is encrypted with a customer managed KMS key, the key policy must allow SNS to use that key, or messages will not reach the queue either.
- Need strict ordering and no duplicates? Use an SNS FIFO topic with SQS FIFO queues.
- Add a CloudWatch alarm on DLQ depth. A DLQ nobody watches just lets failing messages expire silently.
Common errors
| Symptom | Usual cause | Fix |
|---|---|---|
Could not connect to the endpoint URL: http://localhost:4566 |
Moto is not running | docker ps to find the moto container; run step 1 again |
terraform apply tries to call real AWS and fails on keys |
Missing endpoints block or skip_* lines |
Compare with part 1 |
| On real AWS: publish succeeds, queue is empty | Missing queue policy, or a KMS-encrypted queue whose key policy does not allow SNS | Check part 3 and the key policy |
Received messages are odd JSON with Type, TopicArn |
raw_message_delivery is not enabled |
Add that line to the subscription |
Clean up
terraform destroy -auto-approvedocker rm -f motoFAQ
Why not let services call each other directly instead of going through SNS and SQS? With direct calls the sender must wait for the receiver. Through a queue each side runs at its own pace; if the receiver goes down, the messages simply wait in the queue.
What is the difference between SNS and SQS? SNS pushes a message to every subscriber right away and keeps nothing. SQS holds a message until someone receives and deletes it. Together: SNS to broadcast to many, SQS so each receiver has its own buffer.
What should maxReceiveCount be? High enough to survive temporary errors, low enough that failing messages do not tie up resources for long. This guide uses 3 to see the result quickly.
References

Cloud & Network Engineer · TrungCLN
Designs and runs AWS infrastructure, hybrid networking (VPN, BGP) and cloud security. Every guide on this site is built and run for real before it is written.
Related guides

Lab setupBeginner45 min
Build a cloud and networking lab on one Linux machine, for $0
One Linux machine with Docker runs BGP routers, IPsec VPN and a mocked AWS. Install each tool, verify each step and learn why you need it. Written for beginners.
NetworkingIntermediate40 min
VPN with 2 tunnels and BGP: how long does failover really take?
Build two BGP routers over two tunnels like AWS Site-to-Site VPN, measure failover for hard and soft failures, and learn why every config line is there.