SQS Visibility Timeout

Difficulty: Intermediate

Question

What is the SQS visibility timeout, how should you set it, and what happens if a consumer takes longer than the timeout?

Answer

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.

The message lifecycle

  1. A producer sends a message; it is stored and visible.
  2. Consumer A calls ReceiveMessage. SQS returns the message with a receipt handle and starts the visibility timer.
  3. While the timer runs, the message is in flight and hidden from other consumers.
  4. Consumer A processes it and calls DeleteMessage with the receipt handle. Done.
  5. If A crashes or is too slow, the timer expires, the message becomes visible again, and Consumer B may receive it. Its 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.

Choosing the right value

  • Set it longer than the worst-case processing time, with headroom. If generating a PDF invoice usually takes 20 seconds but can take 90, 30 seconds will cause duplicate processing.
  • Do not set it far too high. If a consumer crashes, the message waits for the full timeout before anyone retries it, which delays recovery.
  • For Lambda consumers, AWS recommends setting the queue's visibility timeout to at least six times the function timeout, so retries and batching do not cause premature redelivery.

Extending the timeout for long jobs

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.

Pairing it with a dead-letter queue

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.

Common mistakes

MistakeSymptomFix
Timeout shorter than processing timeDuplicate emails, double chargesIncrease timeout or heartbeat
Deleting before processing finishesLost messages on crashDelete only after success
No idempotencyDuplicates cause real damageUse an idempotency key, for example the payment id
Huge timeoutSlow retries after crashesSize 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.

Visibility timeout in action. A received message is hidden, then either deleted or made visible again for another consumer.
  1. Consumer A → SQS queue: ReceiveMessage
  2. SQS queue → Consumer A: Message plus receipt handle
  3. Consumer A → SQS queue: Crashes, no DeleteMessage
  4. SQS queue → SQS queue: Timeout expires, message visible
  5. Consumer B → SQS queue: ReceiveMessage
  6. SQS queue → Consumer B: Same message, receive count 2
  7. Consumer B → SQS queue: DeleteMessage after success

Code examples

Consumer with a visibility heartbeat

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.

Redrive policy to a DLQ

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.

Key points

  • Default visibility timeout is 30 seconds; maximum is 12 hours.
  • Messages are only removed by DeleteMessage with the receipt handle.
  • Set the timeout above worst-case processing time; for Lambda, at least six times the function timeout.
  • Use ChangeMessageVisibility as a heartbeat for variable-length jobs.
  • Combine with a DLQ (maxReceiveCount) and idempotent consumers.

Common follow-up questions

  • How does SQS achieve at-least-once delivery, and how do you make consumers idempotent?
  • What is the difference between visibility timeout and delay queues?
  • How does visibility timeout behave in FIFO queues with message groups?
  • What is long polling and how does it relate to ReceiveMessage?

Interview tips

  • Walk through the receive, process, delete lifecycle; it shows you understand why duplicates happen.
  • Mention the six-times-Lambda-timeout guideline and the heartbeat pattern.
  • Always pair the answer with DLQs and idempotency; interviewers expect both.

Concepts covered

Visibility Timeout, Receipt Handle, Dead-letter Queue, At-least-once Delivery, ChangeMessageVisibility, Idempotency

More AWS & Cloud Fundamentals questions