Reading25 min read·Module 2High exam weight

Amazon SNS (Notifications & Fan-out)

Key concepts

  • Topics and subscriptions

  • Fan-out pattern with SQS

  • Message filtering

  • FIFO topics

  • Mobile push notifications

Overview

Amazon Simple Notification Service (SNS) is a fully managed pub/sub messaging service that enables you to decouple microservices, distributed systems, and serverless applications. SNS follows a push-based model where messages published to topics are immediately delivered to all subscribers, eliminating the need for polling.

Understanding SNS is critical for the SAA-C03 exam because it's a core component of event-driven architectures, enabling fan-out patterns, real-time notifications, and cross-service communication. You must know when to use SNS vs SQS, how to implement message filtering, and how to design resilient pub/sub architectures.

Pub/Sub Push Model

SNS is a push-based pub/sub service where publishers send messages to topics and all subscribers receive the message immediately. This contrasts with SQS's pull-based polling model.

Exam Tip

Focus on fan-out patterns (SNS → multiple SQS queues), message filtering to reduce processing, FIFO topics for ordered delivery, and combining SNS+SQS for resilient architectures. Know subscriber types: Lambda, SQS, HTTP/S, email, SMS, mobile push.


Key Concepts

SNS Architecture

SNS Architecture Overview
Figure 1: SNS topics push messages to multiple subscriber types simultaneously

SNS Topics

A topic is a logical access point and communication channel. Publishers send messages to topics, and subscribers receive messages from topics they're subscribed to. Topics support up to 12.5 million subscriptions per topic and 100,000 topics per account.

Publishers and Subscribers

Publishers are entities that send messages to topics (applications, AWS services, or users). Subscribers are endpoints that receive messages: Lambda functions, SQS queues, HTTP/S endpoints, email addresses, SMS numbers, and mobile push notifications. A single message can fan out to multiple subscribers simultaneously.

Subscriber Types

SNS Subscriber Types

Subscriber TypeUse CaseDelivery
Amazon SQSDecouple processing, buffer messagesJSON wrapped message
AWS LambdaReal-time serverless processingInvokes function directly
HTTP/S EndpointWebhooks, external APIsPOST request to endpoint
Email/Email-JSONHuman notificationsEmail with message content
SMSMobile text notificationsDirect SMS message
Mobile PushiOS, Android, Fire OS appsPush notification to device
JSONSNS Message Structure
{
  "Type": "Notification",
  "MessageId": "da567617-4c3a-4a36-a9f8-abc123",
  "TopicArn": "arn:aws:sns:us-east-1:123456789012:MyTopic",
  "Subject": "Order Processed",
  "Message": "Order #12345 has been processed",
  "Timestamp": "2025-01-18T12:00:00.000Z",
  "SignatureVersion": "1",
  "Signature": "...",
  "MessageAttributes": {
    "orderType": {
      "Type": "String",
      "Value": "priority"
    }
  }
}

Fan-Out Pattern

SNS Fan-Out Pattern
Figure 2: Fan-out pattern delivers one message to multiple SQS queues for parallel processing

Fan-Out Architecture

The fan-out pattern publishes a single message to an SNS topic that fans out to multiple SQS queues. Each queue can have different consumers processing the same message for different purposes (logging, analytics, notifications, etc.). This decouples publishers from consumers and enables parallel processing.

Fan-Out Best Practice

Combine SNS + SQS for the "fan-out with persistence" pattern. SNS provides immediate fan-out, while SQS provides message durability if consumers are temporarily unavailable. This is the recommended pattern for resilient event-driven systems.

Message Filtering

Subscription Filter Policies

Filter policies enable subscribers to receive only a subset of messages. Filters can apply to message attributes (default) or message body (payload-based filtering). This reduces unnecessary processing and costs by filtering at the SNS level rather than in consumer applications.

JSONMessage Filter Policy Examples
// Filter by message attribute
{
  "store": ["wholesale"],
  "price_usd": [{"numeric": [">=", 100]}]
}

