devHọc Dev
EN
Bài học

Tuần 3 - Ngày 3: SQS, SNS và EventBridge

Tuần 3 – Ngày 3

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 ChangeMessageVisibility API
  • 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
  • WaitTimeSeconds = 1-20
  • Wait up to N seconds for messages to arrive
  • Fewer API calls → lower cost
  • Lower latency

Setup

  • Set ReceiveMessageWaitTimeSeconds at queue level (default polling)
  • Or override per ReceiveMessage call

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 DLQ
    • maxReceiveCount: 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

Producer→SQS→Consumer▼[Visible]▼ReceiveMessagebyConsumer▼[In-flight-hidden]▼┌─────────────────────────────┐│ConsumerDELETESwithin││visibilitytimeout?│└─────────────────────────────┘││YesNo▼▼[Removed][Visibleagain]│▼Retry(uptomaxReceiveCount)│▼[DLQ]

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

SQSSNSEventBridge
TypeQueue (point-to-point)Topic (pub/sub)Event Bus (pub/sub + routing)
Consumers1 consumer per messageMany subscribers per messageMany targets with filtering
DeliveryPull (consumer polls)Push to subscribersPush to targets
Use caseDecouple, async workFanout notificationsEvent-driven architecture

Combined pattern: SNS + SQS fanout

Event→SNSTopic├──SQSQueue1→ConsumerA├──SQSQueue2→ConsumerB└──SQSQueue3→ConsumerC

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

ProtocolUse case
HTTP / HTTPSWebhook to your endpoint
Email / Email-JSONSend notification to email
SMSSend text message to phone (charged per SMS)
SQSFanout to SQS queue
LambdaInvoke 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+ countriesDirect SMS

Subscription confirmation

  • For HTTP/email: subscriber must confirm subscription (click link / verify)
  • Prevents spam

4. Fanout Pattern (SNS + SQS)

Architecture

┌─►SQSQueue1→ConsumerAPublisher→SNSTopic─┼─►SQSQueue2→ConsumerB└─►SQSQueue3→ConsumerC

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

  1. Tạo SNS Topic
  2. Tạo multiple SQS queues
  3. Subscribe each queue to topic
  4. 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

Topic:order-events├──SubscriberA(queue):filterevent_typeIN[order_placed]├──SubscriberB(queue):filterevent_typeIN[order_shipped]└──SubscriberC(Lambda):filteramount>=1000

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)

SNSSQSEventBridge
ModelPub/SubQueueEvent Bus + Routing
SubscribersPush to allPull by 1Push to all matching rules
FilteringYes (subscription)No (consumer filter)Yes (rules)
SourcesProducersProducersAWS services, custom, SaaS
TargetsHTTP, email, SMS, SQS, Lambda, mobile, FirehoseEC2, Lambda, Fargate (poll)25+ AWS services
RetryBuilt-inVisibility timeout + DLQBuilt-in + DLQ
Use caseFanout, notificationsDecouple async workEvent-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

APIGateway→Lambda(placeorder)→SNSTopic├──SQS→Emailservice├──SQS→Inventoryupdate└──SQS→Analyticsingestion

Pattern 2: Multi-channel alerts

CloudWatchAlarm→SNSTopic├──Email(opsteam)├──SMS(on-call)└──Lambda(auto-remediation)

Pattern 3: Mobile app push

Backend→SNSApplication├──APNs(iOSusers)└──FCM(Androidusers)

Pattern 4: Event filtering

EventTopic├──QueueA:eventsoftype"user_signup"→onboarding├──QueueB:eventsoftype"purchase"→CRMupdate└──QueueC:eventswithamount>1000→fraudcheck

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, suffix
  • numeric: ["=", 5], [">", 100]
  • anything-but: exclude
  • cidr: IP range matching

5. Targets (25+ types)

TargetUse case
LambdaCustom processing
SQSQueue for async processing
SNSFanout to subscribers
Step FunctionsWorkflow orchestration
KinesisStream processing
EC2 Run CommandAutomation
EC2 Action (stop, terminate, reboot)EC2 management
Glue JobETL trigger
CodePipelineCI/CD trigger
API Destinations (HTTP endpoint)Webhook to external system
Batch JobBatch compute trigger
ECS TaskContainer 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

  1. Sender account: Create rule, target = event bus ARN of receiver account
  2. Receiver account: Custom event bus, resource policy allowing sender account
  3. 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

  1. Create Archive for event bus
  2. Archive stores events (configurable retention)
  3. 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

Source──►Pipe(Filter→Enrich→Target)││├──SQS,DynamoDBStreams,Kinesis,Kafka,etc.│└──Lambda,StepFunctions,SQS,SNS,EventBridge,etc.

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

EventBridgeSNS
ModelEvent bus (rule-based)Pub/Sub topic
SourcesAWS services + custom + SaaSCustom only
FilteringPowerful (JSON pattern)Basic (attributes)
Targets25+ types10+ types
ReplayYesNo
Schema RegistryYesNo
SchedulerYes (cron)No
Use caseAWS-native events, complex routingNotifications, 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

  1. 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.

  2. 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.

  3. 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 (WaitTimeSeconds 1-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. Set ReceiveMessageWaitTimeSeconds ở queue level hoặc per-request.

  4. 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.

  5. 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.

  6. 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.

  7. 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.

  8. 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.

  9. 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.

  10. 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.

  1. 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.

  1. 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.

  1. 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.

  1. 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.

  1. 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


Bài tiếp theo →