How to build CloudWatch monitoring alerts with AWS CDK
A critical component to any platform architecture is to implement the appropriate monitoring and alerting when things start to degrade or act as we don’t expect. It’s incredibly critical because we cannot assume that everything will always perform without any issues.
Therefore, implementing monitoring and alerting is paramount to the success of your platform. So let’s dive in and create a quick CloudWatch monitor, alert and subsequent action as a result of something hitting our defined threshold.
✍️ What?
At a glance, we’re quickly going to provision a few resources to facilitate setting up the alarm and monitoring:
- CloudWatch alarm
- CloudWatch alarm action
- SNS Topic
We’re going to use an existing Lambda function that exists in the AWS account for testing purposes, but CloudWatch alarms can be created on virtually any metric that gets reported into CloudWatch itself - including the various aggregate metrics that it can calculate too.
🤖 SNS Topic
Firstly, we need to create a SNS topic that can act as our alerting topic that we can subscribe to. SNS is a push-based, fully managed pub/sub service that can facilitate multiple types of publishers and subscribers. It natively has hooks into other AWS services for both the publishing and subscribing - which we’ll see when setting the alarm up down below.
Let’s create our SNS topic that will act as our alerting facilitator:
const stack = cdk.Stack.of(this);
const snsTopic = new sns.Topic(
this,
`cdk-patterns-${stack.stackName}-sns-alerting-topic`,
{
displayName: `cdk-patterns-${stack.stackName}-sns-alerting-topic`,
topicName: `cdk-patterns-${stack.stackName}-sns-alerting-topic`,
}
);
⚡️ Function to monitor
For the purposes of the demo, we’re going to reference and monitor an existing Lambda function that already exists in the account. To do this via CDK, we can simply reference it via the ARN:
import * as lambda from "aws-cdk-lib/aws-lambda";
const stack = cdk.Stack.of(this);
const lambdaFunctionToMonitor = lambda.Function.fromFunctionArn(
this,
`cdk-patterns-${stack.stackName}-lambda-function`,
"<< Fn ARN >>"
);
💡 Create the CloudWatch monitor
Finally, we need to provision the CloudWatch alarm, the metrics for it to track and the subsequent action to take whenever those specified thresholds are breached.
Thankfully, CDK makes this incredibly easy to provision using the L2 constructs that it provides for CloudWatch alarms:
import * as cloudwatch from "aws-cdk-lib/aws-cloudwatch";
import * as cw_actions from "aws-cdk-lib/aws-cloudwatch-actions";
const stack = cdk.Stack.of(this);
const cloudWatchAlarm = new cloudwatch.Alarm(
this,
`cdk-patterns-${stack.stackName}-lambda-cloudwatch-alarm`,
{
alarmName: `cdk-patterns-${stack.stackName}-lambda-cloudwatch-alarm`,
alarmDescription: "CloudWatch alarm to track how many invocations of the lambda function fails",
metric: lambdaFunctionToMonitor.metricErrors(),
threshold: 100,
evaluationPeriods: 2,
}
);
cloudWatchAlarm.addAlarmAction(new cw_actions.SnsAction(snsTopic));
The few things that are taking place here are as follows:
- Creation of the CloudWatch alarm with the lambda function invocation errors defined as the metric to track. We’ve also configured the threshold and evaluation period for triggering the alarm.
- We have then added a publish event to the SNS topic we previously created and attached it to the newly provisioned alarm. This will sent a notification to each of the subscribers to the specified SNS topic.
✅ Subscription testing
If you want to test the set up, you can configure a subscription to the SNS topic (I usually opt for just email for initial testing) and then manually trigger a test event for the newly created CloudWatch alarm.
This will allow you to test the configuration end-to-end and have confidence that whenever something goes wrong, you’ll get notified as soon as things may start to go wrong - and typically, in these sort of circumstances, the earlier you are notified, the better equipped you can be to react!
The following CDK will add an email subscription to your SNS topic:
import * as sns_subscriptions from "aws-cdk-lib/aws-sns-subscriptions";
snsTopic.addSubscription(
new sns_subscriptions.EmailSubscription("<mail@mail.com>")
);
Once you deploy this using cdk deploy
, you’ll need to confirm the subscription to the SNS topic in your mailbox before testing the CloudWatch alarm manual event trigger.
Once you have done this, jump into CloudWatch and trigger the alarm! You should have a nice alerting email now.
Conclusion
- With CloudWatch, it is super easy to configure alarms to monitor certain metrics, for a plethora of AWS services (pretty much anything that can push its metrics into CloudWatch!).
- We can then subsequently provision actions that we want to perform if said alarm gets triggered and the threshold is breached.
- In our case and example above, we created a new SNS topic that our CloudWatch alarm action pushed a notification to whenever the alarm was triggered.
- Monitoring and alerting is super critical to the health and success of your platform, the earlier you can get notified of things starting to go wrong, the better!
- CDK makes it incredibly easy to provision these sorts of alarms and metrics, especially thanks to their L2 construct for CloudWatch alarms.