// Subscriber only receives messages where:
// - store attribute equals "wholesale" AND
// - price_usd is greater than or equal to 100

// Filter by message body (payload-based)
// Set FilterPolicyScope to "MessageBody"
{
  "customer": {
    "tier": ["premium", "enterprise"]
  }
}

Filter Policy Scope

ScopeFilters OnUse Case
MessageAttributes (default)Message attributes onlyStructured metadata filtering
MessageBodyJSON message body contentFilter on actual message payload

Standard vs FIFO Topics

SNS Standard vs FIFO Topics
Figure 3: Standard topics prioritize throughput while FIFO topics guarantee ordering

Standard vs FIFO Topics

FeatureStandard TopicFIFO Topic
Message orderingBest-effortStrict FIFO per message group
DeduplicationNo guaranteeContent-based or deduplication ID
ThroughputNearly unlimited3,000 msg/s or 10 MB/s
SubscribersAll subscriber typesSQS FIFO queues only
Use caseHigh-throughput, order not criticalFinancial transactions, inventory

FIFO Topic Concepts

Message Group ID: Messages with the same group ID are delivered in order. Different groups can be processed in parallel (up to 300 msg/s per group).

Deduplication: Either content-based (SHA-256 hash of body) or explicit deduplication ID. 5-minute deduplication window prevents duplicate delivery.

PYPublishing to FIFO Topic
import boto3

sns = boto3.client('sns')

response = sns.publish(
    TopicArn='arn:aws:sns:us-east-1:123456789012:MyTopic.fifo',
    Message='Process order #12345',
    MessageGroupId='customer-123',      # Required for FIFO
    MessageDeduplicationId='order-12345' # Or use content-based
)

Raw Message Delivery

Raw Message Delivery

By default, SNS wraps messages in JSON with metadata. Enabling raw message delivery sends the message exactly as published, without the JSON wrapper. Useful when subscribers expect a specific format or to reduce message size.

Raw vs JSON Delivery

FeatureJSON Delivery (Default)Raw Delivery
Message formatWrapped in SNS JSON envelopeExact published message
Metadata includedTopic ARN, timestamp, signatureNone (stripped)
Message attributesIncluded in JSONMax 10 attributes for SQS
Use caseNeed SNS metadataPass-through to consumers

Security and Encryption

Access Control

SNS Access Policies

SNS uses resource-based policies (topic policies) and IAM policies to control access. Topic policies define who can publish to or subscribe to a topic. Avoid Principal: "*" to prevent public access.

JSONSNS Topic Policy - Cross-Account Access
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "AllowCrossAccountPublish",
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::111122223333:root"
      },
      "Action": "sns:Publish",
      "Resource": "arn:aws:sns:us-east-1:123456789012:MyTopic"
    }
  ]
}

Encryption

SNS Encryption Options

TypeProtectionConfiguration
In-transit (TLS)Data between client and SNSHTTPS endpoints required
At-rest (SSE-KMS)Stored messagesEnable SSE with KMS key
Client-sideEnd-to-end encryptionEncrypt before publish
SHEnable Server-Side Encryption
aws sns set-topic-attributes \
  --topic-arn arn:aws:sns:us-east-1:123456789012:MyTopic \
  --attribute-name KmsMasterKeyId \
  --attribute-value alias/aws/sns

# Or use custom CMK for cross-account access
aws sns set-topic-attributes \
  --topic-arn arn:aws:sns:us-east-1:123456789012:MyTopic \
  --attribute-name KmsMasterKeyId \
  --attribute-value arn:aws:kms:us-east-1:123456789012:key/12345678-1234

VPC Endpoints

SNS VPC Endpoints

Use VPC endpoints (PrivateLink) to access SNS from private subnets without internet access. This keeps traffic within AWS network and is required for applications handling PII or sensitive data in private subnets.


Mobile Push Notifications

SNS Mobile Push

SNS Mobile Push delivers push notifications to iOS (APNs), Android (FCM), Fire OS (ADM), Windows (WNS), and Baidu (China). You register device tokens with SNS platform applications, then publish to mobile endpoints or topics.

