1.1.8 Messaging Services

Write Code to Use Messaging Services

Amazon SQS (Simple Queue Service)

Standard vs FIFO Queues

FeatureStandardFIFO
ThroughputUnlimited300 msg/s (3000 with batching)
DeliveryAt-least-onceExactly-once
OrderingBest-effortGuaranteed (per Message Group)
DeduplicationNoYes (5-min window)
NamingAnyPhải kết thúc bằng .fifo

Key Configurations

ConfigDefaultMaxMô tả
Visibility Timeout30s12hThời gian message bị ẩn sau khi consumer nhận
Message Retention4 days14 daysThời gian giữ message trong queue
Message Size256KBDùng Extended Client Library cho message lớn hơn
Delay Queue0s15 minDelay 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.