DEV Community

Cover image for Trigger Lambda Function From Amazon SQS - (Let's Build 🏗️ Series)
awedis for AWS Heroes

Posted on

Trigger Lambda Function From Amazon SQS - (Let's Build 🏗️ Series)

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
  })
}
Enter fullscreen mode Exit fullscreen mode
  • 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
}
Enter fullscreen mode Exit fullscreen mode

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' })
    };
  }
};
Enter fullscreen mode Exit fullscreen mode

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.

Image description

Now let us test and send a message from the queue and see if the Lambda will be triggered.

Image description

To check if my Lambda function was executed successfully, I can check the logs through CloudWatch.

Image description

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.

👉 Follow me for more 👾
LinkedIn
X

Top comments (0)