TEXTMobile Push Flow
1. Create Platform Application
   └── Register with push service (APNs, FCM, etc.)
       └── Get platform credentials

2. Register Device Token
   └── App sends device token to your backend
       └── Backend creates SNS Platform Endpoint
           └── Returns endpoint ARN

3. Send Notification
   └── Publish to endpoint ARN (direct)
   └── OR subscribe endpoint to topic (broadcast)

Integration Patterns

SNS + Lambda

Lambda as Subscriber

Lambda functions can subscribe directly to SNS topics for real-time processing. Lambda scales automatically with message volume. For reliability, combine with SQS: SNS → SQS → Lambda with batch processing.

SNS + EventBridge

EventBridge Integration

EventBridge can trigger SNS topics as targets, and SNS can forward to EventBridge. Use EventBridge for complex routing and filtering rules, SNS for simple fan-out. EventBridge supports content-based filtering on the entire event.

Cross-Region and Cross-Account

TEXTCross-Region Fan-Out
Publisher (us-east-1)
    │
    ▼
SNS Topic (us-east-1)
    │
    ├──► SQS Queue (us-east-1)
    │
    └──► SNS Topic (eu-west-1)  ← Cross-region subscription
            │
            ├──► SQS Queue (eu-west-1)
            │
            └──► Lambda (eu-west-1)

Best Practices

Architecture Best Practices

TEXTResilient SNS Architecture
Best Practice: Topic-Queue-Chaining

Publisher
    │
    ▼
SNS Topic (fan-out)
    │
    ├──► SQS Queue 1 ──► Service A (can be offline)
    │
    ├──► SQS Queue 2 ──► Service B (can be offline)
    │
    └──► SQS Queue 3 ──► Service C (can be offline)

Benefits:
├── Messages persist even if consumers are down
├── Each service processes at its own pace
├── Failed messages go to DLQ for retry
└── Decouples all services completely

Cost Optimization

Cost Considerations

HTTP/S endpoints are most cost-effective for high-volume notifications.

Email notifications incur higher per-message costs - use judiciously.

Message filtering reduces costs by preventing unnecessary deliveries.

Payload size matters - messages up to 256 KB, but costs increase with size.

Delivery Retry Policies

Delivery Retry Policies by Endpoint

EndpointRetry BehaviorDLQ Support
HTTP/SConfigurable (1-100 retries)Yes
SQSImmediate (highly reliable)Via SQS DLQ
Lambda2 retries with backoffYes (via Lambda DLQ)
Email/SMSNo retriesNo

Common Exam Scenarios

Exam Scenarios

ScenarioSolutionWhy
Process same event in multiple servicesSNS → multiple SQS queues (fan-out)Parallel processing, decoupled
Real-time processing with reliabilitySNS → SQS → LambdaSQS buffers if Lambda fails
Send subset of messages to subscriberSNS message filteringFilter at SNS, reduce processing
Guaranteed message orderingSNS FIFO → SQS FIFOStrict ordering and deduplication
Notify on EC2 state changesEventBridge → SNS → Email/SMSEvent routing to notifications
Private subnet access to SNSVPC endpoint (PrivateLink)No internet gateway needed
Cross-account event sharingSNS topic policy + cross-account IAMExplicit permissions in both
Mobile app push notificationsSNS Mobile PushMulti-platform support

Common Pitfalls

Pitfall 1: Direct Lambda Subscription Without Queue

Mistake: Subscribing Lambda directly to SNS without an SQS buffer.

Why it fails: If Lambda is throttled or fails, messages are lost after retries.

Correct Approach: Use SNS → SQS → Lambda for reliability. SQS persists messages.

Pitfall 2: Not Using Message Filtering

Mistake: All subscribers receive all messages, filtering in application code.

Why it fails: Wastes compute resources processing irrelevant messages.

Correct Approach: Use SNS filter policies to deliver only relevant messages.

