How to Create CloudWatch Alarms in AWS CDK

Introduction CloudWatch Alarms are an essential tool for monitoring AWS services and receiving notifications when specific metrics reach certain values. In this article, we will explore how to create CloudWatch Alarms in AWS CDK (Cloud...

Introduction

CloudWatch Alarms are an essential tool for monitoring AWS services and receiving notifications when specific metrics reach certain values. In this article, we will explore how to create CloudWatch Alarms in AWS CDK (Cloud Development Kit) and leverage its powerful features to effectively monitor our resources.

CloudWatch Alarms Overview

AWS services emit metrics that can be used to set up alarms via CloudWatch. These metrics can include information such as ConcurrentExecutions, Duration, Errors for a Lambda function, CPUUtilization, DiskReadOps, DiskWriteOps for EC2 instances, and ConsumedReadCapacityUnits, ConsumedWriteCapacityUnits, ThrottledRequests for DynamoDB.

Creating an alarm in CloudWatch allows us to receive notifications when specific metrics reach predetermined values over a specified period of time. For example, we can create an alarm that notifies us if the sum of errors of a Lambda function is greater than or equal to 5 for a period of 3 minutes, or if the average duration time of a Lambda function's invocation exceeds 2 seconds over a period of 3 minutes.

Creating Alarms in AWS CDK

In order to create CloudWatch Alarms in AWS CDK, we need to define the metrics we want to track and then create the corresponding alarms. Let's walk through the steps of creating alarms using a small CDK application as an example.

We will start by defining a Lambda function and the metrics we want to track:

// Define the Lambda function and metrics
const lambdaFunction = new lambda.Function(this, 'MyLambdaFunction', {
  // Lambda function configuration
});

const errorsMetric = lambdaFunction.metricErrors();
const invocationsMetric = lambdaFunction.metricInvocations();

Next, we can add the alarms that will be triggered when our metrics reach a specified threshold:

// Create CloudWatch alarms
const errorsAlarm = new cloudwatch.Alarm(this, 'ErrorsAlarm', {
  metric: errorsMetric,
  comparisonOperator: cloudwatch.ComparisonOperator.GREATER_THAN_OR_EQUAL_TO_THRESHOLD,
  threshold: 5,
  evaluationPeriods: 3,
});

const invocationsAlarm = new cloudwatch.Alarm(this, 'InvocationsAlarm', {
  metric: invocationsMetric,
  comparisonOperator: cloudwatch.ComparisonOperator.GREATER_THAN_OR_EQUAL_TO_THRESHOLD,
  threshold: 1,
  evaluationPeriods: 3,
});

Once we have defined our resources and alarms, we can create the stack and review the results. In the CloudFormation console, we can see that the resources were created successfully. Similarly, in the CloudWatch console, we can observe that the alarms are in the Insufficient data state.

Stack created

CloudWatch alarms insufficient data

Discussion

In order to create Alarms in AWS CDK, we first define the metrics we want to track and then create the CloudWatch alarms that compare a threshold to the emitted statistics over a period of time. While the higher-level constructs in CDK provide helper methods for many metrics, we can also manually create metrics using the Metric class.

For example, if a helper method is not available for the metric we need, we can define it using the Metric class:

const customMetric = new cloudwatch.Metric({
  namespace: 'AWS/Lambda',
  metricName: 'ConcurrentExecutions',
  period: cdk.Duration.minutes(5),
  statistic: 'Maximum',
  dimensions: {
    FunctionName: 'myLambdaFunction',
  },
});

Conclusion

CloudWatch Alarms are a crucial tool for monitoring AWS services and receiving notifications based on defined thresholds. AWS CDK simplifies the process of creating and managing alarms by allowing us to define metrics and alarms as part of our infrastructure-as-code.

Most of the time, we can take advantage of the pre-built helper methods provided by CDK to create metrics. However, in cases where specific metrics are not supported, we can manually create them using the Metric class. The flexibility and power of AWS CDK enable us to build robust monitoring solutions tailored to our specific requirements.

Remember, proficient use of CloudWatch Alarms contributes to maintaining the performance, security, and availability of our applications and infrastructure.

Clean up

To remove the provisioned resources, simply run the cdk destroy command.

Additional Resources

For more information on related topics, check out the following tutorials:

1