iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

SNS

SNS (Simple Notification Service) is AWSs managed pub/sub. Publishers push messages to a topic; subscribers (SQS queues, Lambda, HTTPS endpoints, email, SMS, mobile push) receive them. Pair with SQS for durable fan-out, or push to Lambda for serverless event handling. The simplest production-grade pub/sub on AWS.

Topic + SQS subscriber + Lambda subscriber + filter policies

EXAMPLE
# 1) Create a topic
topic=$(aws sns create-topic --name shop-events --query 'TopicArn' --output text)

# 2) Publish a message
aws sns publish --topic-arn "$topic" \
  --message '{"type":"OrderPaid","orderId":"o1","amount":4995}' \
  --message-attributes '{"type":{"DataType":"String","StringValue":"OrderPaid"}}'

# 3) SQS fanout — most common pattern
queue=$(aws sqs create-queue --queue-name shop-analytics \
  --attributes 'VisibilityTimeout=30,MessageRetentionPeriod=1209600' \
  --query 'QueueUrl' --output text)
queue_arn=$(aws sqs get-queue-attributes --queue-url "$queue" \
  --attribute-names QueueArn --query 'Attributes.QueueArn' --output text)

# Allow SNS to write to the queue
aws sqs set-queue-attributes --queue-url "$queue" \
  --attributes Policy='{"Version":"2012-10-17","Statement":[{
    "Effect":"Allow",
    "Principal":{"Service":"sns.amazonaws.com"},
    "Action":"sqs:SendMessage",
    "Resource":"'"$queue_arn"'",
    "Condition":{"ArnEquals":{"aws:SourceArn":"'"$topic"'"}}
  }]}'

# Subscribe queue to topic
aws sns subscribe --topic-arn "$topic" --protocol sqs --notification-endpoint "$queue_arn"

# Worker pulls from SQS
# const sqs = new SQSClient({...});
# const res = await sqs.send(new ReceiveMessageCommand({ QueueUrl, MaxNumberOfMessages: 10, WaitTimeSeconds: 20 }));
# for (const m of res.Messages ?? []) {
#   await process(JSON.parse(m.Body)); await sqs.send(new DeleteMessageCommand({ QueueUrl, ReceiptHandle: m.ReceiptHandle }));
# }

# 4) Lambda subscriber
fn_arn=$(aws lambda create-function --function-name shop-analytics \
  --runtime nodejs20.x --role arn:aws:iam::...:role/lambda-role \
  --handler handler.handler --zip-file fileb://handler.zip \
  --query 'FunctionArn' --output text)
aws lambda add-permission --function-name shop-analytics \
  --statement-id sns-invoke --action lambda:InvokeFunction \
  --principal sns.amazonaws.com --source-arn "$topic"
aws sns subscribe --topic-arn "$topic" --protocol lambda --notification-endpoint "$fn_arn"

# 5) Filter policies — subscribers only receive matching events
aws sns set-subscription-attributes --subscription-arn <sub-arn> \
  --attribute-name FilterPolicy \
  --attribute-value '{"type":["OrderPaid","OrderShipped"]}'

aws sns set-subscription-attributes --subscription-arn <sub-arn> \
  --attribute-name FilterPolicyScope --attribute-value MessageBody
# 'MessageBody' filters on JSON body (newer); default is message-attributes-only.

# 6) FIFO topics — when ordering matters
fifo_topic=$(aws sns create-topic --name shop-events.fifo --attributes FifoTopic=true,ContentBasedDeduplication=true --query 'TopicArn' --output text)
aws sns publish --topic-arn "$fifo_topic" --message '...' --message-group-id 'orders' --message-deduplication-id 'o1-paid'

# 7) Encryption in transit + at rest
# - Default: HTTPS in transit (SNS endpoint is HTTPS)
# - At-rest: enable SSE via KMS key
aws sns set-topic-attributes --topic-arn "$topic" \
  --attribute-name KmsMasterKeyId --attribute-value alias/aws/sns

# 8) DLQ for failed deliveries (lambda/HTTP subscribers)
aws sns set-subscription-attributes --subscription-arn <sub-arn> \
  --attribute-name RedrivePolicy \
  --attribute-value '{"deadLetterTargetArn":"arn:aws:sqs:...:dlq"}'

# 9) Monitoring
# CloudWatch metrics:
# - NumberOfMessagesPublished
# - NumberOfNotificationsDelivered
# - NumberOfNotificationsFailed
# Set alarm on Failed > 0 for 5m.

# 10) Decision matrix
# - Need persistence + retry?           SQS subscriber
# - Need serverless handler?            Lambda subscriber
# - Mobile push (iOS / Android)?       Direct platform endpoint
# - Email / SMS alerts?                 SNS supports them but better via SES / Twilio
# - High fan-out + durability?          SNS -> N x SQS pattern
# - Strict ordering?                    FIFO topic + FIFO queues
# - Cross-region / cross-account?       SNS supports both with proper policies

# 11) Pitfalls
# - SNS subscriber failures silently dropped (no DLQ) -> data loss
# - Forgetting subscription confirmation for HTTP/HTTPS subscribers
# - High-volume direct SMS (cost spike); use rate limits
# - FIFO topics + non-FIFO queues -> error
# - Confusing message-attribute filter with body filter (set FilterPolicyScope correctly)

Why it matters

SNS -> N x SQS is the canonical AWS pub/sub for durable fan-out. Publishers do not know subscribers; each consumer has its own retry + DLQ + backpressure story via its queue. Reach for EventBridge when you need richer filtering / routing across many services; reach for Kinesis or MSK when ordering + replay over long windows matter.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
# Pub/sub topic — fan out one message to many subscribers (SQS, Lambda, email).
Try it Yourself »

Discussion

Loading…