Thursday, October 23, 2025

AWS - SNS

Amazon SNS is a fully managed publish/subscribe messaging service that enables applications, microservices, and users to communicate asynchronously — meaning messages are pushed to all interested subscribers instantly.

In short:

SNS = Publish once, deliver to many subscribers (fan-out)

It decouples services and allows parallel message delivery to multiple endpoints.


SNS Key Features

FeatureDescription
Pub/Sub messagingOne publisher sends a message to many subscribers simultaneously.
Multiple protocolsSubscribers can be Email, SMS, HTTP/S endpoints, AWS Lambda, or SQS queues.
Fan-out patternA single event triggers multiple downstream processes.
High availabilityFully managed, scalable, and reliable (multi-AZ).
SecurityIAM + topic policies + encryption with AWS KMS.

SNS vs. EventBridge

This is a common AWS interview and design question — let’s break it down clearly:

FeatureAmazon SNSAmazon EventBridge
TypePub/Sub messaging serviceEvent bus for event-driven architecture
Message ModelPublisher → Topic → SubscribersEvent producer → Event bus → Rules → Targets
Routing LogicAll subscribers get the same message (fan-out)Rules filter and route events based on content
Supported TargetsLambda, SQS, HTTP/S, SMS, Email, Mobile20+ AWS services + SaaS apps (Zendesk, Datadog, etc.)
FilteringBasic (per-subscription filter policies)Advanced content-based filtering using JSON pattern
Event FormatCustom message (you define the payload)Standardized JSON “event envelope”
DeliveryPush-based to all subscribersRouted to specific targets based on rule conditions
Best ForAlerts, notifications, fan-out processingComplex event-driven integration across AWS and SaaS
CostCheaperSlightly higher (charged per event and rule)

In short:

  • Use SNS when → you need simple notifications or fan-out (one-to-many).

  • Use EventBridge when → you need intelligent routing, filtering, or event-driven workflows.


Example Architecture — SNS with Multiple Subscribers

Let’s design a multi-subscriber architecture using SNS:

Scenario: EC2 Monitoring & Alert System

When EC2 CPU utilization > 80%, CloudWatch sends an alert → SNS → multiple subscribers take different actions.


Flow:

  1. CloudWatch Alarm detects EC2 CPU spike

  2. Alarm publishes message to SNS topicarn:aws:sns:us-east-1:123456789012:EC2-Alert-Topic

  3. SNS fans out the message to multiple subscribers:

    • Email subscriber: Notifies sysadmin

    • Lambda function: Automatically scales up EC2 instance count

    • SQS queue: Stores message for audit/log processing

    • SMS subscriber: Sends urgent text alert to on-call engineer


Components

ComponentPurpose
CloudWatch AlarmDetects threshold breach and triggers SNS topic
SNS Topic: EC2-Alert-TopicCentral notification hub
Lambda SubscriberExecutes auto-remediation logic (e.g., scale up EC2)
SQS QueueStores events for downstream analytics/audit
Email SubscriberNotifies support engineers
SMS SubscriberSends urgent mobile alerts

Message Example (JSON Payload)

{ "AlarmName": "HighCPUUtilization", "InstanceId": "i-0abc12345def6789", "MetricName": "CPUUtilization", "Threshold": 80, "CurrentValue": 92.3, "Region": "us-east-1", "Time": "2025-10-21T14:10:00Z" }

Architecture Diagram (described for PPT/draw.io)

+----------------------+ | CloudWatch Alarm | | (EC2 CPU > 80%) | +----------+-----------+ | v +---------------+ | SNS Topic | | EC2-Alert-Topic| +-------+--------+ | ----------------------------------------- | | | | v v v v +---------+ +---------+ +----------+ +----------+ | Email | | Lambda | | SQS | | SMS | | Notify | | AutoScale| | Logging | | On-Call | +---------+ +---------+ +----------+ +----------+

Cost & Reliability

FeatureSNS
Pricing~$0.50 per million publishes
RetriesYes, with exponential backoff for Lambda/HTTP
DurabilityMessages stored redundantly across multiple AZs
MonitoringIntegrated with CloudWatch metrics and logs

When to Combine SNS + Event Bridge

In modern AWS event-driven setups, they’re often used together:

Example:
EventBridge captures all EC2 events → applies filtering rules → sends to SNS topic → SNS fans out to Lambda + SQS + email.

So you can use EventBridge for filtering/routing and SNS for multi-channel notification delivery

Cli Commands Example 

#!/bin/bash

# CONFIGURATION

REGION="us-east-1"

TOPIC_NAME="my-cli-demo-topic"

EMAIL_ENDPOINT="your-email@example.com"   # change this

PROFILE="default"                         # change if needed

echo "Creating SNS topic..."


# CREATE TOPIC

TOPIC_ARN=$(aws sns create-topic \

  --name $TOPIC_NAME \

  --region $REGION \

  --profile $PROFILE \

  --query 'TopicArn' \

  --output text)

echo "Topic ARN: $TOPIC_ARN"


# SUBSCRIBE (EMAIL)

echo "Subscribing email to topic..."

SUBSCRIPTION_ARN=$(aws sns subscribe \

  --topic-arn $TOPIC_ARN \

  --protocol email \

  --notification-endpoint $EMAIL_ENDPOINT \

  --region $REGION \

  --profile $PROFILE \

  --query 'SubscriptionArn' \

  --output text)

echo "Subscription ARN: $SUBSCRIPTION_ARN"

echo "IMPORTANT: Confirm the subscription from your email before publishing."


# PUBLISH MESSAGE

echo "Publishing message..."

aws sns publish \

  --topic-arn $TOPIC_ARN \

  --message "Hello from bundled SNS CLI script" \

  --subject "SNS CLI Demo" \

  --region $REGION \

  --profile $PROFILE


# LIST TOPICS

echo "Listing SNS topics..."

aws sns list-topics \

  --region $REGION \

  --profile $PROFILE


# DELETE TOPIC

echo "Deleting topic..."

aws sns delete-topic \

  --topic-arn $TOPIC_ARN \

  --region $REGION \

  --profile $PROFILE

echo "Topic deleted."

echo "Done."

No comments:

Post a Comment

Node | Cluster Vs Worker Threads

Cluster: Multiple processes (scale app across CPU cores) Worker Threads: Multiple threads (handle CPU-heavy work inside one process) Cluster...