TL;DR
Explore AWS Simple Notification Service (SNS) features and learn how to build scalable pub/sub messaging systems
import { MermaidDiagram } from '@/components/mermaid-diagram'
Amazon Simple Notification Service (SNS) is a fully managed pub/sub messaging service. This comprehensive guide explores SNS features and how to implement them effectively in your applications.
graph TB
SNS[SNS Topic]
subgraph Publishers
Lambda1[Lambda Function]
CW[CloudWatch Alarms]
S3[S3 Events]
App[Applications]
end subgraph Subscribers
SQS[SQS Queue]
Lambda2[Lambda Function]
HTTP[HTTP/HTTPS Endpoints]
Email[Email]
SMS[SMS]
end Lambda1 --> SNS
CW --> SNS
S3 --> SNS
App --> SNS
SNS --> SQS
SNS --> Lambda2
SNS --> HTTP
SNS --> Email
SNS --> SMS style SNS fill:#3b82f6,stroke:#2563eb,color:white
style Lambda1 fill:#f1f5f9,stroke:#64748b
style Lambda2 fill:#f1f5f9,stroke:#64748b
style CW fill:#f1f5f9,stroke:#64748b
style S3 fill:#f1f5f9,stroke:#64748b
style App fill:#f1f5f9,stroke:#64748b
style SQS fill:#f1f5f9,stroke:#64748b
style HTTP fill:#f1f5f9,stroke:#64748b
style Email fill:#f1f5f9,stroke:#64748b
style SMS fill:#f1f5f9,stroke:#64748b
/>
}
$1
$1
$1
1. Topics
- Message distribution channels
- Multiple subscription protocols
- Access control policies
2. Publishers
- AWS services integration
- Application publishing
- Cross-account publishing
3. Subscribers
- Multiple endpoint types
- Message filtering
- Delivery retry policies
$1
$1
`` import boto3 sns = boto3.client('sns') response = sns.create_topic(
Name='my-notification-topic',
Tags=[
{
'Key': 'Environment',
'Value': 'Production'
}
]
) fifo_response = sns.create_topic(
Name='my-notification-topic.fifo',
Attributes={
'FifoTopic': 'true',
'ContentBasedDeduplication': 'true'
}
)
python
`Create a standard topic
Create a FIFO topic
$1
` response = sns.subscribe(
TopicArn='arn:aws:sns:region:account-id:my-notification-topic',
Protocol='sqs',
Endpoint='arn:aws:sqs:region:account-id:my-queue'
) response = sns.subscribe(
TopicArn='arn:aws:sns:region:account-id:my-notification-topic',
Protocol='lambda',
Endpoint='arn:aws:lambda:region:account-id:function:my-function'
) response = sns.subscribe(
TopicArn='arn:aws:sns:region:account-id:my-notification-topic',
Protocol='https',
Endpoint='https://example.com/notifications'
)
python
`Subscribe an SQS queue
Subscribe a Lambda function
Subscribe an HTTP/HTTPS endpoint
$1
` response = sns.publish(
TopicArn='arn:aws:sns:region:account-id:my-notification-topic',
Message='Hello from SNS!',
Subject='Test Notification'
) response = sns.publish(
TopicArn='arn:aws:sns:region:account-id:my-notification-topic',
Message='Hello from SNS!',
MessageAttributes={
'Priority': {
'DataType': 'String',
'StringValue': 'High'
},
'Environment': {
'DataType': 'String',
'StringValue': 'Production'
}
}
)
python
`Publish a simple message
Publish with message attributes
$1
$1
` {
"filter_policy": {
"Priority": ["High", "Critical"],
"Environment": ["Production"],
"Version": [{"numeric": [">=", "2.0"]}]
}
}
json
`
` response = sns.subscribe(
TopicArn='arn:aws:sns:region:account-id:my-notification-topic',
Protocol='sqs',
Endpoint='arn:aws:sqs:region:account-id:my-queue',
Attributes={
'FilterPolicy': '{"Priority": ["High", "Critical"]}'
}
)
python
`Subscribe with filter policy
$1
` response = sns.set_subscription_attributes(
SubscriptionArn='subscription-arn',
AttributeName='RedrivePolicy',
AttributeValue=json.dumps({
'deadLetterTargetArn': 'arn:aws:sqs:region:account-id:dead-letter-queue'
})
)
python
`Configure DLQ for failed message delivery
$1
` response = sns.publish(
TopicArn='arn:aws:sns:region:account-id:my-notification-topic.fifo',
Message='Hello from SNS!',
MessageGroupId='group1',
MessageDeduplicationId='unique-id-1234'
)
python
`Publish to FIFO topic
$1
$1
` alarm = cloudwatch.put_metric_alarm(
AlarmName='high-cpu-alarm',
ComparisonOperator='GreaterThanThreshold',
EvaluationPeriods=2,
MetricName='CPUUtilization',
Namespace='AWS/EC2',
Period=300,
Statistic='Average',
Threshold=80,
AlarmActions=[
'arn:aws:sns:region:account-id:my-notification-topic'
]
) s3.put_bucket_notification_configuration(
Bucket='my-bucket',
NotificationConfiguration={
'TopicConfigurations': [
{
'TopicArn': 'arn:aws:sns:region:account-id:my-notification-topic',
'Events': ['s3:ObjectCreated:*']
}
]
}
)
python
`CloudWatch Alarms integration
S3 Event Notifications
$1
` {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::account-id:root"
},
"Action": "sns:Publish",
"Resource": "arn:aws:sns:region:account-id:my-notification-topic"
}
]
}
json
`
$1
$1
` response = cloudwatch.get_metric_statistics(
Namespace='AWS/SNS',
MetricName='NumberOfMessagesPublished',
Dimensions=[
{
'Name': 'TopicName',
'Value': 'my-notification-topic'
}
],
StartTime='2024-02-01T00:00:00Z',
EndTime='2024-02-15T00:00:00Z',
Period=3600,
Statistics=['Sum']
)
python
`Get topic metrics
$1
` response = sns.set_topic_attributes(
TopicArn='arn:aws:sns:region:account-id:my-notification-topic',
AttributeName='DeliveryStatusLogging',
AttributeValue=json.dumps({
'sqs': {
'Success': True,
'Failure': True
},
'lambda': {
'Success': True,
'Failure': True
}
})
)
python
`Enable CloudWatch Logs for delivery status
$1
$1
` {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "events.amazonaws.com"
},
"Action": "sns:Publish",
"Resource": "arn:aws:sns:region:account-id:my-notification-topic",
"Condition": {
"ArnLike": {
"aws:SourceArn": "arn:aws:events:region:account-id:rule/*"
}
}
}
]
}
json
`
$1
` response = sns.set_topic_attributes(
TopicArn='arn:aws:sns:region:account-id:my-notification-topic',
AttributeName='KmsMasterKeyId',
AttributeValue='arn:aws:kms:region:account-id:key/key-id'
)
python
`Enable server-side encryption
$1
$1
` messages = [
{
'Message': 'Message 1',
'Subject': 'Batch 1'
},
{
'Message': 'Message 2',
'Subject': 'Batch 1'
}
] for msg in messages:
response = sns.publish(msg)
python
`Batch publish messages
$1
Implement effective filtering to reduce unnecessary message delivery:
` filter_policy = {
'Priority': ['High'],
'Environment': ['Production'],
'Region': ['us-west-2']
} response = sns.set_subscription_attributes(
SubscriptionArn='subscription-arn',
AttributeName='FilterPolicy',
AttributeValue=json.dumps(filter_policy)
)
python
``Configure precise filter policies
$1
Common issues and solutions:
1. Delivery Failures
- Check subscription status
- Verify endpoint accessibility
- Review DLQ configuration
2. Message Filtering Issues
- Validate filter policies
- Check message attributes
- Review matching logic
3. Performance Problems
- Monitor throttling metrics
- Check message size
- Review batch operations
$1
AWS SNS provides powerful messaging capabilities. Key takeaways:
1. Choose appropriate topic types
2. Implement proper security controls
3. Use message filtering effectively
4. Monitor and optimize costs
5. Follow best practices
$1
Consider implementing:
$1
Here are essential resources for AWS SNS:
1. [AWS SNS Documentation](https://docs.aws.amazon.com/sns/) - Official documentation
2. [SNS Developer Guide](https://docs.aws.amazon.com/sns/latest/dg/) - Comprehensive guide
3. [SNS API Reference](https://docs.aws.amazon.com/sns/latest/api/) - API documentation
4. [SNS Best Practices](https://docs.aws.amazon.com/sns/latest/dg/sns-best-practices.html) - Implementation guidelines
5. [SNS Security](https://docs.aws.amazon.com/sns/latest/dg/sns-security.html) - Security features
6. [SNS Monitoring](https://docs.aws.amazon.com/sns/latest/dg/sns-monitoring.html) - Monitoring guide
7. [SNS Pricing](https://aws.amazon.com/sns/pricing/) - Cost information
8. [SNS FAQs](https://aws.amazon.com/sns/faqs/) - Common questions
These resources provide comprehensive information about implementing and optimizing AWS SNS features.
Why This Matters
Understanding the business and technical context helps you make informed decisions rather than blindly following patterns.
Trade-offs to Consider
Every architectural decision involves trade-offs. Consider your specific requirements, team expertise, and scale when evaluating options.
When NOT to Use This
Knowing when a solution doesn't apply is as valuable as knowing when it does. Consider alternatives for your specific situation.
Decision Framework
Use this framework to evaluate whether this approach is right for your use case based on your specific constraints and requirements.