Build a Resilient Message Processor with Amazon SQS, AWS Lambda and a Dead-Letter Queue
Learn how to decouple your workloads with Amazon SQS, process messages with AWS Lambda, and automatically isolate failing messages in a dead-letter queue using partial batch responses.
## Introduction
When one part of your application calls another directly, a failure in the second part can break the first. Amazon Simple Queue Service (SQS) solves this by putting a queue between them. In this tutorial, you will build a small order processor where:
- Messages are sent to an **SQS queue**
- An **AWS Lambda** function processes them in batches
- Messages that keep failing are moved to a **dead-letter queue (DLQ)** so you can inspect them later
## Architecture
Producer → SQS Queue → Lambda Function → (on repeated failure) → Dead-Letter Queue
## Prerequisites
- An AWS account
- Basic familiarity with the AWS Console
- Region used in this tutorial: your preferred region (for example, `ap-south-1`)
## Step 1: Create the dead-letter queue
1. Open the **Amazon SQS** console and choose **Create queue**.
2. Select **Standard** as the type.
3. Name it `orders-dlq`.
4. Leave the other settings as default and choose **Create queue**.
## Step 2: Create the main queue
1. Choose **Create queue** again, type **Standard**, and name it `orders-queue`.
2. Set **Visibility timeout** to `60 seconds`. As a rule of thumb, it should be at least six times your Lambda function's timeout.
3. Under **Dead-letter queue**, enable it and select `orders-dlq`.
4. Set **Maximum receives** to `3`. After three failed attempts, a message moves to the DLQ.
5. Choose **Create queue**.
## Step 3: Create the Lambda function
1. Open the **AWS Lambda** console and choose **Create function**.
2. Select **Author from scratch**, name it `process-orders`, and choose the latest **Python** runtime.
3. Under permissions, create a new role with basic Lambda permissions. We will add SQS access next.
4. Choose **Create function**.
5. Under **Configuration > General configuration**, set the timeout to `10 seconds`.
Paste this code into the function and choose **Deploy**:
```python
import json
def lambda_handler(event, context):
failures = []
for record in event\["Records"]: try: body = json.loads(record\["body"])
if "orderId" not in body: raise ValueError("Missing orderId")
print(f"Processed order \{body\['orderId']}")
except Exception as e: print(f"Failed message \{record\['messageId']}: \{e}") failures.append(\{"itemIdentifier": record\["messageId"]})
return \{"batchItemFailures": failures}```
The function returns only the failed message IDs. This is called a **partial batch response**. Without it, one bad message would cause the entire batch to be retried, including messages that already succeeded.
## Step 4: Connect the queue to Lambda
1. In your function, choose **Add trigger** and select **SQS**.
2. Choose `orders-queue`.
3. Set **Batch size** to `5`.
4. Under **Additional settings**, enable **Report batch item failures**.
5. Choose **Add**.
If the console warns about permissions, open the function's execution role in IAM and attach the AWS managed policy `AWSLambdaSQSQueueExecutionRole`.
## Step 5: Test it
In the SQS console, open `orders-queue`, choose **Send and receive messages**, and send two messages.
**A valid message:**
```json
{"orderId": "1001", "item": "keyboard"}
```
**An invalid message:**
```json
{"item": "mouse"}
```
Now open **CloudWatch Logs** for your function. You should see the valid order processed successfully and the invalid one failing repeatedly.
After the third failed attempt, check `orders-dlq` and choose **Poll for messages**. Your invalid message will be waiting there for inspection.
## Why this pattern is useful
- **Decoupling:** the producer doesn't care whether the consumer is slow or down.
- **Resilience:** failed messages are retried automatically.
- **Isolation:** poison messages end up in the DLQ instead of blocking everything.
- **Scalability:** Lambda scales with queue depth.
## Best practices
- Set the DLQ retention period longer than the main queue's.
- Create a CloudWatch alarm on `ApproximateNumberOfMessagesVisible` for the DLQ.
- Make your function **idempotent**, because standard queues deliver messages at least once.
- Keep the visibility timeout at least six times the function timeout.
## Clean up
To avoid unnecessary resources, delete the Lambda function, both SQS queues, and the CloudWatch log group.
## Conclusion
You built a decoupled, fault-tolerant message processor using only managed services. From here, you could add an SNS topic to fan messages out to several queues, or write a second Lambda that reprocesses messages from the DLQ.
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article