Bài này gộp 3 chủ đề: Amazon SQS, Amazon SNS, Amazon EventBridge.
Mục tiêu học tập
- Hiểu SQS: managed message queue
- Phân biệt Standard vs FIFO queues
- Nắm visibility timeout, DLQ, long polling
- Áp dụng decoupling pattern với SQS
- Hiểu SNS: managed pub/sub messaging
- Phân biệt Topic types: Standard vs FIFO
- Nắm subscription protocols và message filtering
- Áp dụng fanout pattern (SNS + SQS)
- Hiểu EventBridge: event bus cho event-driven architecture
- Phân biệt Default vs Custom vs Partner Event Bus
- Nắm Rules, Targets, Schema Registry
- Áp dụng cron schedules và cross-account events
Phần 1: Amazon SQS
1. Tổng quan SQS
Amazon SQS (Simple Queue Service) = fully managed message queue service for decoupling distributed components.
Đặc điểm
- Pull-based (consumers poll)
- At-least-once delivery (Standard) / Exactly-once (FIFO)
- Highly available: messages replicated across multiple AZs
- Scalable: handle 100K+ messages/sec (Standard)
- Message size: up to 1 MiB (từ 08/2025; số cũ 256 KB đề thi có thể còn dùng; use S3 for larger)
- Retention: 1 minute - 14 days (default 4 days)
Use cases
- Decouple components (producer ≠ consumer rate)
- Buffer for traffic spikes
- Async processing (orders, emails, image processing)
- Task scheduling (delayed messages)
2. SQS Queue Types
Standard Queue
- At-least-once delivery (may deliver duplicate)
- Best-effort ordering (not strict FIFO)
- Unlimited throughput (auto-scale)
- Most use cases
FIFO Queue
- Exactly-once processing
- Strict FIFO ordering (per Message Group)
- 300 messages/sec (without batching), 3000/sec với batching; bật high-throughput mode thì tới 70,000 TPS/API (tuỳ region)
- Higher cost (~$0.50/M vs $0.40/M)
- Queue name must end with
.fifo
When to use FIFO
- Financial transactions (order matters)
- Sequential events processing
- Banking ledger
- Exactly-once required (no dedup logic in app)
When to use Standard
- High throughput needed
- Order không quan trọng (independent tasks)
- Lower cost
3. Producer
Send Message
sqs.send_message(
QueueUrl='https://sqs.us-east-1.amazonaws.com/111/MyQueue',
MessageBody='{"order_id": "123", "amount": 99.99}',
DelaySeconds=10, # delay before consumers can receive
MessageAttributes={...}
)
Send Message Batch
- Up to 10 messages in 1 call
- Reduces cost (1 API call vs 10)
- Total batch size ≤ 1 MiB (số cũ: 256 KB)
4. Consumer
Poll Messages
response = sqs.receive_message(
QueueUrl='...',
MaxNumberOfMessages=10, # 1-10
WaitTimeSeconds=20, # long polling
VisibilityTimeout=30
)
for msg in response.get('Messages', []):
process(msg['Body'])
# MUST delete after processing
sqs.delete_message(
QueueUrl='...',
ReceiptHandle=msg['ReceiptHandle']
)
Consumers
- EC2 instances (often in ASG)
- Lambda functions (Event Source Mapping → poll automatically)
- ECS / Fargate
- On-prem servers
Auto-scaling consumers
- ASG scale based on CloudWatch metric
ApproximateNumberOfMessagesVisible - Lambda scale automatically (up to concurrency limit)
5. Visibility Timeout
Định nghĩa
Visibility Timeout = period during which a received message is hidden from other consumers.
Workflow
1. Consumer A: ReceiveMessage → message hidden từ others
2. Visibility Timeout starts (default 30s)
3. Consumer A processes message
4. Consumer A: DeleteMessage → message removed
5. (Or) If A fails to delete within timeout → message visible again, another consumer can receive
Configuration
- Default: 30 seconds
- Range: 0 to 12 hours
- Set per queue or per message (override)
Best practice
- Set timeout = average processing time × 2-3 (safety margin)
- Long-running tasks: extend timeout với
ChangeMessageVisibilityAPI - Short tasks: short timeout (faster retry on failure)
Common issue: duplicate processing
- Consumer A processes message but slow
- Timeout expires before A deletes
- Message reappears → Consumer B receives same message
- → Both A and B process duplicate
- Solution: idempotent processing OR extend visibility timeout
6. Long Polling vs Short Polling
Short Polling (default)
WaitTimeSeconds = 0- Returns immediately (even if no messages)
- More API calls → more cost
- Higher latency for low-traffic queues
Long Polling (recommended)
WaitTimeSeconds = 1-20- Wait up to N seconds for messages to arrive
- Fewer API calls → lower cost
- Lower latency
Setup
- Set
ReceiveMessageWaitTimeSecondsat queue level (default polling) - Or override per
ReceiveMessagecall
7. Dead Letter Queue (DLQ)
Định nghĩa
DLQ = secondary queue for messages that failed processing N times.
Workflow
1. Message delivered to consumer
2. Consumer fails to process (exception, timeout)
3. Message reappears, retry
4. After N retries (Max Receive Count), message moves to DLQ
5. DLQ alerts via CloudWatch → investigate
Configuration
RedrivePolicy:deadLetterTargetArn: ARN of DLQmaxReceiveCount: e.g., 3 (after 3 failed processing, move to DLQ)
DLQ best practices
- Set up CloudWatch alarm on DLQ message count
- Manually inspect DLQ for failure pattern
- Fix bug → redrive messages back to source queue (DLQ Redrive)
Use case
- Poison messages (malformed data)
- App bug processing certain message types
- External service downtime causing retries
8. Message Lifecycle
9. SQS Security
Access Control
- IAM policies (identity-based)
- SQS Queue Policy (resource-based, cross-account)
Encryption
- In transit: TLS
- At rest: SQS-managed encryption hoặc KMS
- Enable per queue
VPC Endpoint
- Interface Endpoint cho SQS (PrivateLink)
- Private subnet access SQS không qua internet
10. SQS Advanced Features
Delay Queues
- Delay messages 0-15 minutes before visible to consumers
- Set per queue (default 0)
Message Timers
- Per-message delay (override queue default)
- Up to 15 minutes
FIFO Specific Features
- MessageGroupId: group messages, FIFO within group
- MessageDeduplicationId: dedupe within 5-minute window
- Multiple Groups can process in parallel
Long Messages (> 1 MiB)
- Use SQS Extended Client Library: store payload in S3, queue contains S3 reference
- Or use Step Functions with larger payload support
11. SQS vs SNS vs EventBridge
| SQS | SNS | EventBridge | |
|---|---|---|---|
| Type | Queue (point-to-point) | Topic (pub/sub) | Event Bus (pub/sub + routing) |
| Consumers | 1 consumer per message | Many subscribers per message | Many targets with filtering |
| Delivery | Pull (consumer polls) | Push to subscribers | Push to targets |
| Use case | Decouple, async work | Fanout notifications | Event-driven architecture |
Combined pattern: SNS + SQS fanout
Each consumer processes independently from their queue.
12. SQS Pricing
- $0.40 per million requests (Standard)
- $0.50 per million requests (FIFO)
- Free tier: 1M requests/month
- No data transfer charge within same Region (to EC2)
Optimization
- Batch operations (10 messages/call = 10x cost reduction)
- Long polling (fewer empty polls)
- Right-size visibility timeout
13. Common Patterns
Pattern 1: Order processing
Web app → SQS Queue → Order Processor (EC2 ASG)
→ DLQ if processing fails
Pattern 2: Image thumbnail generation
User upload → S3 → SNS → SQS → Lambda → resize → S3
Pattern 3: Email batch sending
App → SQS FIFO Queue (group by user)
→ Worker reads, sends email via SES
Pattern 4: Job retry mechanism
App → SQS (initial)
→ Lambda → 3 retries
→ DLQ → CloudWatch alarm → Ops investigation
Phần 2: Amazon SNS
1. Tổng quan SNS
Amazon SNS (Simple Notification Service) = fully managed pub/sub messaging service.
Đặc điểm
- Push-based (vs SQS pull-based)
- Fanout: 1 message → multiple subscribers
- Multiple protocols: HTTP/S, Email, SMS, Lambda, SQS, mobile push, Kinesis Firehose
- Highly scalable: millions of messages/sec
- Không lưu trữ message (khác SQS retention 14 ngày): SNS chỉ có delivery retry policy (HTTP/S có backoff); message không giao được sẽ bị discard trừ khi cấu hình DLQ (SQS queue). Muốn durable buffer → fanout sang SQS. Điểm phân biệt SNS/SQS đề thi hay hỏi!
Use cases
- Application notifications (email, SMS)
- Fanout to multiple SQS queues
- Lambda triggers
- Mobile push notifications (iOS, Android, Fire OS)
- CloudWatch alarm notifications
2. Topic Types
Standard Topic
- At-least-once delivery
- Best-effort ordering
- Unlimited throughput
- All subscription types supported
FIFO Topic
- Exactly-once delivery
- Strict ordering (per Message Group)
- 300 publishes/sec (without batching)
- Subscribers: chỉ SQS queues (FIFO hoặc Standard) — không email, SMS, HTTP; Lambda phải đi qua SQS queue
- Topic name must end with
.fifo
When FIFO
- Need ordering across messages
- Need exactly-once
- Trade-off: lower throughput, limited subscriber types
3. Subscription Protocols
| Protocol | Use case |
|---|---|
| HTTP / HTTPS | Webhook to your endpoint |
| Email / Email-JSON | Send notification to email |
| SMS | Send text message to phone (charged per SMS) |
| SQS | Fanout to SQS queue |
| Lambda | Invoke Lambda function |
| Application (mobile push) | iOS APNs, Android FCM, Fire OS ADM, Baidu, WNS, MPNS |
| Amazon Data Firehose (cũ: Kinesis Data Firehose) | Stream to S3, Redshift, OpenSearch |
| SMS to 200+ countries | Direct SMS |
Subscription confirmation
- For HTTP/email: subscriber must confirm subscription (click link / verify)
- Prevents spam
4. Fanout Pattern (SNS + SQS)
Architecture
Lợi ích
- 1 publish → N consumers (no publisher rewrite)
- Each consumer independent (own queue, own processing rate)
- Add/remove consumers without affecting publisher
- Each queue can have own DLQ, own visibility timeout
Use case examples
- E-commerce order placed → Email notification + Update inventory + Trigger analytics
- File upload to S3 → Generate thumbnail + Index for search + Send notification
Setup
- Tạo SNS Topic
- Tạo multiple SQS queues
- Subscribe each queue to topic
- Configure SQS access policy allowing SNS to publish
5. Message Filtering
Định nghĩa
Message Filtering = subscribers receive only messages matching filter policy (instead of all).
Filter Policy (subscriber-level)
{
"event_type": ["order_placed", "order_shipped"],
"amount": [{ "numeric": [">=", 100] }],
"country": [{ "anything-but": ["US"] }]
}
Use case
- 1 topic for all events, subscribers pick relevant ones
- Reduce processing for irrelevant messages
- Simpler architecture than multiple topics
Example
6. SNS Security
Access Control
- IAM policies (identity-based)
- SNS Topic Policy (resource-based, cross-account)
Encryption
- In transit: TLS
- At rest: KMS encryption
VPC Endpoint
- Interface Endpoint cho SNS
- Private subnet publish to SNS
Message data protection (NEW)
- Detect/mask PII trong SNS messages (similar to Macie)
7. Mobile Push Notifications
Supported platforms
- APNs (Apple Push Notification Service) - iOS
- FCM (Firebase Cloud Messaging) - Android
- ADM (Amazon Device Messaging) - Fire OS
- WNS (Windows Push) - Windows
- MPNS (Microsoft Push Notification) - Windows Phone (legacy)
- Baidu Cloud Push - Android China
Workflow
1. App registers with platform (APNs/FCM)
2. App sends device token to your backend
3. Backend creates "endpoint" in SNS for device
4. SNS endpoint added to topic (or directly published)
5. Publish to topic → SNS forwards to APNs/FCM → device
8. SNS with Amazon Data Firehose
Integration (2023+)
- SNS subscribe to Amazon Data Firehose delivery stream
- Stream messages to:
- S3
- Redshift
- OpenSearch
- HTTP endpoint
- 3rd party (Splunk, Datadog)
Use case
- Centralize event logging from SNS to S3 data lake
- Real-time analytics with OpenSearch
9. SNS vs SQS vs EventBridge (deep)
| SNS | SQS | EventBridge | |
|---|---|---|---|
| Model | Pub/Sub | Queue | Event Bus + Routing |
| Subscribers | Push to all | Pull by 1 | Push to all matching rules |
| Filtering | Yes (subscription) | No (consumer filter) | Yes (rules) |
| Sources | Producers | Producers | AWS services, custom, SaaS |
| Targets | HTTP, email, SMS, SQS, Lambda, mobile, Firehose | EC2, Lambda, Fargate (poll) | 25+ AWS services |
| Retry | Built-in | Visibility timeout + DLQ | Built-in + DLQ |
| Use case | Fanout, notifications | Decouple async work | Event-driven architecture |
Decision guide
- Notify multiple subscribers: SNS
- Decouple producer-consumer pace: SQS
- Route AWS events to targets with filtering: EventBridge
- Combo: SNS for fanout, SQS for each subscriber queue, EventBridge for AWS-native events
10. SNS Pricing
- $0.50 per million publishes (Standard)
- $1.00 per million publishes (FIFO)
- HTTP deliveries: $0.60 per million
- Email: $2.00 per 100K (US)
- SMS: per message + country-specific (~$0.00645/SMS in US)
- Lambda invocations: free (Lambda billed separately)
- SQS delivery: free (SQS billed separately)
- Mobile push: $0.50 per million
Free tier
- 1M publishes/month
- 100,000 HTTP deliveries
- 1,000 emails
- 1M mobile push
11. Common Patterns
Pattern 1: Order processing fanout
Pattern 2: Multi-channel alerts
Pattern 3: Mobile app push
Pattern 4: Event filtering
Phần 3: Amazon EventBridge
1. Tổng quan EventBridge
Amazon EventBridge (formerly CloudWatch Events) = serverless event bus routing events từ AWS services, custom apps, SaaS đến targets.
Đặc điểm
- Schema-based events (JSON structured)
- Filter + route events based on rules
- Multi-source: AWS services, custom apps, SaaS partners
- Multi-target: 25+ AWS services
- Cross-account, cross-region event routing
- Replay events (debugging, reprocessing)
- Schema Registry for event discovery
Use cases
- Event-driven architecture
- Cron-based scheduling (replace cron servers)
- React to AWS service events (EC2 state change, S3 upload)
- SaaS integration (Datadog, Zendesk, Shopify, MongoDB)
- Cross-account event sharing
2. EventBridge Components
Event Bus
- Container for events
- 3 types:
- Default Event Bus: AWS service events go here automatically
- Custom Event Bus: for your custom apps' events
- Partner Event Bus: events from SaaS partners (Zendesk, etc.)
Event
- JSON structured message
- Standard fields:
source,detail-type,detail,time,region,account
Rule
- Filter events based on:
- Event source/detail-type
- Event content (JSON pattern matching)
- Route matched events to targets
Target
- Destination for matched events
- 25+ types: Lambda, SQS, SNS, Step Functions, Kinesis, EC2, Glue, ...
3. Event Structure
{
"version": "0",
"id": "abc123",
"detail-type": "EC2 Instance State-change Notification",
"source": "aws.ec2",
"account": "111111111111",
"time": "2025-01-15T10:00:00Z",
"region": "us-east-1",
"resources": [
"arn:aws:ec2:us-east-1:111111111111:instance/i-12345"
],
"detail": {
"instance-id": "i-12345",
"state": "running"
}
}
Standard AWS Service Events
- EC2: instance state change, terminate, stop
- S3: object created, deleted (must enable)
- CodeCommit: push to repo
- CloudTrail: any API call (subset of API events)
- RDS: snapshot complete
- Auto Scaling: launch, terminate
- ECS: task state change
- Health: AWS health events
- Trusted Advisor: check status change
4. Rules and Patterns
Pattern matching examples
Match EC2 instance running state
{
"source": ["aws.ec2"],
"detail-type": ["EC2 Instance State-change Notification"],
"detail": {
"state": ["running"]
}
}
Match S3 upload to specific bucket
{
"source": ["aws.s3"],
"detail-type": ["Object Created"],
"detail": {
"bucket": {
"name": ["my-bucket"]
}
}
}
Match specific account API call (CloudTrail)
{
"source": ["aws.iam"],
"detail-type": ["AWS API Call via CloudTrail"],
"detail": {
"eventName": ["CreateUser", "DeleteUser"]
}
}
Operators
exists,equals-ignore-case,prefix,suffixnumeric:["=", 5],[">", 100]anything-but: excludecidr: IP range matching
5. Targets (25+ types)
| Target | Use case |
|---|---|
| Lambda | Custom processing |
| SQS | Queue for async processing |
| SNS | Fanout to subscribers |
| Step Functions | Workflow orchestration |
| Kinesis | Stream processing |
| EC2 Run Command | Automation |
| EC2 Action (stop, terminate, reboot) | EC2 management |
| Glue Job | ETL trigger |
| CodePipeline | CI/CD trigger |
| API Destinations (HTTP endpoint) | Webhook to external system |
| Batch Job | Batch compute trigger |
| ECS Task | Container task |
| EventBridge Event Bus (cross-account, cross-region) | Forward events |
Multiple targets
- 1 rule → up to 5 targets
- Each target can have own input transformation
Input Transformation
- Modify event JSON before sending to target
- Use case: target API expects different format
6. Schedule (Cron-based Events)
Replaced traditional cron
- Old way: EC2 cron job
- New way: EventBridge Scheduler (rate or cron expression)
Expressions
rate(5 minutes) → every 5 minutes
rate(2 hours) → every 2 hours
cron(0 12 * * ? *) → daily at 12:00 UTC
cron(0 8 ? * MON-FRI *) → Mon-Fri 8 AM UTC
cron(0/30 * * * ? *) → every 30 min
Use cases
- Periodic Lambda execution
- Daily reports
- Database cleanup
- Health checks
EventBridge Scheduler (newer, 2022+)
- Dedicated scheduler service
- More features: one-time schedule, flexible time windows, dead-letter queue
- Recommended for new schedules
7. Schema Registry
Định nghĩa
Schema Registry = discover and manage event schemas.
Đặc điểm
- Auto-discover schemas từ events on event bus
- Browse + search schemas
- Generate code bindings (Java, Python, TypeScript) for type-safe event handling
- Versioning of schemas
Use case
- Developer productivity (autocomplete in IDE)
- Type safety in code
- Document events for team
8. Cross-Account Events
Setup
- Sender account: Create rule, target = event bus ARN of receiver account
- Receiver account: Custom event bus, resource policy allowing sender account
- Sender publishes → events forwarded to receiver
Use case
- Centralized event hub (security account receives all events)
- Multi-account SaaS
9. Replay Events
Định nghĩa
Archive + Replay = save events to archive, replay later for debugging/reprocessing.
Setup
- Create Archive for event bus
- Archive stores events (configurable retention)
- Replay events to bus → reprocess by rules
Use cases
- Debug after fix (replay events that failed before)
- Add new consumer post-hoc
- Disaster recovery (replay events lost during outage)
10. SaaS Integrations
Partner Event Bus
- AWS partners stream events to your account via Partner Event Source
- Examples:
- Auth0: user events
- Datadog: monitoring events
- MongoDB Atlas: DB events
- Shopify: order events
- PagerDuty: incident events
- Stripe: payment events
- Zendesk: ticket events
Setup
- Subscribe to partner in EventBridge console
- Partner creates Event Source → you create Event Bus from source
- Define rules → route to your targets
11. EventBridge Pipes (2022+)
Định nghĩa
Pipes = point-to-point integration between source và target with optional filtering/enrichment.
Architecture
Difference from Event Bus
- Pipes: 1 source → 1 target (point-to-point)
- Event Bus: N sources → N targets (event hub)
Use case
- Replace simple Lambda triggers
- Built-in batching, filtering, enrichment
- No code for simple integrations
12. EventBridge vs SNS
| EventBridge | SNS | |
|---|---|---|
| Model | Event bus (rule-based) | Pub/Sub topic |
| Sources | AWS services + custom + SaaS | Custom only |
| Filtering | Powerful (JSON pattern) | Basic (attributes) |
| Targets | 25+ types | 10+ types |
| Replay | Yes | No |
| Schema Registry | Yes | No |
| Scheduler | Yes (cron) | No |
| Use case | AWS-native events, complex routing | Notifications, fanout |
Decision
- AWS service events: EventBridge (native)
- Custom app fanout to many subscribers: SNS or EventBridge
- Need filtering, routing logic: EventBridge
- Simple notifications: SNS
13. Pricing
EventBridge
- $1 per million events published to custom/partner bus
- AWS service events to default bus: FREE
- Cross-account: charged at sender
- Archive storage: $0.10/GB-month
- Replay: $1/M events
Schedule
- 14M invocations/month free
- $1 per M after
14. Common Patterns
Pattern 1: Auto-tag EC2 on launch
EC2 instance launch event
→ EventBridge rule (match RunInstances)
→ Lambda: add tags based on launching user
Pattern 2: Replace cron
EventBridge Scheduler (cron 0 2 * * ? *)
→ Lambda: daily database cleanup
Pattern 3: Cross-account audit
Account A, B, C → CloudTrail events → EventBridge
→ Forward to Security Account event bus
→ Lambda: log to S3, alert on suspicious activity
Pattern 4: SaaS integration
Zendesk ticket created
→ Partner Event Bus
→ EventBridge rule
→ Lambda → create Slack notification + update CRM
Câu hỏi ôn tập
-
Khác biệt cốt lõi giữa Standard và FIFO queue?
Xem đáp án
Standard: throughput cao (nearly unlimited), delivery at-least-once (có thể duplicate), ordering best-effort (không đảm bảo). FIFO: throughput giới hạn (300 msg/s, hoặc 3000 với batching), delivery exactly-once (deduplication tự động), ordering guaranteed (FIFO). FIFO tên kết thúc bằng
.fifo. Dùng FIFO cho financial transactions, order processing — cần strict ordering; Standard cho high-throughput async jobs. -
Visibility timeout default là bao nhiêu giây?
Xem đáp án
30 giây (default). Range: 0 giây đến 12 giờ. Khi consumer nhận message, message "invisible" với consumers khác trong visibility timeout — ngăn duplicate processing. Nếu consumer xử lý xong → delete message. Nếu timeout hết mà chưa delete → message visible lại, consumer khác có thể nhận. Consumer nên set visibility timeout > max processing time để tránh duplicates.
-
Long polling khác Short polling ở điểm gì?
Xem đáp án
Short polling (default): trả về ngay kể cả queue empty — gây nhiều empty API responses, tốn tiền. Long polling (
WaitTimeSeconds1-20s): SQS đợi đến khi có message hoặc hết timeout mới trả response — giảm empty responses, giảm cost, giảm latency. AWS khuyến nghị dùng long polling (20 giây) cho production. SetReceiveMessageWaitTimeSecondsở queue level hoặc per-request. -
DLQ giải quyết vấn đề gì?
Xem đáp án
Dead Letter Queue (DLQ) lưu messages không thể xử lý thành công sau N lần retry (
maxReceiveCount). Ngăn "poison pill messages" làm block queue mãi mãi. DLQ là Standard/FIFO queue bình thường — có thể inspect, debug, hoặc reprocess messages. Thường setup alarm trên DLQ metrics để alert khi có failures. DLQ phải cùng type (Standard/FIFO) với source queue. -
Tối đa bao nhiêu messages trong 1 batch SendMessage?
Xem đáp án
10 messages per batch (SendMessageBatch API). Tổng size của batch tối đa 1 MiB (số cũ 256 KB — đề thi có thể còn dùng). Batching giảm số API calls và cost (tính theo request, không phải per message). Tương tự, ReceiveMessage có thể nhận tối đa 10 messages per call, DeleteMessageBatch có thể delete tối đa 10 messages. Dùng batching để tối ưu throughput và cost.
-
SNS push hay pull?
Xem đáp án
Push — SNS chủ động push messages đến subscribers ngay khi publish. Khác với SQS (pull model — consumers phải poll). SNS subscriber nhận message ngay lập tức mà không cần polling. Đây là pub/sub model: publisher publish một lần, SNS fan-out đến nhiều subscribers cùng lúc.
-
FIFO topic subscriber type bị giới hạn gì?
Xem đáp án
FIFO SNS topic chỉ deliver tới SQS queues — SQS FIFO (giữ strict ordering và deduplication) hoặc SQS Standard (best-effort ordering, at-least-once, rẻ hơn). Không thể subscribe email, SMS, mobile push, HTTP(S) vào FIFO topic; muốn fan-out tới Lambda thì subscribe SQS queue rồi cho queue trigger Lambda. Standard topic hỗ trợ tất cả subscriber types. Tài liệu/đề thi cũ ghi "chỉ SQS FIFO" — nếu không có phương án "SQS Standard" thì chọn SQS FIFO.
-
Fanout pattern với SNS + SQS giải quyết vấn đề gì?
Xem đáp án
Cho phép một message được xử lý độc lập bởi nhiều consumers. Ví dụ: order placed → SNS topic → (1) SQS queue cho inventory service, (2) SQS queue cho notification service, (3) SQS queue cho analytics. Mỗi service có queue riêng — có thể scale và fail independently. Nếu một service down, messages vẫn trong SQS queue chờ — không mất. Đây là pattern decoupling mạnh nhất cho microservices.
-
Message filtering set ở topic hay subscription level?
Xem đáp án
Subscription level — mỗi subscription có thể có filter policy riêng. Filter policy dựa trên message attributes (key-value metadata trong message). Subscriber chỉ nhận messages matching filter — giảm processing và cost. Ví dụ: subscription A filter
{"type": ["order"]}, subscription B filter{"type": ["payment"]}— cùng topic nhưng mỗi subscriber chỉ nhận relevant messages. -
SNS có hỗ trợ mobile push notifications không? Platforms nào?
Xem đáp án
Có — SNS là platform chuẩn cho mobile push. Hỗ trợ: APNs (Apple Push Notification service — iOS/macOS), FCM/GCM (Firebase Cloud Messaging — Android), ADM (Amazon Device Messaging — Kindle), Baidu Cloud Push (China Android). Cần configure platform application với credentials từ platform. SNS handle authentication với push platforms — không cần code riêng per platform.
- EventBridge default event bus chứa events gì?
Xem đáp án
Default event bus nhận AWS service events (EC2 state changes, S3 object create, RDS snapshots, CodePipeline state changes, GuardDuty findings...). Không thể delete default event bus. Custom event buses tạo riêng cho application events. Partner event buses nhận events từ SaaS partners (Zendesk, Datadog, PagerDuty...). Rule filter events và route đến targets.
- Tối đa bao nhiêu targets per rule?
Xem đáp án
5 targets per rule. Mỗi rule có thể fan-out đến 5 services cùng lúc (Lambda, SQS, SNS, Step Functions, API Gateway, Kinesis, ECS, SSM...). Nếu cần fan-out đến nhiều hơn 5 targets, dùng SNS topic làm 1 target rồi fan-out từ SNS. EventBridge supports 300+ AWS services và SaaS partners làm targets.
- Khi nào dùng EventBridge Pipes thay vì Rules?
Xem đáp án
EventBridge Pipes cho point-to-point integration với transformation: một source (SQS, DynamoDB Streams, Kinesis, Kafka) → optional filtering → optional enrichment (Lambda, Step Functions, API GW) → one target. Phù hợp khi cần transform data trong pipeline. Rules cho broadcast: một event → nhiều targets, complex filtering. Pipes simplify patterns từng cần nhiều Lambda glue code.
- EventBridge có thể schedule cron jobs không?
Xem đáp án
Có — EventBridge Scheduler (và legacy CloudWatch Events scheduled rules) cho phép schedule theo: cron expression (UTC) hoặc rate expression (ví dụ rate(5 minutes)). EventBridge Scheduler (2022) là service riêng, cải tiến hơn: flexible time windows, timezone support, retry with DLQ, millions of schedules. Dùng để trigger Lambda, Step Functions, ECS tasks, SQS, API calls theo lịch.
- Schema Registry giúp developer làm gì?
Xem đáp án
Schema Registry document và discover event schemas (structure của JSON events) trong EventBridge. Tự động infer schema từ events hoặc define thủ công. Lợi ích: (1) Code bindings — generate TypeScript/Java/Python classes từ schema, (2) Discovery — team biết events nào available mà không cần liên hệ nhau, (3) Validation — verify events conform to schema trước khi process. Tương tự Swagger/OpenAPI nhưng cho event-driven systems.
Bài tập thực hành
Phần 1: Amazon SQS
- Tạo Standard SQS queue, send 10 messages, receive batch 10
- Tạo FIFO queue, test ordering với MessageGroupId
- Setup DLQ, force consumer fail, observe message moves to DLQ
- Configure long polling 20s, observe API call reduction
- Setup Lambda trigger từ SQS (Event Source Mapping)
- Test SQS Extended Client cho message > 1 MiB
Phần 2: Amazon SNS
- Tạo Standard SNS Topic
- Subscribe email, confirm subscription, test publish
- Fanout: 1 topic → 3 SQS queues, publish 1 message, verify all 3 received
- Add message filter cho 1 subscription, test filtering works
- Setup CloudWatch alarm → SNS → email
- (Optional) Mobile push setup with FCM
Phần 3: Amazon EventBridge
- Tạo rule: EC2 instance state change → SNS notification
- Tạo EventBridge Schedule chạy Lambda mỗi 5 phút
- Setup cross-account event: từ Account A → bus của Account B
- Browse Schema Registry, generate code binding cho 1 event
- Tạo Pipes: SQS → Lambda với filtering
Tài liệu tham khảo
- Amazon SQS Documentation
- FIFO Queues
- Visibility Timeout
- DLQ
- Amazon SNS Documentation
- SNS Subscription Filter Policies
- Fanout Pattern
- Mobile Push
- EventBridge Documentation
- Event Patterns
- Schedule Expressions
- EventBridge Pipes
- Schema Registry