What is Long Polling in SQS: Explanation and Example
Long polling in AWS SQS is a way to wait for messages to arrive in a queue without constantly checking. It keeps the connection open for a set time, reducing empty responses and saving costs by returning messages only when available or after the wait time ends.How It Works
Imagine you are waiting for a friend to call you. Instead of calling them every minute to ask if they are ready, you just stay on the phone line and wait patiently for their call. This is similar to how long polling works in AWS SQS.
Normally, when you check a queue for messages, you might get an empty response if no messages are there. With long polling, the system holds your request open for up to 20 seconds. If a message arrives during that time, it sends it immediately. If no message arrives, it sends an empty response after the wait.
This reduces the number of times you ask the queue for messages, saving network traffic and costs, and making your application more efficient.
Example
This example shows how to receive messages from an SQS queue using long polling with the AWS SDK for Python (boto3). It waits up to 10 seconds for messages before returning.
import boto3 sqs = boto3.client('sqs') queue_url = 'https://sqs.us-east-1.amazonaws.com/123456789012/MyQueue' response = sqs.receive_message( QueueUrl=queue_url, MaxNumberOfMessages=1, WaitTimeSeconds=10 # Enables long polling ) messages = response.get('Messages', []) if messages: print('Received message:', messages[0]['Body']) else: print('No messages received after waiting.')
When to Use
Use long polling when you want to reduce the number of empty responses and lower costs in your application that reads messages from SQS. It is especially useful when messages arrive irregularly or infrequently.
For example, if you have a system that processes orders or notifications, long polling helps your app wait efficiently for new tasks without wasting resources on constant checks.
Key Points
- Long polling waits up to 20 seconds for messages before responding.
- It reduces empty responses and lowers costs.
- It improves efficiency by reducing network calls.
- Set
WaitTimeSecondsinreceive_messageto enable it.