auto-create CloudWatch Alarms for APIs with Lambda

In a previous post we discussed how to auto-subscribe a CloudWatch Log Group to a Lambda function using CloudWatch Events. So that we don’t need a manual process to ensure all Lambda logs would go to our log aggregation service.

Whilst this is useful in its own right, it only scratches the surface of what we can do. CloudTrail and CloudWatch Events makes it easy to automate many day-to-day operational steps. With the help of Lambda of course ;-)

I work with API Gateway and Lambda heavily. Whenever you create a new API, or make changes, there are several things you need to do:

  • enable Detailed Metrics for the deployment stage
  • set up a dashboard in CloudWatch, showing request count, latencies and error counts
  • set up CloudWatch Alarms for p99 latencies and error counts

Because these are manual steps, they often get missed.

Have you ever forgotten to update the dashboard after adding a new endpoint to your API? And did you also remember to set up a p99 latency alarm on this new endpoint? How about alarms on the no. of 4XX or 5xx errors?

Most teams I have dealt with have some conventions around these, but without a way to enforce them. The result is that the convention is applied in patches and cannot be relied upon. I find this approach doesn’t scale with the size of the team.

It works when you’re a small team. Everyone has a shared understanding, and the necessary discipline to follow the convention. When the team gets bigger, you need automation to help enforce these conventions.

Fortunately, we can automate away these manual steps using the same pattern. In the Monitoring unit of my course Production-Ready Serverless, I demonstrated how you can do this in 3 simple steps:

  1. CloudTrail captures the CreateDeployment request to API Gateway.
  2. CloudWatch Events pattern against this captured request.
  3. Lambda function to a) enable detailed metrics, and b) create alarms for each endpoint

If you use the Serverless framework, then you might have a function that looks like this:

Couple of things to note from the code above:

  • I’m using the serverless-iam-roles-per-function plugin to give the function a tailored IAM role
  • The function needs the apigateway:PATCH permission to enable detailed metrics
  • The function needs the apigateway:GET permission to get the API name and REST endpoints
  • The function needs the cloudwatch:PutMetricAlarm permission to create the alarms
  • The environment variables specify SNS topics for the CloudWatch Alarms

The captured event looks like this:

We can find the restApiId and stageName inside the detail.requestParameters attribute. That’s all we need to figure out what endpoints are there, and so what alarms we need to create.

Inside the handler function, which you can find here, we perform a few steps:

  1. enable detailed metrics with an updateStage call to API Gateway
  2. get the list of REST endpoints with a getResources call to API Gateway
  3. get the REST API name with a getRestApi call to API Gateway
  4. for each of the REST endpoints, create a p99 latency alarm in the AWS/ApiGateway namespace

Now, every time I create a new API, I will have CloudWatch Alarms to alert me when the 99 percentile latency for an endpoint goes over 1 second, for 5 minutes in a row. All this, with just a few lines of code :-)

You can take this further, and have other Lambda functions to:
  • create CloudWatch Alarms for 5xx errors for each endpoint
  • create CloudWatch Dashboard for the API

So there you have it, a useful pattern for automating away manual ops tasks!

And before you even have to ask, yes I’m aware of this serverless plugin by the ACloudGuru folks. It looks neat, but it’s ultimately still something the developer has to remember to do. That requires discipline. My experience tells me that you cannot rely on discipline, ever. Which is why, I prefer to have a platform in place that will generate these alarms automatically.

Enjoy what you’re reading? Subscribe to my newsletter and get more content on AWS and serverless technologies delivered straight to your inbox.

Yan Cui

I’m an AWS Serverless Hero and the author of Production-Ready Serverless. I have run production workload at scale in AWS for nearly 10 years and I have been an architect or principal engineer with a variety of industries ranging from banking, e-commerce, sports streaming to mobile gaming. I currently work as an independent consultant focused on AWS and serverless.

You can contact me via Email, Twitter and LinkedIn.

Hire me.

Check out my new course, Complete Guide to AWS Step Functions.

In this course, we’ll cover everything you need to know to use AWS Step Functions service effectively. Including basic concepts, HTTP and event triggers, activities, design patterns and best practices.

Get Your Copy

Come learn about operational BEST PRACTICES for AWS Lambda: CI/CD, testing & debugging functions locally, logging, monitoring, distributed tracing, canary deployments, config management, authentication & authorization, VPC, security, error handling, and more.

You can also get 40% off the face price with the code ytcui.

Get Your Copy