🚀 AWS SNS & SQS

Complete Guide to Simple Notification Service & Simple Queue Service

🔍 Overview

AWS SNS (Simple Notification Service) and SQS (Simple Queue Service) are fundamental messaging services that enable decoupled, scalable architectures. SNS provides pub/sub messaging for real-time notifications, while SQS offers reliable message queuing for asynchronous processing.
graph TB subgraph "Publishers" P1[Web Application] P2[Mobile App] P3[IoT Device] end subgraph "AWS SNS" SNS[SNS Topic] end subgraph "Subscribers" SQS1[SQS Queue 1] SQS2[SQS Queue 2] EMAIL[Email] SMS[SMS] LAMBDA[Lambda Function] HTTP[HTTP Endpoint] end P1 --> SNS P2 --> SNS P3 --> SNS SNS --> SQS1 SNS --> SQS2 SNS --> EMAIL SNS --> SMS SNS --> LAMBDA SNS --> HTTP style SNS fill:#ff9999 style SQS1 fill:#99ccff style SQS2 fill:#99ccff
Aspect SNS SQS
Purpose Publish/Subscribe messaging Message queuing
Message Delivery Push (immediate) Pull (on-demand)
Subscribers Multiple (fan-out) Single consumer per message
Message Persistence No (fire-and-forget) Yes (until processed)
Use Case Real-time notifications Asynchronous processing

📢 AWS SNS Deep Dive

🎯 Topics

Central communication channels where publishers send messages and subscribers receive them. Topics act as access points for subscribers.

🔗 Subscriptions

Endpoints that receive messages from topics. Support email, SMS, HTTP/HTTPS, SQS, Lambda, and mobile push notifications.

🚀 Fan-out Pattern

Single message published to a topic is delivered to all subscribers simultaneously, enabling parallel processing.

🔒 Message Filtering

Subscribers can receive only messages that match specific attributes, reducing unnecessary processing.

SNS Architecture Flow

sequenceDiagram participant P as Publisher participant SNS as SNS Topic participant S1 as SQS Queue participant S2 as Email participant S3 as Lambda P->>SNS: Publish Message SNS->>S1: Deliver to SQS SNS->>S2: Send Email SNS->>S3: Trigger Lambda Note over SNS: Message delivered to all subscribers simultaneously

⚡ Key Benefits

SNS provides instant message delivery, automatic scaling, and supports multiple protocols. It's perfect for real-time notifications, system alerts, and triggering downstream processes across multiple services.

📬 AWS SQS Deep Dive

📝 Standard Queues

Unlimited throughput with at-least-once delivery. Messages may arrive out of order but provide maximum performance.

🎯 FIFO Queues

First-In-First-Out delivery with exactly-once processing. Maintains order but with limited throughput (300 TPS).

⏰ Visibility Timeout

Prevents multiple consumers from processing the same message. Message becomes invisible during processing.

💀 Dead Letter Queues

Captures messages that fail processing after maximum retry attempts, preventing message loss.

SQS Message Lifecycle

stateDiagram-v2 [*] --> Sent: Send Message Sent --> Available: Message in Queue Available --> InFlight: Receive Message InFlight --> Available: Visibility Timeout Expires InFlight --> Deleted: Delete Message Available --> DLQ: Max Retries Exceeded Deleted --> [*] DLQ --> [*]: Manual Processing

Standard vs FIFO Queues

graph LR subgraph "Standard Queue" P1[Producer] --> SQ[Standard Queue] SQ --> C1[Consumer 1] SQ --> C2[Consumer 2] SQ --> C3[Consumer 3] end subgraph "FIFO Queue" P2[Producer] --> FQ[FIFO Queue] FQ --> C4[Consumer] end style SQ fill:#ffcccc style FQ fill:#ccffcc

🔄 SNS + SQS Integration Patterns

Fan-out Pattern with SQS

graph TD ORDER[Order Placed] --> SNS[SNS Topic: OrderEvents] SNS --> INV[SQS: Inventory Queue] SNS --> PAY[SQS: Payment Queue] SNS --> SHIP[SQS: Shipping Queue] SNS --> EMAIL[SQS: Email Queue] INV --> INVS[Inventory Service] PAY --> PAYS[Payment Service] SHIP --> SHIPS[Shipping Service] EMAIL --> EMAILS[Email Service] style SNS fill:#ff9999 style INV fill:#99ccff style PAY fill:#99ccff style SHIP fill:#99ccff style EMAIL fill:#99ccff

🎯 Why Combine SNS and SQS?

This pattern provides the best of both worlds: immediate notification delivery from SNS with the reliability and durability of SQS queues. If a service is temporarily unavailable, messages wait in the queue rather than being lost.

Cross-Region Replication

