1.1.8 Messaging Services
Write Code to Use Messaging Services
Amazon SQS (Simple Queue Service)
Standard vs FIFO Queues
| Feature | Standard | FIFO |
|---|
| Throughput | Unlimited | 300 msg/s (3000 with batching) |
| Delivery | At-least-once | Exactly-once |
| Ordering | Best-effort | Guaranteed (per Message Group) |
| Deduplication | No | Yes (5-min window) |
| Naming | Any | Phải kết thúc bằng .fifo |
Key Configurations
| Config | Default | Max | Mô tả |
|---|
| Visibility Timeout | 30s | 12h | Thời gian message bị ẩn sau khi consumer nhận |
| Message Retention | 4 days | 14 days | Thời gian giữ message trong queue |
| Message Size | — | 256KB | Dùng Extended Client Library cho message lớn hơn |
| Delay Queue | 0s | 15 min | Delay trước khi message visible |
Long Polling vs Short Polling
import boto3
sqs = boto3.client('sqs')
# Long Polling — giảm empty responses, tiết kiệm cost
response = sqs.receive_message(
QueueUrl='https://sqs.region.amazonaws.com/123456789/my-queue',
MaxNumberOfMessages=10,
WaitTimeSeconds=20 # Long polling (1-20s)
)
Dead-Letter Queue (DLQ)
- Message chuyển sang DLQ sau
maxReceiveCount lần fail - Dùng để debug failed messages
- Redrive policy: Cho phép move messages từ DLQ về source queue
Amazon SNS (Simple Notification Service)
Pub/Sub Model
- Topic → nhiều Subscriptions (SQS, Lambda, HTTP/S, Email, SMS)
- Fan-out pattern: 1 SNS topic → nhiều SQS queues
Message Filtering
{
"store": ["example_corp"],
"event": [{"prefix": "order-"}],
"customer_interests": ["rugby", "football"],
"price_usd": [{"numeric": [">=", 100]}]
}
- Filter policies áp dụng trên subscription level
- Giảm unnecessary processing ở consumer
SNS FIFO Topics
- Kết hợp với SQS FIFO queues
- Ordered + deduplicated delivery
- Strict ordering trong Message Group
SQS + SNS Fan-out Pattern
Producer → SNS Topic → SQS Queue 1 → Consumer A
→ SQS Queue 2 → Consumer B
→ SQS Queue 3 → Consumer C
- Đảm bảo tất cả consumers nhận được message
- Mỗi queue xử lý độc lập, không ảnh hưởng nhau
- Retry và DLQ riêng cho từng queue
Exam Tip: SQS Standard = high throughput + at-least-once. SQS FIFO = ordering + exactly-once. SNS Fan-out = 1 message → nhiều consumers. Long Polling (WaitTimeSeconds > 0) luôn tốt hơn Short Polling.