How to Integrate SQS with Lambda or EC2 for Task Processing
Step-by-step SQS integration with Lambda event source mappings and EC2 workers: visibility timeout, DLQ, partial batch failures, backlog scaling.
You integrate Amazon SQS with Lambda by creating an event source mapping, so Lambda polls the queue and invokes your function with batches of messages. With EC2, your own worker process long-polls the queue, processes each message, deletes it, and an Auto Scaling group adds or removes workers based on backlog per instance. Both need correct visibility timeouts and a dead-letter queue.
This guide shows both patterns step by step, with CLI commands, worker code, scaling and failure handling, and a comparison to help you choose. It is part of our AWS cluster, which starts with the top AWS services DevOps engineers use daily.
Key takeaways
- Lambda reads SQS through an event source mapping. Batch size can be up to 10,000 for standard queues and 10 for FIFO queues; batches above 10 require a batching window of at least 1 second.
- Set the queue's visibility timeout to at least six times the function timeout, as AWS recommends, so retries after throttling do not cause duplicate processing.
- Turn on partial batch responses (
ReportBatchItemFailures) so only failed messages go back to the queue. - EC2 workers should use long polling (up to 20 seconds), delete each message after success, and scale on backlog per instance rather than raw queue length.
- SQS delivers at least once, so consumers must be idempotent in both patterns.
Why put a queue in front of task processing
A queue separates the part of a system that creates work from the part that does it. A web application can accept an image upload, put a message on a queue and respond to the user immediately, while workers resize the image in the background. If traffic spikes, messages wait in the queue instead of overwhelming the workers. If a worker crashes, the message becomes visible again and another worker picks it up.
Amazon SQS offers standard queues, with very high throughput and at-least-once delivery, and FIFO queues, with ordering within a message group and exactly-once processing within a deduplication window. Our guide on standard vs FIFO queues covers that choice, and the benefits of decoupling with SQS explains the architecture in more depth.
How SQS delivery works
Three settings control most behaviour, whichever consumer you use.
Visibility timeout. When a consumer receives a message, SQS hides it from other consumers for the visibility timeout, 30 seconds by default. If the consumer deletes the message before the timeout ends, it is gone. If not, it becomes visible again and can be received a second time. A consumer can extend the timeout with ChangeMessageVisibility, up to a maximum of 12 hours from first receipt.
Long polling. A ReceiveMessage call with WaitTimeSeconds greater than zero waits for messages to arrive, up to 20 seconds. This cuts empty responses and cost compared with short polling, which returns immediately even when no messages are available.
Redrive policy. A dead-letter queue (DLQ) receives messages that have been received more than maxReceiveCount times without being deleted. That keeps a "poison" message from looping forever. Our guide to setting up SQS queues and dead-letter queues walks through the console steps.
Step 1: Create the queue and dead-letter queue
Create the DLQ first, then the main queue with a redrive policy pointing at it. AWS recommends a maxReceiveCount of at least 5 when Lambda is the consumer, so Lambda has a few chances to retry before a message moves to the DLQ.
aws sqs create-queue --queue-name tasks-dlq
DLQ_ARN=$(aws sqs get-queue-attributes \
--queue-url "$(aws sqs get-queue-url --queue-name tasks-dlq --query QueueUrl --output text)" \
--attribute-names QueueArn --query Attributes.QueueArn --output text)
aws sqs create-queue --queue-name tasks \
--attributes '{
"VisibilityTimeout": "180",
"ReceiveMessageWaitTimeSeconds": "20",
"RedrivePolicy": "{\"deadLetterTargetArn\":\"'"$DLQ_ARN"'\",\"maxReceiveCount\":\"5\"}"
}'
The 180-second visibility timeout here assumes a Lambda function timeout of 30 seconds (six times 30). Adjust both together.
Pattern A: SQS with AWS Lambda
Step 2: Give the function permission to read the queue
Attach the AWS managed policy AWSLambdaSQSQueueExecutionRole to the function's execution role. It grants the receive, delete and attribute permissions Lambda needs. If the queue uses a customer managed KMS key, also allow kms:Decrypt.
Step 3: Create the event source mapping
aws lambda create-event-source-mapping \
--function-name process-task \
--event-source-arn arn:aws:sqs:ap-south-1:123456789012:tasks \
--batch-size 10 \
--function-response-types ReportBatchItemFailures \
--scaling-config MaximumConcurrency=20
The queue and the function must be in the same Region, though they can be in different accounts. Lambda now polls the queue for you; you do not write any polling code.
Step 4: Write a handler that reports partial failures
By default, if a function throws an error while processing a batch, every message in the batch returns to the queue, including the ones that succeeded. With ReportBatchItemFailures turned on, the function returns the IDs of only the failed messages:
import json
def handler(event, context):
failures = []
for record in event["Records"]:
try:
task = json.loads(record["body"])
process(task) # must be idempotent
except Exception:
failures.append({"itemIdentifier": record["messageId"]})
return {"batchItemFailures": failures}
Successful messages are deleted by Lambda; failed ones become visible again after the visibility timeout and are retried until they reach the DLQ.
How Lambda scales with SQS
For standard queues, Lambda starts with five concurrent batches. If messages keep arriving, it adds up to 300 concurrent invocations per minute, up to a maximum of 1,250 concurrent invocations. The MaximumConcurrency setting on the mapping caps how many invocations that one queue can drive, which protects downstream systems like databases. AWS also offers a provisioned mode with dedicated event pollers for steady high-throughput workloads; it cannot be combined with maximum concurrency.
If you set reserved concurrency on the function, AWS suggests at least five, to reduce throttling. Throttled batches return to the queue, which is one reason the six-times visibility rule exists.
Lambda limits to keep in mind
A Lambda function can run for at most 15 minutes, and the total batch payload must fit within the 6 MB synchronous invocation limit. SQS messages themselves have a size limit too. If tasks run longer than a few minutes or need large inputs, pass a pointer such as an S3 key in the message instead of the data. See Lambda timeout and payload limits for detail.
Pattern B: SQS with EC2 workers
Step 2: Write a long-polling worker
On EC2 you own the polling loop. A minimal Python worker using boto3 looks like this:
import boto3, json
sqs = boto3.client("sqs", region_name="ap-south-1")
QUEUE_URL = "https://sqs.ap-south-1.amazonaws.com/123456789012/tasks"
while True:
resp = sqs.receive_message(
QueueUrl=QUEUE_URL,
MaxNumberOfMessages=10,
WaitTimeSeconds=20,
)
for msg in resp.get("Messages", []):
try:
process(json.loads(msg["Body"])) # must be idempotent
sqs.delete_message(QueueUrl=QUEUE_URL,
ReceiptHandle=msg["ReceiptHandle"])
except Exception:
pass # message reappears after the visibility timeout
Give the instance an IAM role that allows sqs:ReceiveMessage, sqs:DeleteMessage, sqs:ChangeMessageVisibility and sqs:GetQueueAttributes on this queue only. Never put access keys on the instance. Run the worker as a systemd service so it restarts if it crashes.
Step 3: Handle long tasks with a visibility heartbeat
If a task can take longer than the queue's visibility timeout, the worker should periodically call change_message_visibility to extend it while work continues. AWS suggests this heartbeat approach and notes that extensions cannot go beyond 12 hours from first receipt. For work longer than that, split it into steps or use AWS Step Functions.
Step 4: Scale on backlog per instance
Scaling on raw queue length ignores how many workers you already have. AWS recommends a target tracking policy on backlog per instance: the ApproximateNumberOfMessages queue attribute divided by the number of InService instances. The target value is your acceptable backlog per instance, calculated as acceptable latency divided by average processing time per message. For example, with 0.1 seconds per message and 10 seconds acceptable latency, the target is 100 messages per instance.
AWS now recommends computing this with CloudWatch metric math in the target tracking policy rather than publishing a custom metric yourself, which saves cost and code.
Step 5: Protect work during scale-in
When an Auto Scaling group terminates an instance, any message it was processing becomes visible again after the timeout and another worker repeats the task. For long tasks, AWS describes using instance scale-in protection: the worker turns protection on while it processes a message and off when it finishes, so the group only terminates idle workers. Also handle the SIGTERM signal to finish or release the current message cleanly.
Worked example: an image thumbnail pipeline
Consider a site where users upload photos. The upload API stores the original in an S3 bucket and sends a small JSON message such as {"bucket": "uploads", "key": "user42/photo.jpg"} to the tasks queue. It then returns success to the user straight away.
With the Lambda pattern, the event source mapping delivers batches of these messages to a function that downloads each image, creates thumbnails and writes them to a second bucket. A maximum concurrency of 20 keeps the function from overwhelming the database where it records the thumbnail paths. If a corrupt image causes an error, only that message is reported as a failure; after five failed receives it moves to the DLQ, an alarm fires, and an engineer inspects the file.
Now suppose the team adds video transcoding that takes 30 minutes per file. That exceeds Lambda's 15-minute limit, so a second queue feeds EC2 workers on compute-optimised instances. Each worker extends visibility every few minutes while it transcodes, turns on scale-in protection during a job, and deletes the message when the output is written. The Auto Scaling group tracks backlog per instance, so a burst of uploads adds workers and a quiet night removes them.
The two consumers share the same idempotency rule: before processing, check whether the output object already exists, and skip the work if it does. That one check makes duplicate deliveries harmless in both paths.
Testing the integration before production
Send test messages with aws sqs send-message, including a deliberately malformed one, and confirm that good messages are processed and the bad one ends up in the DLQ after the expected number of receives. Stop the worker or throttle the function to zero concurrency, let a backlog build, then restore it and watch scaling and the age-of-oldest-message metric recover. Testing failure paths in staging is far cheaper than discovering them during a real traffic spike.
Lambda or EC2: how to choose
| Factor | Lambda consumer | EC2 worker |
|---|---|---|
| Polling code | Managed by Lambda | You write and run it |
| Max task duration | 15 minutes | Up to 12 hours visibility, longer with redesign |
| Scaling | Automatic, capped by maximum concurrency | Auto Scaling on backlog per instance |
| Idle cost | None for compute | Running instances cost money |
| Partial failures | ReportBatchItemFailures | Delete only successful messages |
| Special hardware or software | Limited | Any instance type, GPUs, custom OS |
| Best fit | Short, bursty tasks | Long, heavy or steady workloads |
Containers on ECS or EKS sit between the two. They run the same polling worker as EC2 and can scale on the same backlog metric, often with less instance management.
Making consumers idempotent
Standard queues can deliver a message more than once, and retries after timeouts or throttling add more duplicates. Design every task so that running it twice has the same effect as running it once. Common techniques: use a unique task ID and record completed IDs in a database table with a conditional write; make writes "upsert" rather than "insert"; or check whether the output object already exists before generating it. FIFO queues reduce duplicates within their deduplication window, but idempotency is still the safer default.
Monitoring the integration
Watch a few CloudWatch metrics. On the queue, ApproximateNumberOfMessagesVisible shows backlog and ApproximateAgeOfOldestMessage shows whether processing is falling behind; alarm on the age, because it reflects user impact directly. On the DLQ, alarm whenever the visible message count is above zero. For Lambda, watch Errors, Throttles and duration. For EC2, watch instance count against backlog. Our guide on monitoring EC2, RDS and Lambda with CloudWatch covers dashboards and alarms.
When messages land in the DLQ, investigate the cause, fix it, and use the SQS redrive feature to move them back to the source queue.
Common mistakes
Setting the visibility timeout shorter than the processing time is the most frequent one; messages reappear while still being processed and run twice. Forgetting to delete messages on EC2 has the same effect. Letting one bad message fail a whole Lambda batch, because partial batch responses are off, wastes work and can push good messages into the DLQ. Scaling Lambda without a concurrency cap can overload a database that cannot handle hundreds of connections. Each of these has a direct fix covered above.
To build and practise these patterns in a guided lab, our AWS Solutions Architect Associate training covers SQS, Lambda, EC2 Auto Scaling and decoupled designs, in the Kharadi, Pune classroom or live online.
Frequently asked questions
How does Lambda read messages from SQS?
Through an event source mapping. Lambda polls the queue, sends batches to your function, and deletes messages that were processed successfully.
What visibility timeout should I set for a Lambda consumer?
At least six times the function timeout, plus any batching window, as AWS recommends. The function timeout must not exceed the queue's visibility timeout.
What is the maximum batch size for SQS and Lambda?
Up to 10,000 records for standard queues and 10 for FIFO queues. Batch sizes above 10 require a batching window of at least one second.
What does ReportBatchItemFailures do?
It lets the function return the IDs of failed messages so only those go back to the queue, instead of retrying the whole batch.
How should EC2 workers scale with SQS?
Use target tracking on backlog per instance, calculated from ApproximateNumberOfMessages divided by InService instances, ideally with CloudWatch metric math.
What is the maximum long polling wait time in SQS?
20 seconds. Any WaitTimeSeconds value above zero turns on long polling.
Can SQS deliver the same message twice?
Yes. Standard queues are at-least-once, and retries add duplicates, so consumers should be idempotent.
When should I choose EC2 over Lambda for SQS processing?
When tasks run longer than 15 minutes, need special hardware or software, or the workload is steady enough that always-on instances cost less.
References
What's Your Reaction?
Like
0
Dislike
0
Love
0
Funny
0
Angry
0
Sad
0
Wow
0