Trigger Lambda Function From Amazon SQS - (Let's Build šļø Series)
awedis
Posted on October 9, 2024
Let's build a simple architecture where a Lambda function is triggered from Amazon SQS.
The main parts of this article:
1- Architecture Overview (Terraform)
2- About AWS Services (Info)
3- Technical Part (Code)
4- Result
5- Conclusion
Architecture Overview (Terraform)
- aws_sqs_queue:
resource "aws_sqs_queue" "my_queue" {
name = "my_sqs_queue"
redrive_policy = jsonencode({
deadLetterTargetArn = aws_sqs_queue.dlq_queue.arn
maxReceiveCount = 10
})
}
- aws_lambda_event_source_mapping
resource "aws_lambda_event_source_mapping" "sqs_trigger" {
event_source_arn = aws_sqs_queue.my_queue.arn
function_name = aws_lambda_function.my_lambda.arn
enabled = true
batch_size = 5
}
The whole project is available on my Github here
About AWS Services (Info)
1- AWS Lambda: To trigger our function and execute the code.
2- Amazon SQS: Amazon Simple Queue Service (Amazon SQS) offers a secure, durable, and available hosted queue to integrate and decouple distributed software systems and components.
Technical Part (Code)
exports.handler = async (event) => {
try {
event.Records.forEach(record => {
const messageBody = record.body;
console.log("Received message:", messageBody);
});
return {
statusCode: 200,
body: JSON.stringify({ message: 'Message processed successfully!' })
};
} catch (error) {
console.error("Error processing SQS message:", error);
return {
statusCode: 500,
body: JSON.stringify({ message: 'Error processing message' })
};
}
};
Result
Once we apply we can see our Lambda function has been created, and notice that the SQS service has been connected as a trigger.
Now let us test and send a message from the queue and see if the Lambda will be triggered.
To check if my Lambda function was executed successfully, I can check the logs through CloudWatch.
Conclusion
In many cases, you need to build distributed systems with queues, especially when you are processing big traffic and you don't want to lose any data.
Thank you for reading my article.
Posted on October 9, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
February 20, 2024