Amazon SNS (Simple Notification Service)
Simple Notification Service, Pub/Sub, Fan-out, Message Filtering
Tổng quan
Amazon SNS là fully managed pub/sub messaging service để gửi notifications đến nhiều subscribers cùng lúc.
SNS vs SQS
| SNS | SQS | |
|---|---|---|
| Model | Pub/Sub (push) | Queue (pull) |
| Message Delivery | 1 message → ALL subscribers | 1 message → 1 consumer |
| Persistence | No (instant delivery) | Yes (up to 14 days) |
| Consumer | Passive (receive push) | Active (poll messages) |
1. Core Concepts
1.1 Topic
1.2 Message Structure
1.3 Publishers
| Publisher | Mô tả |
|---|---|
| AWS SDK | Publish API từ applications |
| CloudWatch Alarms | Alert notifications |
| S3 Events | Bucket notifications |
| Lambda | Function triggers |
| Many AWS Services | EventBridge, CodePipeline... |
2. Subscription Types
2.1 Tất cả Subscription Protocols
2.2 Protocol Details
| Protocol | Use Case | Confirmation |
|---|---|---|
| SQS | Decouple processing | Auto-confirmed |
| Lambda | Serverless processing | Auto-confirmed |
| HTTP/HTTPS | Webhooks, APIs | Must confirm subscription |
| User alerts | Must confirm via link | |
| SMS | Mobile alerts | No confirmation needed |
| Mobile Push | App notifications | Device registration |
2.3 Subscription Confirmation
3. Message Filtering
3.1 Filter Policy
3.2 Filter Policy Operators
| Operator | Example | Matches |
|---|---|---|
| Exact match | {"color": ["red"]} | color = "red" |
| OR | {"color": ["red", "blue"]} | color = "red" OR "blue" |
| Prefix | {"region": [{"prefix": "us-"}]} | region starts with "us-" |
| Numeric | {"price": [{"numeric": [">", 100]}]} | price > 100 |
| Exists | {"color": [{"exists": true}]} | color attribute exists |
| Anything-but | {"color": [{"anything-but": "red"}]} | color != "red" |
3.3 Filter Policy Scope
4. SNS + SQS Fan-out
4.1 Vấn đề và Giải pháp
Vấn đề: Một event cần trigger nhiều xử lý độc lập
Giải pháp: Fan-out = "Phân nhánh" message ra nhiều hướng
4.2 Tại sao dùng SQS thay vì Lambda trực tiếp?
| SNS → Lambda | SNS → SQS → Consumer | |
|---|---|---|
| Buffering | ❌ Lambda phải sẵn sàng | ✅ SQS giữ message khi app down |
| Retry | Lambda tự handle | ✅ SQS có built-in retry |
| DLQ | Phức tạp hơn | ✅ DLQ dễ config |
| Rate limiting | ❌ Lambda bị overwhelm | ✅ Consumer xử lý theo tốc độ |
4.3 Fan-out với Message Filtering
⚠️ QUAN TRỌNG: Filter xảy ra ở tầng SNS, TRƯỚC KHI gửi đến SQS
Tại sao filter ở SNS tốt hơn filter ở SQS/Consumer?
| Filter ở Consumer | Filter ở SNS | |
|---|---|---|
| Flow | SQS nhận TẤT CẢ → Consumer đọc rồi bỏ | SNS chỉ gửi message match |
| Cost | ❌ Tốn tiền SQS requests | ✅ Tiết kiệm |
| Load | ❌ Consumer xử lý message không cần | ✅ Giảm load |
4.4 Cross-Region Fan-out
5. Spring Boot Integration
5.1 Spring Boot có thể nhận SNS messages?
Có! Nhưng có 2 cách:
5.2 Option 1: HTTP Endpoint
5.3 Option 2: SNS → SQS → Spring Boot (Recommended)
5.4 So sánh các patterns
| Pattern | Pros | Cons |
|---|---|---|
| SNS → HTTP | Simple, direct | Need public URL, handle retries |
| SNS → SQS → App | Decoupled, buffering, DLQ | Extra hop, slight delay |
| SNS → Lambda | Serverless, auto-scale | Cold start, 15 min timeout |
6. FIFO Topics
5.1 FIFO Topic Features
5.2 Message Group ID
6. Security
6.1 Encryption
6.2 Access Control
SNS Access Policy Example (Allow S3 to publish):
7. Best Practices
7.1 Design Patterns
| Pattern | Description |
|---|---|
| Fan-out | SNS → Multiple SQS queues |
| Event-driven | SNS → Lambda |
| Cross-account | SNS topic in Account A, SQS in Account B |
| Cross-region | SNS topic in region A, SQS in region B |
7.2 Message Filtering Best Practices
| Practice | Recommendation |
|---|---|
| Filter at SNS | Don't filter in Lambda/Consumer |
| Use MessageAttributes | More efficient than body filtering |
| Keep policies simple | Complex policies = slower processing |
7.3 Reliability
7.4 Cost Optimization
| Strategy | Description |
|---|---|
| Message Filtering | Reduce unnecessary deliveries |
| Batch Publishing | PublishBatch API (up to 10 msgs) |
| Right Protocol | SQS cheaper than SMS for alerts |
8. SNS vs SQS vs EventBridge
| Feature | SNS | SQS | EventBridge |
|---|---|---|---|
| Model | Pub/Sub | Queue | Event Bus |
| Filtering | Simple (attributes) | None | Advanced (100+ rules) |
| Persistence | No | Yes | Archive/Replay |
| Targets | Many protocols | Consumer apps | AWS services |
| Transform | No | No | Yes |
| Use Case | Fan-out | Decouple | Event-driven |
9. Common Exam Questions
Q1: SNS vs SQS delivery model?
A: SNS = Push to all subscribers. SQS = Consumer pulls messages, 1 per message.
Q2: SNS FIFO can subscribe to what?
A: Only SQS FIFO queues. Cannot subscribe to Lambda or Standard SQS.
Q3: Message filtering là gì?
A: Filter policy trên subscription để chỉ nhận messages matching criteria.
Q4: Max subscriptions per topic?
A: 12,500,000 subscriptions
Q5: SNS message max size?
A: 256 KB
Q6: How to ensure SQS receives from SNS?
A: Configure SQS access policy cho phép SNS topic gửi messages.