graph TB subgraph "Region 1 (Primary)" APP1[Application] --> SNS1[SNS Topic] SNS1 --> SQS1[Local SQS Queue] SNS1 --> HTTP1[HTTP Endpoint to Region 2] end subgraph "Region 2 (Secondary)" HTTP1 --> SNS2[SNS Topic] SNS2 --> SQS2[Local SQS Queue] end SQS1 --> PROC1[Processing Service] SQS2 --> PROC2[Processing Service]

⚙️ AWS CLI Configuration

Setting up SNS

1. Create SNS Topic

aws sns create-topic --name OrderNotifications
This command creates a new SNS topic named "OrderNotifications". The topic serves as a communication channel where publishers can send messages and subscribers can receive them. AWS returns a TopicArn that uniquely identifies this topic.

2. Create FIFO Topic (for ordered messages)

aws sns create-topic --name OrderNotifications.fifo --attributes FifoTopic=true,ContentBasedDeduplication=true
Creates a FIFO (First-In-First-Out) topic that ensures message ordering and exactly-once delivery. The .fifo suffix is required. ContentBasedDeduplication=true automatically generates deduplication IDs based on message content to prevent duplicate messages.

3. List Topics

aws sns list-topics
Retrieves all SNS topics in your AWS account for the current region. Returns topic ARNs and basic metadata for each topic.

4. Subscribe Email to Topic

aws sns subscribe --topic-arn arn:aws:sns:us-east-1:123456789012:OrderNotifications --protocol email --notification-endpoint user@example.com
Creates an email subscription to the topic. AWS will send a confirmation email to the specified address. The user must click the confirmation link to activate the subscription. Replace the topic-arn with your actual topic ARN.

5. Subscribe SQS Queue to Topic

aws sns subscribe --topic-arn arn:aws:sns:us-east-1:123456789012:OrderNotifications --protocol sqs --notification-endpoint arn:aws:sqs:us-east-1:123456789012:OrderProcessingQueue
Subscribes an SQS queue to receive messages from the SNS topic. This enables the fan-out pattern where a single SNS message can trigger multiple SQS queues for parallel processing. Ensure the SQS queue policy allows SNS to deliver messages.

6. Publish Message to Topic

aws sns publish --topic-arn arn:aws:sns:us-east-1:123456789012:OrderNotifications --message "New order received: Order #12345" --subject "Order Notification"
Publishes a message to all subscribers of the topic. The message is delivered immediately to all active subscriptions. The subject parameter is used for email and SMS protocols to provide a message header.

7. Publish with Message Attributes (for filtering)

aws sns publish --topic-arn arn:aws:sns:us-east-1:123456789012:OrderNotifications --message "Premium order received" --message-attributes '{"OrderType":{"DataType":"String","StringValue":"Premium"},"Amount":{"DataType":"Number","StringValue":"150.00"}}'
Publishes a message with custom attributes that can be used for message filtering. Subscribers can filter messages based on these attributes to receive only relevant messages, reducing processing overhead and improving efficiency.

Setting up SQS

1. Create Standard SQS Queue

aws sqs create-queue --queue-name OrderProcessingQueue
Creates a standard SQS queue with default settings. Standard queues offer unlimited throughput and at-least-once delivery but don't guarantee message ordering. They're ideal for high-volume, parallel processing scenarios.

2. Create FIFO Queue

aws sqs create-queue --queue-name OrderProcessingQueue.fifo --attributes FifoQueue=true,ContentBasedDeduplication=true
Creates a FIFO queue that maintains strict message ordering and provides exactly-once processing. The .fifo suffix is mandatory. ContentBasedDeduplication prevents duplicate messages based on message content without requiring explicit deduplication IDs.

3. Configure Queue Attributes

aws sqs set-queue-attributes --queue-url https://sqs.us-east-1.amazonaws.com/123456789012/OrderProcessingQueue --attributes VisibilityTimeoutSeconds=300,MessageRetentionPeriod=1209600,MaxReceiveCount=3
Configures important queue parameters: VisibilityTimeoutSeconds (300) sets how long messages remain invisible after being received, MessageRetentionPeriod (1209600 = 14 days) determines how long messages stay in the queue, and MaxReceiveCount (3) sets retry attempts before moving to dead letter queue.

4. Create Dead Letter Queue

aws sqs create-queue --queue-name OrderProcessingQueue-DLQ
Creates a dead letter queue to capture messages that fail processing after the maximum number of retry attempts. This prevents message loss and allows for manual investigation and reprocessing of problematic messages.

5. Configure Dead Letter Queue

aws sqs set-queue-attributes --queue-url https://sqs.us-east-1.amazonaws.com/123456789012/OrderProcessingQueue --attributes '{"RedrivePolicy":"{\"deadLetterTargetArn\":\"arn:aws:sqs:us-east-1:123456789012:OrderProcessingQueue-DLQ\",\"maxReceiveCount\":3}"}'
Links the main queue to its dead letter queue with a redrive policy. Messages that are received 3 times without being successfully deleted are automatically moved to the dead letter queue for troubleshooting.

6. Send Message to Queue

