跳到正文
DEV Community· Aditya gupta·· 1 小時前AI 評分48

SQS 訊息為何會被處理兩次

The message that gets processed twice

AI 導讀

SQS 收到訊息後不會將其從佇列移除,而是在可見性逾時期間隱藏訊息;若工作者未能在逾時前刪除訊息,其他消費者便可能再次處理。預設逾時為 30 秒,長時間工作的任務可延長逾時,但從首次接收起上限為 12 小時。標準 SQS 佇列採至少一次傳遞,消費者應具備冪等性,不能只依賴逾時避免重複處理。

正文

Cover image for The message that gets processed twice

Aditya gupta

This story was written with the assistance of an AI writing program.

Your worker processed the SQS message. So why did another worker process it again?

Because receiving a message does not remove it from the queue. It hides it from other consumers for the length of the visibility timeout. If your worker does not delete the message before the timeout expires, it becomes visible again and another consumer can pick it up.

The default is 30 seconds, starting from the moment the message is delivered. You are expected to process and delete within that window.

Too short, and slow jobs can run twice. Too long, and failed messages take longer to reappear, so retries slow down. Match it to your real processing time.

For jobs that run long, extend the timeout while you work:
aws sqs change-message-visibility --queue-url --receipt-handle --visibility-timeout 300

A heartbeat that calls this periodically keeps the message hidden until the job finishes. Setting the timeout to 0 hands the message back immediately. The hard cap is 12 hours from the first receive, and extending does not reset that.

One more thing: standard SQS queues are at-least-once. Even inside the timeout, AWS does not guarantee a message will not be delivered more than once. Make your consumers idempotent instead of trusting the timeout.

Check your queue's setting:
aws sqs get-queue-attributes --queue-url --attribute-names VisibilityTimeout

Takeaway: the timeout hides a message; only DeleteMessage removes it. Tune the timeout, delete after success, and design for duplicates anyway.
Diagram: SQS visibility timeout. Receive 1 starts the visibility window; receive 2 inside the window returns nothing; after expiry, receive 3 returns the message again.

來源:DEV Community · dev.to