Amazon SNS & Pub/Sub Messaging
A comprehensive deep dive into Amazon SNS — topics, subscriptions, fan-out patterns, message filtering, FIFO topics, delivery retry policies, mobile push, and pub/sub design patterns for the DVA-C02 exam.
What is Amazon SNS?
Amazon SNS (Simple Notification Service) is a fully managed publish/subscribe messaging service. A producer publishes one message to a topic and SNS instantly delivers it to all subscribers — fan-out to many consumers in a single publish call.
Core mental model: SNS is a megaphone. One publisher speaks; everyone subscribed hears it simultaneously. Contrast with SQS, which is a mailbox — one consumer picks up each message.
When to use SNS:
- Fan-out: one event must trigger multiple independent workflows
- Real-time push notifications (mobile, SMS, email)
- Decoupling microservices that need to react to the same event
- Cross-region or cross-account event delivery
Core Concepts
| Concept | Description |
|---|---|
| Topic | The communication channel. Publishers send to a topic ARN. |
| Subscription | An endpoint (SQS, Lambda, HTTP, email…) registered to a topic. |
| Publisher | Any AWS service or application that calls Publish on the topic. |
| Message | Up to 256 KB of text. Delivered to all active subscriptions. |
Scale limits:
- Up to 12,500,000 subscriptions per topic
- Up to 100,000 topics per account
- Messages delivered within milliseconds to all subscribers
Supported Subscription Protocols
| Protocol | Use case | Notes |
|---|---|---|
| Amazon SQS | Durable fan-out, async processing | Most common — combines push + pull |
| AWS Lambda | Serverless processing | Invokes function synchronously |
| HTTP / HTTPS | Webhooks, third-party systems | Must confirm subscription |
| Human notifications | Plain text or JSON | |
| Email-JSON | Machine-readable email | Full SNS message envelope |
| SMS | Text messages to phones | Per-message cost, country limits |
| Mobile Push | iOS (APNs), Android (FCM/GCM), etc. | Via platform application endpoint |
| Kinesis Data Firehose | Stream to S3, Redshift, OpenSearch | For high-volume log/event pipelines |
Publishing Messages
1import { SNSClient, PublishCommand } from '@aws-sdk/client-sns';
2
3const sns = new SNSClient({ region: 'us-east-1' });
4
5// Basic publish
6await sns.send(new PublishCommand({
7 TopicArn: 'arn:aws:sns:us-east-1:123456789:OrderEvents',
8 Subject: 'Order Placed', // used for email subscriptions
9 Message: JSON.stringify({
10 eventType: 'ORDER_PLACED',
11 orderId: 'ORD-001',
12 customerId: 'cust_A',
13 amount: 99.99,
14 }),
15 MessageAttributes: {
16 eventType: {
17 DataType: 'String',
18 StringValue: 'ORDER_PLACED', // used by filter policies
19 },
20 tier: {
21 DataType: 'String',
22 StringValue: 'premium',
23 },
24 },
25}));Message Structure Received by Subscribers
1{
2 "Type": "Notification",
3 "MessageId": "abc-123-def",
4 "TopicArn": "arn:aws:sns:us-east-1:123:OrderEvents",
5 "Subject": "Order Placed",
6 "Message": "{\"eventType\":\"ORDER_PLACED\",\"orderId\":\"ORD-001\"}",
7 "Timestamp": "2024-01-15T10:30:00.000Z",
8 "MessageAttributes": {
9 "eventType": { "Type": "String", "Value": "ORDER_PLACED" }
10 }
11}SQS subscribers receive this full SNS envelope as the SQS message body. Parse
Message(which is a JSON string) to get the actual payload.
Fan-Out Pattern (SNS + SQS)
The SNS + SQS fan-out is the most important SNS architecture pattern. It combines SNS's instant multi-delivery with SQS's durability and independent processing.
Why not S3 → 3 Lambda functions directly?
- S3 event notifications only support one destination per event type
- Fan-out via SNS → multiple SQS queues lets each consumer scale, retry, and DLQ independently
- If one consumer's Lambda is throttled, its SQS queue buffers the messages
1// Subscribe an SQS queue to an SNS topic
2import { SubscribeCommand } from '@aws-sdk/client-sns';
3
4await sns.send(new SubscribeCommand({
5 TopicArn: 'arn:aws:sns:us-east-1:123:FileUploaded',
6 Protocol: 'sqs',
7 Endpoint: 'arn:aws:sqs:us-east-1:123:image-resizer',
8 Attributes: {
9 RawMessageDelivery: 'true', // delivers Message string directly, not SNS envelope
10 },
11}));Message Filtering
By default, every subscriber receives every message. Filter policies let you route only relevant messages to each subscriber — reducing unnecessary Lambda invocations and SQS processing.
Filters are evaluated against MessageAttributes.
1// Subscription filter policy — only deliver ORDER_PLACED and ORDER_UPDATED events
2// for premium-tier customers with amount > 50
3{
4 "eventType": ["ORDER_PLACED", "ORDER_UPDATED"],
5 "tier": ["premium"],
6 "amount": [{ "numeric": [">", 50] }]
7}1// Attach filter policy when creating subscription
2await sns.send(new SubscribeCommand({
3 TopicArn: 'arn:aws:sns:us-east-1:123:OrderEvents',
4 Protocol: 'sqs',
5 Endpoint: 'arn:aws:sqs:us-east-1:123:premium-orders',
6 Attributes: {
7 FilterPolicy: JSON.stringify({
8 eventType: ['ORDER_PLACED', 'ORDER_UPDATED'],
9 tier: ['premium'],
10 }),
11 FilterPolicyScope: 'MessageAttributes', // or 'MessageBody'
12 },
13}));Filter operators:
| Operator | Example | Matches |
|---|---|---|
| Exact match | ["ORDER_PLACED"] | Attribute equals "ORDER_PLACED" |
| Multiple values | ["A", "B"] | Attribute equals "A" OR "B" |
| Numeric range | [{"numeric": [">", 50, "<=", 100]}] | 50 < value ≤ 100 |
| Prefix | [{"prefix": "ORDER_"}] | Attribute starts with "ORDER_" |
| Exists | [{"exists": true}] | Attribute is present |
| Does not exist | [{"exists": false}] | Attribute is absent |
| Anything but | [{"anything-but": "CANCELLED"}] | Attribute is not "CANCELLED" |
SNS FIFO Topics
SNS FIFO topics provide strict ordering and exactly-once delivery — mirroring SQS FIFO.
| Feature | Standard Topic | FIFO Topic |
|---|---|---|
| Ordering | Best-effort | Strict per MessageGroupId |
| Deduplication | No | Yes (5-minute window) |
| Throughput | 30,000 msg/sec | 300 msg/sec (3,000 with batching) |
| Subscribers | All protocols | SQS FIFO only |
| Name suffix | Any | Must end in .fifo |
1// Publishing to FIFO topic
2await sns.send(new PublishCommand({
3 TopicArn: 'arn:aws:sns:us-east-1:123:OrderEvents.fifo',
4 Message: JSON.stringify({ orderId: 'ORD-001', action: 'PLACE' }),
5 MessageGroupId: 'customer-cust_A', // ordering group
6 MessageDeduplicationId: 'ORD-001-PLACE', // dedup key
7}));Delivery Retry Policy
For HTTP/HTTPS subscriptions, SNS retries failed deliveries with exponential backoff:
| Phase | Retries | Delay |
|---|---|---|
| Immediate | 3 | No delay |
| Pre-backoff | 2 | 1 second |
| Backoff | 10 | 10s → 20s → 40s… (up to 20 min) |
| Post-backoff | Up to 100,000 | 20 minutes each |
Total retry duration: up to 23 days.
For SQS and Lambda subscribers, SNS delivery is near-instant with built-in retries. If delivery ultimately fails, SNS can route to a Dead-Letter Queue on the subscription.
1# Set a DLQ on an SNS subscription
2aws sns set-subscription-attributes \
3 --subscription-arn arn:aws:sns:us-east-1:123:OrderEvents:sub-abc \
4 --attribute-name RedrivePolicy \
5 --attribute-value '{"deadLetterTargetArn":"arn:aws:sqs:us-east-1:123:sns-dlq"}'Mobile Push Notifications
SNS supports push notifications to mobile platforms through Platform Application Endpoints.
1// Register a device and send a push notification
2import { CreatePlatformEndpointCommand, PublishCommand } from '@aws-sdk/client-sns';
3
4// 1. Register the device token from APNs/FCM
5const { EndpointArn } = await sns.send(new CreatePlatformEndpointCommand({
6 PlatformApplicationArn: 'arn:aws:sns:us-east-1:123:app/APNS/MyApp',
7 Token: 'device-token-from-apns',
8 CustomUserData: JSON.stringify({ userId: 'usr_01' }),
9}));
10
11// 2. Send push notification directly to the device
12await sns.send(new PublishCommand({
13 TargetArn: EndpointArn,
14 MessageStructure: 'json',
15 Message: JSON.stringify({
16 APNS: JSON.stringify({
17 aps: {
18 alert: { title: 'Order Shipped!', body: 'Your order ORD-001 is on the way.' },
19 badge: 1,
20 sound: 'default',
21 },
22 }),
23 default: 'Your order ORD-001 has shipped.',
24 }),
25}));Access Control — Topic Policies
SNS topics use resource-based policies to control cross-account or cross-service publishing:
1{
2 "Version": "2012-10-17",
3 "Statement": [
4 {
5 "Effect": "Allow",
6 "Principal": { "Service": "s3.amazonaws.com" },
7 "Action": "SNS:Publish",
8 "Resource": "arn:aws:sns:us-east-1:123:FileUploaded",
9 "Condition": {
10 "ArnLike": { "aws:SourceArn": "arn:aws:s3:::my-upload-bucket" }
11 }
12 }
13 ]
14}SNS vs SQS vs EventBridge
| Feature | SNS | SQS | EventBridge |
|---|---|---|---|
| Model | Push (pub/sub) | Pull (polling) | Event routing |
| Message persistence | ❌ No storage | ✅ Up to 14 days | ❌ No storage |
| Fan-out | ✅ Native | ❌ One consumer at a time | ✅ Up to 5 targets per rule |
| Message filtering | ✅ MessageAttributes | ❌ | ✅ Rich event pattern matching |
| Ordering | FIFO topic | FIFO queue | ❌ |
| Event schema registry | ❌ | ❌ | ✅ |
| SaaS integrations | ❌ | ❌ | ✅ 200+ partners |
| Replay events | ❌ | ❌ | ✅ Archive + replay |
| Max message size | 256 KB | 256 KB | 256 KB |
DVA-C02 Quick Reference
| Topic | Key Fact |
|---|---|
| SNS delivery model | Push — no polling needed |
| Max message size | 256 KB |
| Max subscriptions per topic | 12,500,000 |
| Supported subscriber protocols | SQS, Lambda, HTTP/HTTPS, Email, SMS, Mobile Push, Firehose |
| Fan-out pattern | SNS → multiple SQS queues |
| Message persistence | None — not stored after delivery attempt |
| Filter policy scope | MessageAttributes or MessageBody |
| FIFO topic subscriber restriction | SQS FIFO queues only |
| FIFO topic throughput | 300 msg/sec (3,000 with batching) |
| HTTP retry duration | Up to 23 days |
| Subscription DLQ | Per-subscription RedrivePolicy |
RawMessageDelivery | Delivers raw Message string, skips SNS envelope |
| Cross-account publishing | Requires SNS topic policy |
| S3 → multiple Lambda pattern | Use S3 → SNS → multiple SQS fan-out |
Practice Questions5
Q1. A developer publishes a message to an SNS topic that has 3 subscriptions: one Lambda, one SQS queue, and one HTTP endpoint. The HTTP endpoint is temporarily unavailable. What happens to the HTTP delivery?
Select one answer before revealing.
Q2. A developer wants to ensure that different types of subscribers to an SNS topic only receive the messages relevant to them. For example, "order" subscribers should not receive "payment" messages. Which SNS feature enables this without creating separate topics?
Select one answer before revealing.
Q3. A company wants to send notifications via SNS to both an SQS queue and email subscribers. They are concerned about losing messages if the SQS queue is overwhelmed. Which SNS feature should they configure on the SQS subscription?
Select one answer before revealing.
Q4. A developer publishes a message to an SNS FIFO topic and wants to prevent duplicate messages from being processed by the SQS FIFO subscriber within a 5-minute window. Which mechanism handles this?
Select one answer before revealing.
Q5. A developer needs to send the same promotional notification to 500,000 mobile app users via SNS. Creating individual subscriptions for each user would be complex. Which SNS feature handles this at scale?
Select one answer before revealing.