AWS Lambda enables you to run code without managing a server. You simply plop in your code and it does the rest (no maintenance, scaling concerns, etc). The cost is only $0.20 per 1 million requests/month and the first million requests are free each month.
In the previous post, I setup an SNS topic. I’m extending this further so that a node.js function will be triggered in AWS Lambda each time my SNS topic is triggered. This Lambda function will feed metrics into AWS CloudWatch which will allow me to chart/monitor/set alarms against events or patterns with my SNS topic. A practical use case for this could be understanding event patterns or logging SNS messages (and their contents) sent to your customers.
Creating your Lambda Function
From the Lambda page of the AWS console, select “Create Function”. From here, we’ll author from scratch. Below are the inputs I’ve used for this example:
Name: SNSPingerToCloudWatch
Runtime: Node.js 8.10
Role: Choose and existing role
Existing role: lambda_basic_execution
On the page after selecting “Create Function”, we’ll click “SNS” from the “Add Triggers” section and then select our SNS topic in the “Configure Triggers” section. Then click “Add” and “Save”. Here’s a screenshot of the final state.
Next, click on your function name (SNSPingerToCloudWatch) in the flow chart and scroll to edit the function code.
The JS we’ll use:
exports.handler = async (event, context) => { const message = event.Records[0].Sns.Message; console.log('Pinger says:', message); return message; };
Under Basic Settings, I’ve set the timeout duration to 5 seconds (because that’s the timeout duration I have set in my SNS topic PHP script) You can add descriptions, throttles, etc but I’m leaving those at the defaults. Here’s a screenshot of my final config for this Lambda function.
Once complete, click “Save” again and then we’re ready to test. I manually fired my SNS topic and jumped over to the “Monitoring” tab of the console. It took a minute or so but I saw my event appear. From here, you can view the log details in CloudWatch, as well.