Difficulty: Intermediate
What is the SQS visibility timeout, how should you set it, and what happens if a consumer takes longer than the timeout?
The SQS visibility timeout is the period after a consumer receives a message during which SQS hides that message from other consumers. If the consumer deletes the message before the timeout expires, it is gone; if not, the message becomes visible again and another consumer can receive it. The default is 30 seconds, the maximum is 12 hours, and it can be set per queue or per receive call.
ReceiveMessage. SQS returns the message with a receipt handle and starts the visibility timer.DeleteMessage with the receipt handle. Done.ApproximateReceiveCount goes up.SQS never deletes a message just because it was received. This is what makes standard queues at-least-once: the same message can be processed more than once.
If processing time varies, use a heartbeat: call ChangeMessageVisibility periodically to extend the timeout while work is still progressing. Setting it to 0 makes the message visible immediately, which is a quick way to hand it back after a known transient failure.
A redrive policy with maxReceiveCount moves a message to a dead-letter queue (DLQ) after it has been received that many times without deletion. Without a DLQ, a poison message that always crashes the consumer would bounce forever. Use DLQ redrive to move messages back after fixing the bug.
| Mistake | Symptom | Fix |
|---|---|---|
| Timeout shorter than processing time | Duplicate emails, double charges | Increase timeout or heartbeat |
| Deleting before processing finishes | Lost messages on crash | Delete only after success |
| No idempotency | Duplicates cause real damage | Use an idempotency key, for example the payment id |
| Huge timeout | Slow retries after crashes | Size to realistic worst case |
In FIFO queues, while a message from a message group is in flight, later messages in the same group are not delivered, so a slow consumer also blocks its group. For a payment workflow at a company like Razorpay, the visibility timeout plus idempotent handlers is what stops a webhook from being processed twice.
import threading, boto3
sqs = boto3.client("sqs")
QUEUE = "https://sqs.ap-south-1.amazonaws.com/111122223333/invoices"
def heartbeat(handle, stop):
# Every 20s, push visibility out to 60s from now
while not stop.wait(20):
sqs.change_message_visibility(QueueUrl=QUEUE, ReceiptHandle=handle,
VisibilityTimeout=60)
resp = sqs.receive_message(QueueUrl=QUEUE, MaxNumberOfMessages=1,
WaitTimeSeconds=20, VisibilityTimeout=60)
for msg in resp.get("Messages", []):
stop = threading.Event()
threading.Thread(target=heartbeat, args=(msg["ReceiptHandle"], stop)).start()
try:
generate_invoice(msg["Body"]) # may take minutes
sqs.delete_message(QueueUrl=QUEUE, ReceiptHandle=msg["ReceiptHandle"])
finally:
stop.set()
The heartbeat keeps the message hidden while work progresses; if the process dies, heartbeats stop and the message reappears within about a minute instead of waiting hours.
aws sqs set-queue-attributes --queue-url $QUEUE_URL --attributes '{
"VisibilityTimeout": "120",
"RedrivePolicy": "{\"deadLetterTargetArn\":\"arn:aws:sqs:ap-south-1:111122223333:invoices-dlq\",\"maxReceiveCount\":\"5\"}"
}'
After five failed receives the message moves to the DLQ, so one poison message cannot block or waste consumers forever.
Visibility Timeout, Receipt Handle, Dead-letter Queue, At-least-once Delivery, ChangeMessageVisibility, Idempotency