aws sqs send-message --queue-url https://sqs.us-east-1.amazonaws.com/123456789012/OrderProcessingQueue --message-body "Process order #12345 for customer John Doe"
Sends a message directly to the SQS queue. The message will remain in the queue until a consumer receives and processes it. For FIFO queues, you would also need to specify MessageGroupId and optionally MessageDeduplicationId.

7. Receive Messages

aws sqs receive-message --queue-url https://sqs.us-east-1.amazonaws.com/123456789012/OrderProcessingQueue --max-number-of-messages 10 --wait-time-seconds 20
Retrieves up to 10 messages from the queue using long polling (wait-time-seconds=20). Long polling reduces the number of API calls and provides more efficient message retrieval by waiting for messages to arrive if the queue is empty.

8. Delete Processed Message

aws sqs delete-message --queue-url https://sqs.us-east-1.amazonaws.com/123456789012/OrderProcessingQueue --receipt-handle "AQEBwJnKyrHigUMZj6rYigCgxlaS3SLy0a..."
Removes a message from the queue after successful processing. The receipt-handle is provided when receiving the message and acts as a temporary identifier. If you don't delete the message, it will become visible again after the visibility timeout expires.

Queue Policy for SNS Integration

aws sqs set-queue-attributes --queue-url https://sqs.us-east-1.amazonaws.com/123456789012/OrderProcessingQueue --attributes '{ "Policy": "{ \"Version\": \"2012-10-17\", \"Statement\": [{ \"Effect\": \"Allow\", \"Principal\": \"*\", \"Action\": \"sqs:SendMessage\", \"Resource\": \"arn:aws:sqs:us-east-1:123456789012:OrderProcessingQueue\", \"Condition\": { \"ArnEquals\": { \"aws:SourceArn\": \"arn:aws:sns:us-east-1:123456789012:OrderNotifications\" } } }] }" }'
Sets a queue policy that allows the SNS topic to send messages to the SQS queue. This is essential for SNS-to-SQS integration. The policy grants SendMessage permission only to the specific SNS topic, ensuring security through the SourceArn condition.

Message Filtering Setup

aws sns set-subscription-attributes --subscription-arn arn:aws:sns:us-east-1:123456789012:OrderNotifications:12345678-1234-1234-1234-123456789012 --attribute-name FilterPolicy --attribute-value '{"OrderType":["Premium","VIP"],"Amount":[{"numeric":[">=",100]}]}'
Configures message filtering for a subscription. This filter ensures the subscriber only receives messages where OrderType is "Premium" or "VIP" AND the Amount is greater than or equal to 100. Message filtering reduces unnecessary message processing and improves system efficiency.

✨ Best Practices

🔒 Security

  • Use IAM policies for fine-grained access control
  • Enable encryption at rest and in transit
  • Implement least privilege principle
  • Use VPC endpoints for private communication

📊 Monitoring

  • Set up CloudWatch alarms for queue depth
  • Monitor failed message delivery
  • Track processing latency
  • Use X-Ray for distributed tracing

⚡ Performance

  • Use batch operations when possible
  • Implement exponential backoff for retries
  • Configure appropriate visibility timeouts
  • Use long polling for SQS

🛡️ Reliability

  • Always implement dead letter queues
  • Design for idempotent processing
  • Use FIFO queues when ordering matters
  • Implement proper error handling

💡 Pro Tips

  • Cost Optimization: Use message filtering to reduce unnecessary processing and costs
  • Scalability: SNS automatically scales, but consider SQS queue limits and tune accordingly
  • Testing: Use SNS message attributes for A/B testing and canary deployments
  • Debugging: Enable detailed monitoring and logging for troubleshooting

Common Architecture Patterns

graph TD subgraph "Microservices Communication" MS1[User Service] --> SNS1[User Events] MS2[Order Service] --> SNS2[Order Events] MS3[Payment Service] --> SNS3[Payment Events] SNS1 --> SQS1[Notification Queue] SNS2 --> SQS2[Fulfillment Queue] SNS3 --> SQS3[Accounting Queue] SQS1 --> LAMBDA1[Email Service] SQS2 --> LAMBDA2[Shipping Service] SQS3 --> LAMBDA3[Billing Service] end style SNS1 fill:#ff9999 style SNS2 fill:#ff9999 style SNS3 fill:#ff9999 style SQS1 fill:#99ccff style SQS2 fill:#99ccff style SQS3 fill:#99ccff

🎯 Summary

AWS SNS and SQS together provide a powerful messaging foundation for modern cloud applications. SNS excels at real-time, fan-out messaging patterns, while SQS provides reliable, asynchronous message processing. When combined, they enable resilient, scalable architectures that can handle complex distributed system requirements.

🚀 When to Use SNS

Real-time notifications, event broadcasting, triggering multiple downstream systems, mobile push notifications, and system alerts.

📬 When to Use SQS

Asynchronous job processing, decoupling application components, handling traffic spikes, and ensuring message durability.