Sub topic 5
Long polling to cut empty responses and cost
This chapter assumes you can send and receive SQS messages with boto3, and that you know a received message stays hidden until it is deleted or its visibility timeout expires. Here you will see how a ReceiveMessage call can wait for messages, and why that is usually the right default.
Short polling and long polling
A ReceiveMessage call can behave in two ways:
- Short polling returns immediately. SQS stores each queue on many servers. A short poll asks only a random subset of them, so it can return an empty response even when messages exist on servers that were not asked. Short polling is the default for a queue that has not been configured otherwise.
- Long polling waits up to a time you choose, from 1 to 20 seconds. SQS queries all of its servers for the queue. It returns as soon as at least one message is available. If nothing arrives before the wait ends, it returns an empty response.
You turn on long polling by setting a wait time greater than zero. A wait time of zero means short polling.
Why it reduces cost
SQS bills per request, and an empty response counts as a request. A consumer that short polls an idle queue once per second makes 86,400 requests per day and gets nothing back from any of them. A consumer that long polls with a 20-second wait makes at most 4,320 requests per day on the same idle queue (86,400 / 20).
Long polling also reduces latency. A message that arrives during a long poll is returned right away. A short-polling consumer has to wait for its next loop iteration, and that poll may still miss the message because of the server sampling.
Two ways to enable it
You can set the wait time on the queue, so every consumer long polls by default. You can also set it on each call.
import boto3
sqs = boto3.client("sqs")
queue_url = sqs.get_queue_url(QueueName="orders")["QueueUrl"]
# Option 1: queue-level default (0-20 seconds)
sqs.set_queue_attributes(
QueueUrl=queue_url,
Attributes={"ReceiveMessageWaitTimeSeconds": "20"},
)
# Option 2: per-call value, which overrides the queue default
resp = sqs.receive_message(
QueueUrl=queue_url,
MaxNumberOfMessages=10,
WaitTimeSeconds=20,
)
print(len(resp.get("Messages", [])), "messages received")The per-call WaitTimeSeconds takes precedence over the queue attribute. If you pass WaitTimeSeconds=0 on a call, that call short polls even if the queue default is 20. This is useful for a quick "is anything there?" check, but it is a common cause of unexpected empty responses when someone adds it by accident.
Client timeouts
The HTTP client must be willing to wait longer than the long-poll wait. The default boto3 read timeout is 60 seconds, which is enough for a 20-second wait. If you or your platform lowered it, the client gives up before SQS responds, and you get timeout errors instead of empty responses.
import boto3
from botocore.config import Config
# Read timeout must exceed WaitTimeSeconds
config = Config(read_timeout=25, retries={"max_attempts": 3})
sqs = boto3.client("sqs", config=config)
queue_url = sqs.get_queue_url(QueueName="orders")["QueueUrl"]
while True:
resp = sqs.receive_message(
QueueUrl=queue_url,
MaxNumberOfMessages=10,
WaitTimeSeconds=20,
)
for msg in resp.get("Messages", []):
print("got", msg["Body"])
sqs.delete_message(
QueueUrl=queue_url, ReceiptHandle=msg["ReceiptHandle"]
)Note that the loop has no sleep. With long polling, the wait happens inside the call, so an idle consumer does not spin. If you copy a short-polling loop that sleeps between calls, you can remove the sleep once you enable long polling.
Behavior to know about
- Fewer messages than requested.
MaxNumberOfMessagesis an upper bound (1 to 10). A long poll returns as soon as any message is available, so it may return one message even if you asked for ten. It does not wait to fill the batch. - Empty responses still happen. If the queue stays empty for the whole wait, you get an empty list. Your code must handle
resp.get("Messages", [])rather than indexingresp["Messages"], which raisesKeyErrorwhen the key is missing. - One long poll holds one connection. A consumer with many worker threads should give each thread its own receive loop, or use a shared client with a sufficient connection pool. Check your HTTP pool size if threads block each other.
- Visibility timeout starts at delivery. The timer begins when SQS returns the message, not when the long poll began, so waiting does not eat into processing time.
- Lambda event source mappings. Lambda polls SQS for you, so you do not set a wait time in your function code.
Checking that it works
CloudWatch reports NumberOfEmptyReceives for each queue. This counts ReceiveMessage calls that returned nothing. After switching to long polling, you should see this metric drop sharply on an idle or lightly used queue. If it stays high, look for consumers that pass WaitTimeSeconds=0, consumers that use a different SDK default, or many consumers polling a nearly idle queue.
When short polling is still reasonable
Long polling is the right default in almost every case. Short polling suits a single-threaded program that polls several queues in one loop. A long wait on the first queue would delay checking the others. In that case, consider a separate thread for each queue, each with long polling, rather than reverting to short polling.
Exercise
A consumer loop calls receive_message(QueueUrl=url, WaitTimeSeconds=0) and sleeps one second between calls. The queue has ReceiveMessageWaitTimeSeconds set to 20. Is the consumer long polling? What two changes would you make to cut its request count on an idle queue, and what is the maximum number of requests per day afterward for one consumer?
Show answer
It is not long polling, because the per-call WaitTimeSeconds=0 overrides the queue default and makes each call a short poll. Remove the WaitTimeSeconds=0 argument (or set it to 20), and remove the one-second sleep, since the wait now happens inside the call. On an idle queue, one consumer then makes at most 86,400 / 20 = 4,320 requests per day.