Amazon SQS

Serverless managed queue for decoupling producers from consumers. Extreme scale, no provisioning. Two flavours (Standard, FIFO), a Dead Letter Queue for poison messages, and a handful of gotchas — visibility timeout, idempotency, Lambda ESM sizing.

Queue managed serverless để tách producer khỏi consumer. Scale khủng, không cần provisioning. Hai loại (Standard, FIFO), Dead Letter Queue cho message độc, và vài cái bẫy — visibility timeout, idempotency, Lambda ESM sizing.

Reach for itNên dùng

  • Decouple producers from consumers so one can scale/fail independentlyTách producer khỏi consumer để scale/fail độc lập
  • Write buffer in front of DynamoDB / RDS to absorb spikesBuffer ghi trước DynamoDB / RDS để hút spike
  • Async request/response between microservicesRequest/response async giữa microservice
  • Fan-in from many producers to a worker pool (EC2 ASG / Lambda)Fan-in nhiều producer đổ về pool worker (EC2 ASG / Lambda)

Not the right toolKhông hợp

  • Fan-out one message → many subscribers → SNSFan-out 1 message → nhiều subscriber → SNS
  • Real-time streaming with replay / long retention → KinesisStream real-time có replay / retention dài → Kinesis
  • Long-running orchestration with branches → Step FunctionsOrchestration dài có branch → Step Functions
  • Payloads > 1 MiB without an S3 pointerPayload > 1 MiB mà không dùng S3 pointer

Standard vs FIFOStandard vs FIFO

Standard = huge throughput, at-least-once, best-effort ordering. FIFO = ordered, exactly-once processing per MessageGroupId, capped throughput. Standard = throughput lớn, at-least-once, thứ tự best-effort. FIFO = có thứ tự, exactly-once theo MessageGroupId, throughput giới hạn.

Standard FIFO
OrderThứ tự Best-effortBest-effort Preserved in send orderĐúng thứ tự gửi
DeliveryDelivery At-least-once (dup possible)At-least-once (có thể trùng) Exactly-once processingXử lý exactly-once
ThroughputThroughput ~Unlimited~Không giới hạn 300 msg/s · 3,000 msg/s batched · high-throughput mode: 70,000/s (~700,000/s batched)có batch · high-throughput mode: 70,000/s (~700,000/s có batch)
GroupingGrouping — MessageGroupId
DedupDedup — 5-min window · MessageDeduplicationId or content-based (SHA-256)Cửa sổ 5 phút · MessageDeduplicationId hoặc theo content (SHA-256)
Large payloadsPayload lớn Cap is 1 MiB (raised from 256 KiB, Aug 2025) — opt in by raising the queue's MaximumMessageSize (default stays 256 KiB). Billing counts each 64 KiB chunk as one request, so a 1 MiB message = 16 requests. Anything larger: blob to S3, S3 key in the message — the Extended Client Library does this transparently, up to 2 GB. Giới hạn 1 MiB (tăng từ 256 KiB, 8/2025) — phải tự nâng MaximumMessageSize của queue (mặc định vẫn 256 KiB). Billing tính mỗi 64 KiB là 1 request, nên message 1 MiB = 16 request. To hơn nữa: blob upload S3, message chứa key S3 — Extended Client Library làm sẵn, tới 2 GB.

Dead Letter QueueDead Letter Queue

A message that fails MaximumReceives attempts moves to a partner queue for inspection instead of looping forever. Message fail quá MaximumReceives lần sẽ chuyển sang queue kèm để inspect, không lặp mãi.

  • A consumer that doesn't DeleteMessage before visibility timeout = the message reappears. That's the failure loop.Consumer không DeleteMessage trước visibility timeout = message quay lại. Đó là failure loop.
  • MaximumReceives is the threshold before eviction to the DLQ. Small integer, tune per workload.MaximumReceives là ngưỡng trước khi đẩy sang DLQ. Số nhỏ, tuỳ workload.
  • DLQ must match queue type: FIFO ↔ FIFO, Standard ↔ Standard.DLQ phải cùng loại: FIFO ↔ FIFO, Standard ↔ Standard.
  • Set DLQ retention to 14 days so you have time to look before messages expire.Đặt retention DLQ 14 ngày để có thời gian điều tra trước khi hết hạn.
  • Expiry runs off the original enqueue timestamp — time spent in the source queue counts against DLQ retention. Another reason to max it at 14 days.Hết hạn tính theo enqueue timestamp gốc — thời gian nằm ở source queue trừ vào retention của DLQ. Thêm lý do để đặt max 14 ngày.
  • Numbers: visibility timeout default 30 s (max 12 h, extend per-message with ChangeMessageVisibility) · retention default 4 days, max 14 · long poll up to 20 s · delay up to 15 min.Con số: visibility timeout mặc định 30 s (max 12 h, gia hạn từng message bằng ChangeMessageVisibility) · retention mặc định 4 ngày, max 14 · long poll tối đa 20 s · delay tối đa 15 phút.
