Overview and What You Will Learn
Use SQS when one consumer should process each message, SNS when many services need the same message at once, and Kinesis when you need an ordered, replayable stream of continuous data. All three put something between producer and consumer so neither side waits on the other.
In this lab, you will:
- Build an SQS queue with a Dead Letter Queue and watch visibility timeout and redrive happen
- Delete a message correctly after processing it
- Build an SNS topic that fans out to two SQS queues and prove both received a copy
- Clean up in dependency order
Why This Matters in Production
Picture a food delivery platform like Swiggy at dinner rush. When an order is placed, five services need to know: fraud, shipping, email, analytics and the restaurant display. If the order service calls all five directly, one slow service makes the customer wait, and a traffic spike overwhelms every service together. A broker like Zerodha has a different need, where trade events must stay in order, and a streaming platform like Hotstar must capture a huge, continuous flow of viewer events without loss. Decoupling, ordering and streaming are the three problems these services solve.
Core Principles
Why Decoupling Exists
When services call each other synchronously, they inherit each other's speed and availability. A queue, topic or stream in the middle lets each side run, scale and fail independently.
SQS Standard or FIFO
SQS holds messages until a consumer processes and deletes them. Standard queues give nearly unlimited throughput with at-least-once delivery and best-effort ordering, so consumers must be idempotent. FIFO queues guarantee order and remove duplicates, at lower throughput.
| Property | Standard | FIFO |
|---|---|---|
| Throughput | Nearly unlimited | 300 msg/s per API action, 3,000 with batching, more in high throughput mode |
| Ordering | Best effort | Strict, per message group |
| Duplicates | Possible | Removed within 5 minutes |
Retention defaults to 4 days and can reach 14 days. Maximum message size has been 256 KB and was raised to 1 MiB, so check the current quota for your Region. FIFO queue names must end in .fifo, and every message needs a MessageGroupId.
How Visibility Timeout Works
When a consumer receives a message, SQS hides it from other consumers for the visibility timeout. If the consumer deletes it in time, it is gone. If not, the message reappears for another attempt.
The default is 30 seconds and the range is 0 seconds to 12 hours. A timeout that is too short makes slow work get processed twice. One that is too long leaves a crashed consumer's message stuck for hours. For long jobs, extend it with ChangeMessageVisibility.
RememberWhen Lambda is the consumer, set the queue's visibility timeout to at least 6 times the function timeout, so retries do not make messages visible mid-processing.
Long Polling and Dead Letter Queues
Short polling returns immediately even when the queue is empty, so a busy loop wastes API calls and money. Long polling holds the request open for up to 20 seconds and returns the moment a message arrives. Set ReceiveMessageWaitTimeSeconds to 20 on the queue.
A Dead Letter Queue (DLQ) catches messages that fail repeatedly. After maxReceiveCount receives without a delete, SQS moves the message to the DLQ, where you can inspect it, fix the bug and redrive it back.
TipPut a CloudWatch alarm on the DLQ's
ApproximateNumberOfMessagesVisible. A message in the DLQ is a bug report, and you want to hear about it in minutes.
Two Patterns: Worker Scaling and Spike Buffering
SQS plus an Auto Scaling group makes a self-regulating pipeline. A CloudWatch alarm on queue depth adds workers when the queue grows and removes them when it drains. Target tracking on backlog per instance is the cleaner version of this.
The same queue protects a database from spikes. Writers push 10,000 messages per second into SQS, and a consumer drains them into RDS at a safe 500 per second, so nothing is dropped and the database is never overwhelmed.
SNS Pub/Sub and the Fan-Out Pattern
An SQS message goes to one consumer, while an SNS message goes to every subscriber. SNS does not store messages, so a subscriber that is down at publish time misses it. The fix is to subscribe an SQS queue per consumer, so each queue persists its own copy.
A topic supports up to 12,500,000 subscriptions, and subscribers include SQS, Lambda, Firehose, email, SMS, mobile push and HTTP endpoints. A filter policy on a subscription delivers only messages whose attributes match, so one topic can serve status=placed to fraud and status=cancelled to refunds. S3 cannot send the same event type and prefix to several destinations, so it publishes once to SNS (or EventBridge), which fans out to the rest.
Common MistakeForgetting the SQS queue access policy. SNS needs permission to send to each queue, and without it everything looks configured but no messages arrive.
Kinesis Data Streams
Kinesis collects continuous data such as clicks, IoT readings and logs, and stores it so it can be read in order and replayed. A shard is the capacity unit: it accepts up to 1 MB/s or 1,000 records/s in and serves 2 MB/s out. Records with the same partition key land on the same shard in order.
Retention is 24 hours by default and can be extended to 365 days. That makes Kinesis the only one of the three that supports replay, so you can fix a consumer bug and reprocess yesterday's data.
| Mode | You manage | Best for |
|---|---|---|
| Provisioned | Shard count | Steady, predictable traffic |
| On-Demand | Nothing | Spiky or unknown traffic |
By default consumers share a shard's 2 MB/s read capacity. Enhanced fan-out gives each registered consumer its own 2 MB/s per shard.
Amazon Data Firehose
Firehose delivers streaming data to a destination with no consumer code. It buffers by size or time, optionally runs a Lambda to transform records, and loads the batch into S3, Redshift, OpenSearch, Splunk or an HTTP endpoint. It is near real-time, not real-time, because buffering adds delay of roughly a minute by default, so check current minimums for your destination.
How to Choose
| Service | Model | Persistence and replay |
|---|---|---|
| SQS | Queue, consumers pull | Until deleted, no replay |
| SNS | Pub/sub, SNS pushes | Not stored, no replay |
| Kinesis | Stream, consumers pull | 1 to 365 days, replay |
- Choose SQS for a work queue where one consumer handles each job, or to buffer a spike.
- Choose SNS when the same event must reach many services, or for push notifications.
- Choose Kinesis for continuous high-volume data, real-time analytics, several consumers on one stream, or replay.
Amazon MQ is the exception: it runs managed ActiveMQ and RabbitMQ brokers that speak open protocols such as AMQP, MQTT and STOMP. Use it only when migrating an application whose messaging layer you cannot rewrite. New applications should use SQS and SNS.
Detailed Step-by-Step Practical Lab
This lab uses the AWS CLI and costs almost nothing. It needs jq for building the queue policies.
export AWS_REGION=ap-south-1export AWS_DEFAULT_REGION=$AWS_REGIONexport ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)- Create the Dead Letter Queue and read its ARN:
export DLQ_URL=$(aws sqs create-queue --queue-name devops-orders-dlq \ --query QueueUrl --output text)export DLQ_ARN=$(aws sqs get-queue-attributes --queue-url $DLQ_URL \ --attribute-names QueueArn --query Attributes.QueueArn --output text)- Create the main queue with long polling, a 60 second visibility timeout, and the DLQ attached after 3 receives:
cat > orders-attrs.json << EOF{ "VisibilityTimeout": "60", "ReceiveMessageWaitTimeSeconds": "20", "RedrivePolicy": "{\"deadLetterTargetArn\":\"$DLQ_ARN\",\"maxReceiveCount\":\"3\"}"}EOF export ORDERS_URL=$(aws sqs create-queue --queue-name devops-orders \ --attributes file://orders-attrs.json --query QueueUrl --output text)- Send a message, then receive it with a short 10 second timeout. A second receive straight away returns nothing, because the message is hidden. After the timeout it reappears with a higher receive count:
aws sqs send-message --queue-url $ORDERS_URL \ --message-body '{"orderId":"ORD-001","city":"Mumbai","amount":450}' aws sqs receive-message --queue-url $ORDERS_URL --visibility-timeout 10 \ --wait-time-seconds 5 --attribute-names ApproximateReceiveCount aws sqs receive-message --queue-url $ORDERS_URL --wait-time-seconds 2 # empty: in flight sleep 11aws sqs receive-message --queue-url $ORDERS_URL --visibility-timeout 10 \ --wait-time-seconds 5 --attribute-names ApproximateReceiveCount # reappears- Never delete the message, so it fails repeatedly. After 3 receives SQS moves it to the DLQ, which can take one more poll:
for i in 1 2 3; do sleep 11 aws sqs receive-message --queue-url $ORDERS_URL --visibility-timeout 10 \ --wait-time-seconds 5 > /dev/nulldone sleep 11aws sqs receive-message --queue-url $ORDERS_URL --wait-time-seconds 5aws sqs receive-message --queue-url $DLQ_URL --wait-time-seconds 5 # the failed message- Now process one message correctly. Receive it, then delete it with its receipt handle:
aws sqs send-message --queue-url $ORDERS_URL --message-body '{"orderId":"ORD-002"}' export RECEIPT=$(aws sqs receive-message --queue-url $ORDERS_URL \ --wait-time-seconds 10 --query 'Messages[0].ReceiptHandle' --output text) aws sqs delete-message --queue-url $ORDERS_URL --receipt-handle "$RECEIPT"- Create an SNS topic and a second queue, then subscribe both queues. SNS can only deliver after each queue's policy allows it:
export TOPIC_ARN=$(aws sns create-topic --name devops-order-events \ --query TopicArn --output text) export FRAUD_URL=$(aws sqs create-queue --queue-name devops-fraud-check \ --query QueueUrl --output text) for URL in $ORDERS_URL $FRAUD_URL; do QARN=$(aws sqs get-queue-attributes --queue-url $URL \ --attribute-names QueueArn --query Attributes.QueueArn --output text) cat > queue-policy.json << EOF{ "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Principal": { "Service": "sns.amazonaws.com" }, "Action": "sqs:SendMessage", "Resource": "$QARN", "Condition": { "ArnEquals": { "aws:SourceArn": "$TOPIC_ARN" } } }]}EOF jq -n --arg p "$(cat queue-policy.json)" '{Policy: $p}' > queue-attrs.json aws sqs set-queue-attributes --queue-url $URL --attributes file://queue-attrs.json aws sns subscribe --topic-arn $TOPIC_ARN --protocol sqs --notification-endpoint $QARNdone- Publish once, then read both queues. Each should hold a copy, which proves the fan-out:
aws sns publish --topic-arn $TOPIC_ARN \ --message '{"orderId":"ORD-003","event":"placed"}' aws sqs receive-message --queue-url $ORDERS_URL --wait-time-seconds 10aws sqs receive-message --queue-url $FRAUD_URL --wait-time-seconds 10- Clean up. Deleting the topic removes its subscriptions:
aws sns delete-topic --topic-arn $TOPIC_ARNaws sqs delete-queue --queue-url $ORDERS_URLaws sqs delete-queue --queue-url $FRAUD_URLaws sqs delete-queue --queue-url $DLQ_URLProduction Best Practices & Common Pitfalls
Common MistakeUsing SQS when several services need the same message. A queue message goes to one consumer, so use an SNS topic that fans out to one SQS queue per service.
Common MistakeForgetting
DeleteMessageafter successful processing. The message becomes visible again after the timeout and is processed a second time. Always delete after success.
Common MistakeUsing Firehose when you need Data Streams. Firehose buffers, stores nothing and cannot replay. Use Data Streams with your own consumer for low latency or reprocessing.
TipA common serverless analytics pipeline is devices to Kinesis Data Streams, Firehose to S3 in Parquet, Athena for queries and QuickSight for dashboards. Kinesis gives real-time collection and replay, and Firehose handles conversion and delivery.
SecurityEncrypt queues and topics with SSE, and scope queue and topic policies to exact ARNs with
aws:SourceArnconditions. Never grantPrincipal: *on a queue.
- Make consumers idempotent. Standard queues and retries both deliver duplicates, so processing a message twice must be safe.
- Always attach a DLQ. A poison message otherwise loops forever, and alarm on the DLQ depth.
- Use long polling everywhere. It is cheaper and returns faster than short polling.
- Choose partition keys that spread load. A hot key sends all traffic to one shard and throttles it.
- Use SNS FIFO plus SQS FIFO for ordered fan-out. Standard topics give no ordering guarantee.
Quick Reference & Troubleshooting Commands
| Command | Description |
|---|---|
aws sqs create-queue --attributes file://attrs.json |
Create a queue with settings |
aws sqs receive-message --wait-time-seconds 20 |
Long poll for messages |
aws sqs delete-message --receipt-handle H |
Delete after processing |
aws sqs change-message-visibility |
Extend the timeout for a slow job |
aws sns publish --topic-arn ARN |
Publish to a topic |
aws sns subscribe --protocol sqs |
Subscribe a queue to a topic |
aws kinesis describe-stream-summary |
Check a stream's shard count |
| Problem | Likely cause | Fix |
|---|---|---|
| Messages processed twice | Timeout shorter than processing time | Raise visibility timeout or extend it per message |
| SNS messages never reach the queue | Queue policy blocks SNS | Allow sns.amazonaws.com with a SourceArn condition |
| Queue keeps growing | Too few consumers | Scale workers on queue depth |
| Kinesis throttling errors | Hot shard or too few shards | Better partition keys, more shards, or On-Demand |
| Message missing from main queue | Moved to the DLQ | Inspect the DLQ and redrive after the fix |