Sub topic 4
Visibility timeout: how SQS hides messages while you work
This chapter assumes you can send and receive SQS messages with boto3, know what a queue's receipt handle is, and have read the previous chapter on the send, receive, and delete lifecycle. It covers what the visibility timeout does, how to set and change it, and the errors that come from setting it wrong.
The problem it solves
SQS does not hand a message to one consumer and forget it. A queue is a distributed system, and a consumer can crash, hang, or lose its network connection after it receives a message. If SQS removed the message on receive, that work would be lost.
Instead, SQS keeps the message and hides it. The period during which a received message is hidden from other consumers is the visibility timeout. If the consumer deletes the message before the period ends, the message is gone for good. If it does not, the message becomes visible again and another receive call can return it.
This is why the lifecycle has a separate delete step. Receiving a message is a lease, and deleting it is how you confirm the work is done.
How it works
The timeout starts the moment SQS returns the message to you, not when you begin processing.
- A consumer calls
ReceiveMessage. SQS returns the message and starts a timer. - While the timer runs, no other
ReceiveMessagecall returns that message. - If the consumer calls
DeleteMessagewith the receipt handle before the timer ends, the message is removed. - If the timer ends first, the message becomes visible again. The next receive call can return it, and it gets a new receipt handle.
The receipt handle is tied to a single receive. Each time a message is received, SQS issues a new handle, and you must use the handle from the most recent receive when you delete or change the message.
Default and limits
The default visibility timeout for a queue is 30 seconds. The allowed range is 0 seconds to 12 hours. You can set it in three places.
| Where | How | Scope |
|---|---|---|
| Queue attribute | `VisibilityTimeout` on `CreateQueue` or `SetQueueAttributes` | Every message received from the queue |
| Receive call | `VisibilityTimeout` parameter on `ReceiveMessage` | Only the messages returned by that call |
| Per message | `ChangeMessageVisibility` | One in-flight message |
A value on the receive call overrides the queue default for that call. The queue default is what you get when you pass nothing.
Setting the timeout
The queue-level setting is the one to get right first. The example below creates a queue with a 60-second timeout.
import boto3
sqs = boto3.client("sqs")
queue_url = sqs.create_queue(
QueueName="orders",
Attributes={"VisibilityTimeout": "60"},
)["QueueUrl"]
attrs = sqs.get_queue_attributes(
QueueUrl=queue_url, AttributeNames=["VisibilityTimeout"]
)["Attributes"]
print(attrs["VisibilityTimeout"])Attribute values are passed as strings, even for numbers. Passing an integer raises a parameter validation error in boto3.
A good starting rule is to set the timeout to several times the time your consumer normally needs to process one message. A consumer that takes 10 seconds on average and 25 at the slow end is safer with 60 seconds than with the 30-second default. If you receive a batch of 10 messages and process them one after another, the last message waits while the first nine are processed. The timeout for the whole batch has to cover that wait.
Extending the timeout while you work
Some jobs have unpredictable duration. Setting a 12-hour timeout for all of them is a poor answer, because a crashed consumer would then delay the retry by up to 12 hours. The better pattern is a short timeout that the consumer extends as it works, a technique often called a heartbeat.
ChangeMessageVisibility sets a new timeout for one in-flight message. The new value counts from the moment of the call, not from the original receive.
import boto3
sqs = boto3.client("sqs")
queue_url = sqs.get_queue_url(QueueName="orders")["QueueUrl"]
resp = sqs.receive_message(
QueueUrl=queue_url,
MaxNumberOfMessages=1,
WaitTimeSeconds=20,
VisibilityTimeout=30,
)
for msg in resp.get("Messages", []):
handle = msg["ReceiptHandle"]
for step in range(3):
# ... one slice of long-running work ...
# Push the deadline out 30 seconds from now
sqs.change_message_visibility(
QueueUrl=queue_url,
ReceiptHandle=handle,
VisibilityTimeout=30,
)
sqs.delete_message(QueueUrl=queue_url, ReceiptHandle=handle)Two rules apply to extensions.
- The total time a message can stay in flight is capped at 12 hours from the first receive. Extending beyond that is rejected.
- You can only change the visibility of a message that is currently in flight. If the timeout has already expired, or another consumer has received the message, the call fails.
You can also use ChangeMessageVisibility in the other direction. Setting the timeout to 0 makes the message visible again immediately. This is a quick way to release a message when the consumer decides it cannot process it right now.
What "in flight" means
A message is in flight after a receive call returns it and before it is deleted or its timeout expires. In-flight messages count against a quota. A standard queue allows about 120,000 in-flight messages, and a FIFO queue allows 20,000. If you reach the quota, ReceiveMessage on a standard queue returns an OverLimit error, and on a FIFO queue it returns no messages.
This matters when consumers receive messages faster than they delete them, for example when a long timeout combines with a stuck consumer fleet. The ApproximateNumberOfMessagesNotVisible CloudWatch metric reports the in-flight count.
Common errors
- Timeout shorter than processing time. The message reappears while the first consumer is still working, a second consumer picks it up, and the work runs twice. The receive count also rises, which pushes the message toward the dead-letter queue even though nothing failed.
- Timeout much longer than needed. A consumer that crashes leaves the message hidden for the full period, so recovery is slow.
- Using a stale receipt handle. After a timeout expires and the message is received again, the old handle can no longer be relied on. Deleting with an old handle may fail or may silently not remove the message. Always use the handle from the latest receive.
- Deleting after a failure. Deleting in a
finallyblock removes messages that were never processed. Delete only on success. - Integer attribute values.
{"VisibilityTimeout": 60}fails in boto3. Use"60".
Interaction with other features
The visibility timeout works with retries and dead-letter queues. Each time a message is received, SQS increments its receive count. When the count exceeds the maxReceiveCount in the redrive policy, SQS moves the message to the dead-letter queue. A timeout that is too short therefore causes extra receives and can send healthy messages to the dead-letter queue.
For Lambda consumers, AWS recommends setting the queue's visibility timeout to at least six times the function timeout, plus the value of the batch window. This leaves room for retries after throttling.
Duplicates from an expired timeout are one reason consumers must be idempotent, which a later chapter covers.
Exercise
A consumer receives a batch of 10 messages from a queue with the default visibility timeout. It processes them one at a time, and each takes about 5 seconds. What happens to the later messages in the batch, and what are two ways to fix it?
Show answer
The timeout starts for all 10 messages when the batch is received. The consumer needs about 50 seconds, which is longer than the 30-second default, so the last few messages become visible again before the consumer reaches them. Another consumer can receive them, and the work is duplicated. Fixes: raise the queue's VisibilityTimeout above the full batch time (for example to 120 seconds), or receive fewer messages per call with a smaller MaxNumberOfMessages. Calling ChangeMessageVisibility for the remaining messages as you go also works.
Exercise
A consumer calls ChangeMessageVisibility with VisibilityTimeout=30 twenty seconds after it received a message whose timeout was 60 seconds. How long does the message stay hidden from that point, and why?
Show answer
It stays hidden for 30 more seconds, until 50 seconds after the original receive. The new value counts from the time of the ChangeMessageVisibility call, not from the original receive, so it replaces the remaining 40 seconds. This shortens the hiding period. To extend it, pass a value larger than the time remaining.