Why it existsVì sao có Debugging. If a bad message keeps crashing every consumer, without a DLQ you'd throttle the whole worker pool. The DLQ pulls the poison message out of the hot path. Debugging. Nếu 1 message xấu làm crash mọi consumer, không có DLQ thì cả pool bị chết đứng. DLQ kéo message độc khỏi luồng chính.

DLQ Redrive to SourceDLQ Redrive to Source

Native feature to push messages from the DLQ back to the source queue (or any queue) in batches. No custom code, no manual consumer. Feature native để đẩy message từ DLQ trở lại source queue (hoặc queue khác) theo batch. Không cần code, không cần consumer tay.

  • Inspect + fix the bug in the consumer, then hit "Start DLQ redrive". Messages replay through the fixed code path.Kiểm tra + sửa bug trong consumer, sau đó bấm "Start DLQ redrive". Message được replay qua code đã sửa.
  • Configurable destination — usually the source queue, but you can redirect to a triage queue.Có thể chọn đích — thường là source, nhưng có thể chuyển sang queue triage.

Idempotency at the consumerIdempotency ở consumer

SQS Standard is at-least-once. Any consumer will see duplicates. Design the write so re-doing it is a no-op. SQS Standard là at-least-once. Consumer sẽ gặp duplicate. Thiết kế bước ghi sao cho làm lại không gây tác dụng phụ.

Not idempotentKhông idempotent IdempotentIdempotent
DynamoDB PutItem that always creates a new rowPutItem luôn tạo row mới Upsert by natural keyUpsert theo key nghiệp vụ
SQL INSERT auto-incrementINSERT auto-increment INSERT … ON CONFLICT DO NOTHING
Charges Stripe charge without idempotency-keyStripe charge không có idempotency-key Same op keyed by MessageId or business IDCùng thao tác gắn MessageId hoặc ID nghiệp vụ
PipelinePipeline SQS → EC2 consumer (long polling, batch fetch) → upsert into DynamoDB → DeleteMessage. If the consumer crashes between the upsert and the delete, the message returns to the queue — the upsert absorbs the retry. SQS → EC2 consumer (long polling, lấy batch) → upsert vào DynamoDB → DeleteMessage. Nếu consumer chết giữa upsert và delete, message quay về queue — upsert hấp thụ lần retry.

Lambda Event Source MappingLambda Event Source Mapping

Lambda's ESM long-polls SQS, hands the function a batch, and manages deletes on success. Works for both Standard and FIFO. ESM của Lambda long-poll SQS, đưa function 1 batch, và tự xoá message khi thành công. Dùng được cả Standard và FIFO.

  • Batch size: Standard up to 10,000 msgs (>10 needs a batch window ≥1 s; total event ≤6 MB) · FIFO max 10.Batch size: Standard tới 10,000 message (>10 phải set batch window ≥1 s; tổng event ≤6 MB) · FIFO max 10.
  • Set queue visibility timeout to 6× Lambda timeout. If a batch takes 20 s of Lambda work, give SQS ~120 s so it doesn't re-deliver mid-processing.Đặt visibility timeout của queue = 6× timeout Lambda. Batch tốn 20 s Lambda thì cho SQS ~120 s để không tái phát khi đang xử lý.
  • DLQ configured on the SQS queue, not on the Lambda function. Lambda's own DLQ is for async invocations only.DLQ đặt trên queue SQS, không phải trên Lambda function. DLQ của Lambda chỉ áp dụng cho invocation async.
  • Alternative: use a Lambda Destination for failures instead of an SQS DLQ.Cách khác: dùng Lambda Destination cho fail thay cho DLQ SQS.
  • To cap concurrency, set ESM maximum concurrency (min 2) — not reserved concurrency on the function. Reserved concurrency makes pollers get throttled, batches retry, and messages leak to the DLQ.Muốn giới hạn concurrency, set maximum concurrency của ESM (min 2) — không phải reserved concurrency trên function. Reserved concurrency làm poller bị throttle, batch retry, message rớt sang DLQ.
  • Enable partial batch responses (ReportBatchItemFailures) — otherwise one bad record sends the whole batch back to the queue.Bật partial batch response (ReportBatchItemFailures) — không thì 1 record hỏng kéo cả batch quay lại queue.

Request / Response patternPattern Request / Response

Two queues: one for the request, one for the response. Gives you decoupling, fault-tolerance, and load balancing across workers. Hai queue: một cho request, một cho response. Được decoupling, fault-tolerance, và cân tải qua worker.

DecouplingDecoupling Client and worker deploy independentlyClient và worker deploy độc lập
Fault toleranceFault tolerance Worker crash → message stays queuedWorker chết → message vẫn ở queue
Load balancingCân tải Fleet drains the queue at its paceFleet rút queue theo tốc độ của nó
Async by designAsync từ đầu Client can time out and reconnect laterClient có thể timeout và kết nối lại sau