Skip to main content

Choosing SQS, SNS, and Kinesis for Messaging

Decouple services with SQS queues, fan out messages with SNS, and process real-time streams with Kinesis Data Streams and Firehose.

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.

flowchart LR O[Order service] -->|Publish| Q[(Queue or topic)] Q -->|Pull or push| E[Email service] Q --> F[Fraud service] classDef prod fill:#326CE5,color:#FFFFFF classDef mid fill:#F97316,color:#FFFFFF classDef cons fill:#10B981,color:#FFFFFF class O prod class Q mid class E,F cons

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.

stateDiagram-v2 [*] --> Visible Visible --> InFlight: ReceiveMessage InFlight --> Deleted: DeleteMessage InFlight --> Visible: Timeout expires InFlight --> DLQ: Too many receives

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.

Remember

When 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.

Tip

Put 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.

flowchart TD P[Order service] -->|Publish once| T{{SNS topic}} T --> Q1[(Fraud queue)] T --> Q2[(Shipping queue)] T --> Q3[(Email queue)] Q1 --> W1[Fraud worker] Q2 --> W2[Shipping worker] Q3 --> W3[Email worker] classDef prod fill:#326CE5,color:#FFFFFF classDef topic fill:#F97316,color:#FFFFFF classDef queue fill:#DBEAFE,color:#1E293B classDef worker fill:#10B981,color:#FFFFFF class P prod class T topic class Q1,Q2,Q3 queue class W1,W2,W3 worker

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 Mistake

Forgetting 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.

flowchart LR S[Producers] --> K[Kinesis Data Streams] K -->|Replay possible| C[Your consumer] K --> F[Firehose] F --> B[(S3 bucket)] classDef src fill:#475569,color:#FFFFFF classDef stream fill:#F97316,color:#FFFFFF classDef code fill:#8B5CF6,color:#FFFFFF classDef store fill:#326CE5,color:#FFFFFF class S src class K,F stream class C code class B store

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.

Bash
export AWS_REGION=ap-south-1
export AWS_DEFAULT_REGION=$AWS_REGION
export ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
  1. Create the Dead Letter Queue and read its ARN:
Bash
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)
  1. Create the main queue with long polling, a 60 second visibility timeout, and the DLQ attached after 3 receives:
Bash
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)
  1. 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:
Bash
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 11
aws sqs receive-message --queue-url $ORDERS_URL --visibility-timeout 10 \
--wait-time-seconds 5 --attribute-names ApproximateReceiveCount # reappears
  1. Never delete the message, so it fails repeatedly. After 3 receives SQS moves it to the DLQ, which can take one more poll:
Bash
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/null
done
sleep 11
aws sqs receive-message --queue-url $ORDERS_URL --wait-time-seconds 5
aws sqs receive-message --queue-url $DLQ_URL --wait-time-seconds 5 # the failed message
  1. Now process one message correctly. Receive it, then delete it with its receipt handle:
Bash
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"
  1. Create an SNS topic and a second queue, then subscribe both queues. SNS can only deliver after each queue's policy allows it:
Bash
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 $QARN
done
  1. Publish once, then read both queues. Each should hold a copy, which proves the fan-out:
Bash
aws sns publish --topic-arn $TOPIC_ARN \
--message '{"orderId":"ORD-003","event":"placed"}'
aws sqs receive-message --queue-url $ORDERS_URL --wait-time-seconds 10
aws sqs receive-message --queue-url $FRAUD_URL --wait-time-seconds 10
  1. Clean up. Deleting the topic removes its subscriptions:
Bash
aws sns delete-topic --topic-arn $TOPIC_ARN
aws sqs delete-queue --queue-url $ORDERS_URL
aws sqs delete-queue --queue-url $FRAUD_URL
aws sqs delete-queue --queue-url $DLQ_URL

Production Best Practices & Common Pitfalls

Common Mistake

Using 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 Mistake

Forgetting DeleteMessage after successful processing. The message becomes visible again after the timeout and is processed a second time. Always delete after success.

Common Mistake

Using 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.

Tip

A 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.

Security

Encrypt queues and topics with SSE, and scope queue and topic policies to exact ARNs with aws:SourceArn conditions. Never grant Principal: * 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

Resources

AWS Direct Connect vs VPN: Run Both as Failover

AWS Direct Connect vs VPN: Run Both as Failover

Run AWS Direct Connect as primary and Site-to-Site VPN as BGP failover. Size the backup, set route preference and test it before an outage does.

10 min read•Aug 2026
Lambda vs Fargate vs EC2 Spot: The Cost Crossover

Lambda vs Fargate vs EC2 Spot: The Cost Crossover

Lambda vs Fargate vs EC2 Spot, at the crossover where Lambda stops being cheaper — 2026 pricing, invocation thresholds, and interruption math.

5 min read•Aug 2026
Secrets Manager vs Parameter Store vs Vault

Secrets Manager vs Parameter Store vs Vault

Secrets Manager vs Parameter Store vs Vault: cost math, rotation, dynamic secrets and a decision flow, plus the Vault, IBM and OpenBao licensing context.

10 min read•Aug 2026
AWS VPC Security: Hardening Every Layer

AWS VPC Security: Hardening Every Layer

Harden your AWS VPC in layers: subnets, Security Groups, NACLs, Flow Logs, endpoints, and IAM conditions, with CLI examples for production.

10 min read•Jul 2026
Event-Driven Architecture on AWS Explained

Event-Driven Architecture on AWS Explained

Build event-driven systems on AWS with SQS, SNS, EventBridge and Kinesis: fan-out, DLQs, idempotent consumers and queue-based scaling.

11 min read•Jul 2026
S3 vs RDS vs DynamoDB: Choosing AWS Storage

S3 vs RDS vs DynamoDB: Choosing AWS Storage

Choosing S3, RDS, or DynamoDB wrong costs you in performance, cost, and scalability. Here is a practical decision guide based on your actual access patterns.

5 min read•Jul 2026
AWS Cost Optimisation: 8 Actions That Cut Bills

AWS Cost Optimisation: 8 Actions That Cut Bills

Cut your AWS bill without re-architecting: eight ordered steps from anomaly alerts and tagging to rightsizing, VPC endpoints, Savings Plans and Spot.

11 min read•Jul 2026
EC2 vs Lambda vs Fargate: Choosing AWS Compute

EC2 vs Lambda vs Fargate: Choosing AWS Compute

Choose between EC2, Lambda and Fargate using traffic shape, state and runtime limits, with worked cost break-evens instead of rules of thumb.

11 min read•Jul 2026

Explore More in AWS Messaging, Analytics, and Containers

All 6 Topics

Frequently Asked Questions

Is Choosing SQS, SNS, and Kinesis for Messaging free to learn on DevOps Network?

Yes - this topic, like everything on DevOps Network, is 100% free with no paywall or sign-up gate.

What does the Choosing SQS, SNS, and Kinesis for Messaging topic cover?

Decouple services with SQS queues, fan out messages with SNS, and process real-time streams with Kinesis Data Streams and Firehose.

Found a mistake, an outdated step or a broken link?