Appearance
AWS Integration & Messaging — Theory (Bản gốc slide / Original slide)
1. Section Introduction — Sync vs. Async Communication
- Khi triển khai nhiều ứng dụng, chúng chắc chắn sẽ cần giao tiếp với nhau
- Có 2 kiểu giao tiếp giữa ứng dụng:
- Synchronous (application → application trực tiếp)
- Asynchronous / Event-based (application → queue → application)
- Giao tiếp đồng bộ (sync) có thể gặp vấn đề khi có spike traffic đột ngột — ví dụ: bình thường encode 10 video, đột nhiên cần encode 1000 video cùng lúc thì sao?
- Trong trường hợp đó, tốt hơn nên decouple (tách rời) các ứng dụng:
- Dùng SQS: mô hình queue
- Dùng SNS: mô hình pub/sub
- Dùng Kinesis: mô hình real-time streaming
- Các dịch vụ này có thể scale độc lập với ứng dụng của bạn!
- When deploying multiple applications, they will inevitably need to communicate with one another
- There are two patterns of application communication:
- Synchronous (application to application, directly)
- Asynchronous / Event-based (application to queue to application)
- Synchronous communication between applications can be problematic if there are sudden spikes of traffic — what if you need to suddenly encode 1000 videos but usually it's 10?
- In that case, it's better to decouple your applications:
- Using SQS: queue model
- Using SNS: pub/sub model
- Using Kinesis: real-time streaming model
- These services can scale independently from our application!
2. Amazon SQS — Queue là gì? (What's a Queue?)
- Nhiều Producer gửi message vào SQS Queue
- Nhiều Consumer poll (kéo) message ra khỏi queue để xử lý
- Multiple Producers send messages into the SQS Queue
- Multiple Consumers poll messages from the queue to process them
3. Amazon SQS — Standard Queue
- Dịch vụ lâu đời nhất của AWS (hơn 10 năm)
- Fully managed service, dùng để decouple ứng dụng
- Đặc điểm:
- Throughput không giới hạn, số lượng message không giới hạn trong queue
- Retention mặc định 4 ngày, tối đa 14 ngày
- Độ trễ thấp (< 10ms lúc publish và receive)
- Giới hạn 1,024 KB mỗi message
- Có thể có message trùng lặp (at least once delivery, thỉnh thoảng)
- Có thể có message không đúng thứ tự (best effort ordering)
- Oldest offering of AWS (over 10 years old)
- Fully managed service, used to decouple applications
- Attributes:
- Unlimited throughput, unlimited number of messages in queue
- Default retention 4 days, maximum 14 days
- Low latency (< 10 ms on publish and receive)
- Limitation of 1,024 KB per message
- Can have duplicate messages (at least once delivery, occasionally)
- Can have out of order messages (best effort ordering)
4. SQS — Producing & Consuming Messages
Producing Messages:
- Gửi vào SQS bằng SDK (
SendMessageAPI) - Message được lưu trong SQS cho tới khi consumer xoá nó
- Ví dụ: gửi order để xử lý (order id, customer id, các attribute tuỳ ý), kích thước tối đa 1024 KB
- SQS Standard: throughput không giới hạn
Consuming Messages:
- Consumer (chạy trên EC2, server, hoặc AWS Lambda)…
- Poll SQS để lấy message (nhận tối đa 10 message mỗi lần)
- Xử lý message (ví dụ: insert vào RDS database)
- Xoá message bằng
DeleteMessageAPI
Nhiều EC2 Consumer:
- Các consumer nhận và xử lý message song song
- At least once delivery, best-effort ordering
- Consumer xoá message sau khi xử lý xong
- Có thể scale ngang consumer để tăng throughput xử lý
Producing Messages:
- Produced to SQS using the SDK (
SendMessageAPI) - The message is persisted in SQS until a consumer deletes it
- Example: send an order to be processed (order id, customer id, any attributes), up to 1024 KB
- SQS standard: unlimited throughput
Consuming Messages:
- Consumers (running on EC2 instances, servers, or AWS Lambda)…
- Poll SQS for messages (receive up to 10 messages at a time)
- Process the messages (e.g., insert into an RDS database)
- Delete the messages using the
DeleteMessageAPI
Multiple EC2 Instances Consumers:
- Consumers receive and process messages in parallel
- At least once delivery, best-effort message ordering
- Consumers delete messages after processing them
- We can scale consumers horizontally to improve throughput
5. SQS với Auto Scaling Group & Decouple Application Tiers
SQS với Auto Scaling Group (ASG):
- ASG poll message từ queue
- Dựa trên CloudWatch Metric — Queue Length (
ApproximateNumberOfMessages) - Khi vượt ngưỡng → CloudWatch Alarm kích hoạt → ASG tự scale thêm EC2 instance
SQS để decouple giữa các tầng ứng dụng (Application Tiers):
- Front-end web app nhận request →
SendMessagevào SQS Queue (scale vô hạn) - Back-end processing application →
ReceiveMessagesđể xử lý - Cả 2 tầng đều Auto-Scaling độc lập với nhau
SQS làm buffer cho database writes:
- Nếu load quá lớn mà ghi thẳng vào RDS/Aurora/DynamoDB, có thể mất transaction
- Giải pháp: đẩy request vào SQS Queue trước (enqueue), rồi consumer dequeue và insert vào DB — giúp đệm (buffer) tải đột biến, tránh làm quá tải hoặc mất dữ liệu
SQS with Auto Scaling Group (ASG):
- ASG polls for messages from the queue
- Based on CloudWatch Metric — Queue Length (
ApproximateNumberOfMessages) - When it breaches a threshold → CloudWatch Alarm fires → ASG scales EC2 instances
SQS to decouple between application tiers:
- Front-end web app receives requests →
SendMessageinto the SQS Queue (infinitely scalable) - Back-end processing application →
ReceiveMessagesto process them - Both tiers Auto-Scale independently
SQS as a buffer to database writes:
- If the load is too big and you write directly to RDS/Aurora/DynamoDB, transactions may be lost
- Solution: enqueue requests into an SQS Queue first, then a consumer dequeues and inserts into the DB — this buffers traffic spikes, avoiding overload or data loss
6. Amazon SQS — Security
- Encryption:
- In-flight: mã hoá bằng HTTPS API
- At-rest: mã hoá bằng KMS key
- Client-side: nếu client muốn tự mã hoá/giải mã
- Access Controls: dùng IAM policy để kiểm soát quyền truy cập SQS API
- SQS Access Policies (tương tự S3 bucket policy):
- Hữu ích cho truy cập cross-account tới SQS queue
- Hữu ích để cho phép service khác (SNS, S3…) ghi vào SQS queue
- Encryption:
- In-flight encryption using HTTPS API
- At-rest encryption using KMS keys
- Client-side encryption if the client wants to perform encryption/decryption itself
- Access Controls: IAM policies to regulate access to the SQS API
- SQS Access Policies (similar to S3 bucket policies):
- Useful for cross-account access to SQS queues
- Useful for allowing other services (SNS, S3…) to write to an SQS queue
7. SQS — Message Visibility Timeout
- Sau khi một message được poll bởi một consumer, nó trở nên vô hình (invisible) với các consumer khác
- Mặc định "message visibility timeout" = 30 giây
- Nghĩa là message có 30 giây để được xử lý xong
- Sau khi hết visibility timeout, message "hiện lại" (visible) trong SQS
- Nếu message không được xử lý xong trong thời gian visibility timeout, nó sẽ bị xử lý lại (processed twice)
- Consumer có thể gọi
ChangeMessageVisibilityAPI để xin thêm thời gian - Nếu visibility timeout quá cao (hàng giờ) và consumer crash → việc xử lý lại sẽ mất nhiều thời gian
- Nếu visibility timeout quá thấp (vài giây) → có thể gây ra message trùng lặp (duplicates)
- After a message is polled by a consumer, it becomes invisible to other consumers
- By default, the "message visibility timeout" is 30 seconds
- That means the message has 30 seconds to be processed
- After the message visibility timeout is over, the message becomes "visible" again in SQS
- If a message is not processed within the visibility timeout, it will be processed twice
- A consumer could call the
ChangeMessageVisibilityAPI to get more time - If visibility timeout is too high (hours), and the consumer crashes, re-processing will take time
- If visibility timeout is too low (seconds), we may get duplicates
8. Amazon SQS — Long Polling
- Khi consumer request message từ queue, nó có thể tuỳ chọn "chờ" (wait) nếu queue chưa có message nào
- Gọi là Long Polling
- Long Polling giúp giảm số lượng API call tới SQS, đồng thời tăng hiệu quả và giảm latency của ứng dụng
- Thời gian chờ có thể từ 1 giây tới 20 giây (20 giây được khuyến nghị)
- Long Polling được ưu tiên hơn Short Polling
- Có thể bật Long Polling ở cấp queue hoặc ở cấp API bằng tham số
WaitTimeSeconds
- When a consumer requests messages from the queue, it can optionally "wait" for messages to arrive if there are none in the queue
- This is called Long Polling
- Long Polling decreases the number of API calls made to SQS while increasing efficiency and reducing latency
- The wait time can be between 1 sec to 20 sec (20 sec preferable)
- Long Polling is preferable to Short Polling
- Long polling can be enabled at the queue level or at the API level using
WaitTimeSeconds
9. Amazon SQS — FIFO Queue
- FIFO = First In First Out (đảm bảo thứ tự message trong queue)
- Throughput giới hạn: 300 msg/s (không batching), 3000 msg/s (có batching)
- Exactly-once send (loại bỏ trùng lặp bằng Deduplication ID)
- Message được xử lý theo đúng thứ tự bởi consumer
- Sắp xếp theo Message Group ID (mọi message cùng group được đảm bảo thứ tự) — tham số bắt buộc
- FIFO = First In First Out (ordering of messages in the queue)
- Limited throughput: 300 msg/s without batching, 3000 msg/s with batching
- Exactly-once send capability (by removing duplicates using a Deduplication ID)
- Messages are processed in order by the consumer
- Ordering by Message Group ID (all messages in the same group are ordered) — mandatory parameter
10. Amazon SNS — Tổng quan (Pub/Sub là gì?)
- Vấn đề: nếu muốn gửi một message tới NHIỀU receiver thì sao?
- "Event producer" chỉ gửi message tới MỘT SNS topic
- Có thể có bao nhiêu "event receiver" (subscription) tuỳ ý để lắng nghe notification từ topic
- Mỗi subscriber của topic sẽ nhận TẤT CẢ message (lưu ý: có tính năng mới để filter message)
- Tối đa 12,500,000 subscription mỗi topic
- Giới hạn 100,000 topic
- Các loại subscriber: SQS, Lambda, Kinesis Data Firehose, Email, SMS & Mobile Notification, HTTP(S) Endpoint
- The problem: what if you want to send one message to many receivers?
- The "event producer" only sends a message to ONE SNS topic
- There can be as many "event receivers" (subscriptions) as we want to listen to the topic's notifications
- Each subscriber to the topic gets ALL the messages (note: new feature to filter messages)
- Up to 12,500,000 subscriptions per topic
- 100,000 topics limit
- Subscriber types: SQS, Lambda, Kinesis Data Firehose, Email, SMS & Mobile Notifications, HTTP(S) Endpoints
11. SNS — Tích hợp, Publish & Security
SNS tích hợp với rất nhiều dịch vụ AWS — nhiều service có thể gửi thẳng dữ liệu vào SNS để tạo notification:
- CloudWatch Alarms, AWS Budgets, Lambda
- Auto Scaling Group (Notifications), S3 Bucket (Events), DynamoDB
- CloudFormation (State Changes), AWS DMS (New Replica), RDS Events
Cách publish:
- Topic Publish (dùng SDK): tạo topic → tạo subscription (một hoặc nhiều) → publish vào topic
- Direct Publish (cho mobile app SDK): tạo platform application → tạo platform endpoint → publish vào platform endpoint — hoạt động với Google GCM, Apple APNS, Amazon ADM…
Security:
- Encryption: in-flight (HTTPS), at-rest (KMS key), client-side (nếu tự mã hoá)
- Access Controls: IAM policy kiểm soát SNS API
- SNS Access Policies (tương tự S3 bucket policy): hữu ích cho cross-account access, và cho phép service khác (S3…) ghi vào SNS topic
SNS integrates with many AWS services — many services can send data directly to SNS for notifications:
- CloudWatch Alarms, AWS Budgets, Lambda
- Auto Scaling Group (Notifications), S3 Bucket (Events), DynamoDB
- CloudFormation (State Changes), AWS DMS (New Replica), RDS Events
How to publish:
- Topic Publish (using the SDK): create a topic → create a subscription (or many) → publish to the topic
- Direct Publish (for mobile apps SDK): create a platform application → create a platform endpoint → publish to the platform endpoint — works with Google GCM, Apple APNS, Amazon ADM…
Security:
- Encryption: in-flight (HTTPS), at-rest (KMS keys), client-side (if self-encrypting)
- Access Controls: IAM policies regulate the SNS API
- SNS Access Policies (similar to S3 bucket policies): useful for cross-account access, and for allowing other services (S3…) to write to an SNS topic
12. SNS + SQS: Fan Out
- Push một lần vào SNS, nhận ở tất cả SQS queue đã subscribe
- Hoàn toàn decoupled, không mất dữ liệu
- SQS cho phép: lưu trữ dữ liệu (persistence), xử lý trễ (delayed processing) và retry công việc
- Có thể thêm SQS subscriber theo thời gian
- Đảm bảo SQS queue access policy cho phép SNS ghi vào
- Cross-Region Delivery: hoạt động với SQS Queue ở region khác
Ứng dụng — S3 Events tới nhiều queue:
- Với cùng một cặp (event type, prefix), chỉ được có MỘT S3 Event rule
- Muốn gửi cùng một S3 event tới nhiều SQS queue → dùng fan-out qua SNS (S3 → SNS Topic → nhiều SQS Queue / Lambda Function)
Ứng dụng — SNS tới S3 qua Kinesis Data Firehose:
- SNS có thể gửi tới Kinesis Data Firehose, cho phép kiến trúc:
Buying Service → SNS Topic → Kinesis Data Firehose → Amazon S3(hoặc bất kỳ đích KDF hỗ trợ)
- Push once in SNS, receive in all SQS queues that are subscribers
- Fully decoupled, no data loss
- SQS allows for: data persistence, delayed processing and retries of work
- Ability to add more SQS subscribers over time
- Make sure your SQS queue access policy allows SNS to write
- Cross-Region Delivery: works with SQS Queues in other regions
Application — S3 Events to multiple queues:
- For the same (event type, prefix) combination, you can only have ONE S3 Event rule
- To send the same S3 event to many SQS queues → use fan-out via SNS (S3 → SNS Topic → multiple SQS Queues / Lambda Function)
Application — SNS to S3 through Kinesis Data Firehose:
- SNS can send to Kinesis Data Firehose, enabling:
Buying Service → SNS Topic → Kinesis Data Firehose → Amazon S3(or any KDF-supported destination)
13. SNS — FIFO Topic & Message Filtering
SNS FIFO Topic:
- FIFO = First In First Out (đảm bảo thứ tự message trong topic)
- Đặc điểm tương tự SQS FIFO:
- Sắp xếp theo Message Group ID
- Loại trùng bằng Deduplication ID hoặc Content-Based Deduplication
- Có thể có SQS Standard và SQS FIFO làm subscriber
- Throughput giới hạn (giống SQS FIFO)
- SNS FIFO + SQS FIFO: Fan Out — dùng khi cần cả fan-out, ordering, và deduplication cùng lúc
SNS — Message Filtering:
- Dùng JSON policy để lọc message gửi tới từng subscription của topic
- Nếu một subscription không có filter policy → nó nhận mọi message
- Ví dụ: topic order có nhiều subscription, mỗi subscription gắn Filter Policy riêng (
State: Placed,State: Cancelled,State: Declined) → mỗi SQS Queue/Email chỉ nhận đúng loại message mình quan tâm, cộng thêm một queue nhận tất cả (All)
SNS FIFO Topic:
- FIFO = First In First Out (ordering of messages in the topic)
- Similar features to SQS FIFO:
- Ordering by Message Group ID
- Deduplication using a Deduplication ID or Content-Based Deduplication
- Can have SQS Standard and FIFO queues as subscribers
- Limited throughput (same as SQS FIFO)
- SNS FIFO + SQS FIFO: Fan Out — used when you need fan out + ordering + deduplication
SNS — Message Filtering:
- A JSON policy used to filter messages sent to a topic's subscriptions
- If a subscription doesn't have a filter policy, it receives every message
- Example: an order topic with several subscriptions, each with its own Filter Policy (
State: Placed,State: Cancelled,State: Declined) → each SQS Queue/Email only receives the message type it cares about, plus one queue receiving all (All)
14. Amazon Kinesis Data Streams
- Thu thập và lưu trữ dữ liệu streaming theo thời gian thực
- Producer: Click Streams, IoT devices, Applications, Metrics & Logs, Kinesis Agent
- Consumer: Application, Lambda, Amazon Data Firehose, Managed Service for Apache Flink
Đặc điểm:
- Retention tối đa 365 ngày
- Có khả năng replay (xử lý lại) dữ liệu bởi consumer
- Dữ liệu không thể xoá khỏi Kinesis (cho tới khi hết hạn)
- Dữ liệu tối đa 10MiB (use case điển hình: nhiều dữ liệu real-time "nhỏ")
- Đảm bảo thứ tự dữ liệu cho cùng một Partition ID
- At-rest KMS encryption, in-flight HTTPS encryption
- Kinesis Producer Library (KPL) để viết producer tối ưu
- Kinesis Client Library (KCL) để viết consumer tối ưu
Capacity Modes:
- Provisioned mode: chọn số shard, mỗi shard nhận 1MB/s in (hoặc 1000 record/s) và 2MB/s out; scale thủ công tăng/giảm shard; trả phí theo shard được cấp phát/giờ
- On-demand mode: không cần cấp phát/quản lý capacity; capacity mặc định 4MB/s in (4000 record/s); tự động scale theo throughput peak quan sát được trong 30 ngày gần nhất; trả phí theo stream/giờ + data in/out theo GB
- Collect and store streaming data in real-time
- Producers: Click Streams, IoT devices, Applications, Metrics & Logs, Kinesis Agent
- Consumers: Application, Lambda, Amazon Data Firehose, Managed Service for Apache Flink
Attributes:
- Retention up to 365 days
- Ability to reprocess (replay) data by consumers
- Data can't be deleted from Kinesis (until it expires)
- Data up to 10MiB (typical use case is a lot of "small" real-time data)
- Data ordering guarantee for data with the same Partition ID
- At-rest KMS encryption, in-flight HTTPS encryption
- Kinesis Producer Library (KPL) to write an optimized producer application
- Kinesis Client Library (KCL) to write an optimized consumer application
Capacity Modes:
- Provisioned mode: choose the number of shards, each shard gets 1MB/s in (or 1000 records/s) and 2MB/s out; scale manually to increase/decrease shards; pay per shard provisioned per hour
- On-demand mode: no need to provision/manage capacity; default capacity 4MB/s in (4000 records/s); scales automatically based on observed throughput peak during the last 30 days; pay per stream per hour + data in/out per GB
15. Amazon Data Firehose
- Lưu ý: trước đây gọi là "Kinesis Data Firehose"
- Fully Managed Service, đích đến hỗ trợ:
- Amazon Redshift / Amazon S3 / Amazon OpenSearch Service
- Bên thứ 3: Splunk / MongoDB / Datadog / NewRelic…
- Custom HTTP Endpoint
- Tự động scale, serverless, trả tiền theo mức dùng
- Near Real-Time với khả năng buffer theo kích thước/thời gian
- Hỗ trợ CSV, JSON, Parquet, Avro, Raw Text, Binary data
- Convert sang Parquet/ORC, nén bằng gzip/snappy
- Custom data transformation bằng AWS Lambda (ví dụ: CSV → JSON)
Kinesis Data Streams vs. Amazon Data Firehose:
| Kinesis Data Streams | Amazon Data Firehose |
|---|---|
| Thu thập streaming data | Load streaming data vào S3/Redshift/OpenSearch/3rd party/custom HTTP |
| Tự viết producer & consumer code | Fully managed |
| Real-time | Near real-time |
| Provisioned/On-Demand mode | Tự động scale |
| Lưu trữ dữ liệu tới 365 ngày | Không lưu trữ dữ liệu |
| Có khả năng Replay | Không hỗ trợ Replay |
- Note: used to be called "Kinesis Data Firehose"
- Fully Managed Service, destinations:
- Amazon Redshift / Amazon S3 / Amazon OpenSearch Service
- 3rd party: Splunk / MongoDB / Datadog / NewRelic…
- Custom HTTP Endpoint
- Automatic scaling, serverless, pay for what you use
- Near Real-Time with buffering capability based on size/time
- Supports CSV, JSON, Parquet, Avro, Raw Text, Binary data
- Conversions to Parquet/ORC, compression with gzip/snappy
- Custom data transformations using AWS Lambda (e.g., CSV to JSON)
Kinesis Data Streams vs. Amazon Data Firehose:
| Kinesis Data Streams | Amazon Data Firehose |
|---|---|
| Streaming data collection | Load streaming data into S3/Redshift/OpenSearch/3rd party/custom HTTP |
| Producer & Consumer code | Fully managed |
| Real-time | Near real-time |
| Provisioned/On-Demand mode | Automatic scaling |
| Data storage up to 365 days | No data storage |
| Replay Capability | Doesn't support replay capability |
16. So sánh: SQS vs. SNS vs. Kinesis
| SQS | SNS | Kinesis |
|---|---|---|
| Consumer "pull data" | Push data tới nhiều subscriber | Standard: pull data — 2 MB/shard |
| Data bị xoá sau khi consume | Tối đa 12,500,000 subscriber | Enhanced fan-out: push data — 2 MB/shard/consumer |
| Có thể có bao nhiêu worker (consumer) tuỳ ý | Data không được persist (mất nếu không deliver được) | Có khả năng replay data |
| Không cần provision throughput | Mô hình Pub/Sub | Dành cho real-time big data, analytics, ETL |
| Đảm bảo thứ tự chỉ trên FIFO queue | Tối đa 100,000 topic | Đảm bảo thứ tự ở cấp shard |
| Có khả năng delay từng message riêng lẻ | Không cần provision throughput | Data hết hạn sau X ngày |
| Tích hợp SQS cho fan-out pattern | Provisioned hoặc On-Demand capacity mode | |
| Hỗ trợ FIFO cho SQS FIFO |
| SQS | SNS | Kinesis |
|---|---|---|
| Consumer "pull data" | Push data to many subscribers | Standard: pull data — 2 MB per shard |
| Data is deleted after consumed | Up to 12,500,000 subscribers | Enhanced fan-out: push data — 2 MB per shard per consumer |
| Can have as many workers (consumers) as we want | Data is not persisted (lost if not delivered) | Possibility to replay data |
| No need to provision throughput | Pub/Sub model | Meant for real-time big data, analytics, ETL |
| Ordering guarantees only on FIFO queues | Up to 100,000 topics | Ordering at the shard level |
| Individual message delay capability | No need to provision throughput | Data expires after X days |
| Integrates with SQS for fan-out pattern | Provisioned or On-Demand capacity mode | |
| FIFO capability for SQS FIFO |
17. Amazon MQ
- SQS, SNS là dịch vụ "cloud-native": giao thức độc quyền của AWS
- Ứng dụng truyền thống chạy on-premises có thể dùng các giao thức mở như: MQTT, AMQP, STOMP, Openwire, WSS
- Khi migrate lên cloud, thay vì phải re-engineer ứng dụng để dùng SQS/SNS, có thể dùng Amazon MQ
- Amazon MQ là managed message broker service hỗ trợ các giao thức mở kể trên
- Amazon MQ không scale mạnh như SQS/SNS
- Amazon MQ chạy trên server, có thể chạy Multi-AZ với failover
- Amazon MQ có cả tính năng queue (~SQS) lẫn topic (~SNS)
High Availability:
- Broker ACTIVE ở một AZ, broker STANDBY ở AZ khác — failover tự động khi ACTIVE gặp sự cố
- Cả hai broker dùng chung storage Amazon EFS
- SQS, SNS are "cloud-native" services: proprietary protocols from AWS
- Traditional applications running on-premises may use open protocols such as: MQTT, AMQP, STOMP, Openwire, WSS
- When migrating to the cloud, instead of re-engineering the application to use SQS and SNS, we can use Amazon MQ
- Amazon MQ is a managed message broker service for these open protocols
- Amazon MQ doesn't "scale" as much as SQS/SNS
- Amazon MQ runs on servers, can run in Multi-AZ with failover
- Amazon MQ has both queue features (~SQS) and topic features (~SNS)
High Availability:
- ACTIVE broker in one AZ, STANDBY broker in another AZ — automatic failover when ACTIVE has an issue
- Both brokers share Amazon EFS storage