Pitfall 3: FIFO Topic with Non-FIFO Subscribers

Mistake: Trying to subscribe Lambda or HTTP to a FIFO topic.

Why it fails: FIFO topics only support SQS FIFO (and standard) queue subscriptions.

Correct Approach: Use FIFO topic → SQS FIFO → Lambda for ordered processing.

Pitfall 4: Public Topic Policies

Mistake: Using Principal: "*" in topic policies.

Why it fails: Anyone can publish or subscribe, creating security risks.

Correct Approach: Specify exact account IDs or use condition keys for VPC endpoints.

Pitfall 5: Ignoring Raw Message Delivery Limits

Mistake: Sending more than 10 message attributes with raw delivery enabled.

Why it fails: Messages are discarded as client-side errors for SQS.

Correct Approach: Disable raw delivery for messages with many attributes, or reduce attributes.



Quick Reference

SNS Limits

Key SNS Limits

ResourceStandardFIFO
Topics per account100,0001,000
Subscriptions per topic12,500,000100
Messages per secondNearly unlimited3,000 or 10 MB/s
Message size256 KB256 KB
Message attributes10 max10 max
Filter policies per topic200N/A

Message Retention

TEXTSNS Message Lifecycle
1. Publisher sends message to topic
   └── Message validated (size, attributes)

2. SNS processes message
   ├── Applies filter policies
   └── Determines eligible subscribers

3. Delivery attempts
   ├── Immediate for most endpoints
   ├── Retry policy for HTTP/S failures
   └── Success or failure logged

4. After all deliveries
   └── Message deleted (no persistence in SNS)

Note: SNS does NOT retain messages!
Use SQS if you need persistence.

Common CLI Commands

SHSNS CLI Commands
# Create topic
aws sns create-topic --name MyTopic

# Create FIFO topic
aws sns create-topic --name MyTopic.fifo \
  --attributes FifoTopic=true,ContentBasedDeduplication=true

# Subscribe SQS queue
aws sns subscribe \
  --topic-arn arn:aws:sns:us-east-1:123456789012:MyTopic \
  --protocol sqs \
  --notification-endpoint arn:aws:sqs:us-east-1:123456789012:MyQueue

# Publish message
aws sns publish \
  --topic-arn arn:aws:sns:us-east-1:123456789012:MyTopic \
  --message "Hello World" \
  --message-attributes '{"store":{"DataType":"String","StringValue":"retail"}}'

# Set filter policy
aws sns set-subscription-attributes \
  --subscription-arn arn:aws:sns:us-east-1:123456789012:MyTopic:abc123 \
  --attribute-name FilterPolicy \
  --attribute-value '{"store":["retail"]}'

Test Your Knowledge

Q

A company needs to process the same order event in three different microservices: inventory, shipping, and analytics. What is the MOST scalable and decoupled architecture?

AUse SQS with multiple consumers polling the same queue
BUse SNS topic with three SQS queue subscriptions
CUse EventBridge with three Lambda targets
DUse Step Functions to orchestrate the three services
Q

An application publishes order messages with attributes for order type (retail/wholesale) and region. A subscriber only needs to process wholesale orders from the US region. What should the architect configure?

ALambda function to filter messages after receiving
BSNS filter policy on the subscription
CSQS message filtering on the queue
DEventBridge content-based rule
Q

A financial services company needs to ensure stock trade messages are processed in exact order with no duplicates. Which SNS configuration is required?

AStandard topic with message deduplication ID
BFIFO topic with SQS FIFO queue subscription
CStandard topic with Lambda subscriber and DLQ
DFIFO topic with HTTP/S endpoint subscription
Q

An application in a private subnet needs to publish messages to SNS without using a NAT gateway or internet gateway. What is the MOST secure solution?

AUse AWS Direct Connect to access SNS
BCreate an SNS VPC endpoint (PrivateLink)
CEnable public IP on the EC2 instances
DUse a bastion host to proxy SNS requests

Further Reading

Related services

SNSSQSLambda