SQS = mỗi message chỉ tới một consumer (competing-consumers). SNS = 1 message → nhiều subscriber. Order created cần gửi email, update inventory, sync warehouse, notify mobile app — tất cả từ một event. SNS fan-out giải quyết bài toán này.


  flowchart LR
    OrderSvc["Order Service"] --> Topic["SNS Topic<br/>order-created"]
    Topic -->|"filter: priority=high"| EmailQ["SQS email-queue"]
    Topic --> InventoryQ["SQS inventory-queue"]
    Topic --> Lambda["Lambda push-notify"]
TOPIC_ARN=$(aws sns create-topic --name order-created --query 'TopicArn' --output text)

aws sns subscribe --topic-arn $TOPIC_ARN --protocol sqs \
  --notification-endpoint $SQS_ARN \
  --attributes '{"RawMessageDelivery":"true","FilterPolicy":"{\"priority\":[\"high\",\"critical\"]}"}'
await sns.send(
  new PublishCommand({
    TopicArn: TOPIC_ARN,
    Message: JSON.stringify({ orderId: "ORD-001", total: 150000 }),
    MessageAttributes: {
      priority: { DataType: "String", StringValue: "high" },
    },
  })
);

Fan-out SNS→SQS: pattern mạnh nhất

Mỗi consumer có SQS queue riêng → rate riêng, retry riêng, DLQ riêng. Nếu email service chết, inventory queue vẫn xử lý bình thường.

SNS vs EventBridge

SNSEventBridge
FilterMessage attribute (đơn giản)Event pattern (content-based, phức tạp)
SchemaKhôngSchema registry + discovery
ArchiveKhôngArchive + replay
Dùng khiFan-out đơn giản, notification đa kênhComplex event routing, multi-source

SNS và SQS là bộ đôi messaging cơ bản nhất trên AWS. Khi cần routing phức tạp hơn, bài sau sẽ nói về EventBridge.

Bài sau: Phần 27: EventBridge — event bus, rule, schema registry