auto-create CloudWatch Alarms for APIs with Lambda

You can become a serverless blackbelt. Enrol to my 4-week online workshop Production-Ready Serverless and gain hands-on experience building something from scratch using serverless technologies. At the end of the workshop, you should have a broader view of the challenges you will face as your serverless architecture matures and expands. You should also have a firm grasp on when serverless is a good fit for your system as well as common pitfalls you need to avoid. Sign up now and get 15% discount with the code yanprs15!

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.
Liked this article? Support me on Patreon and get direct help from me via a private Slack channel or 1-2-1 mentoring.
Subscribe to my weekly newsletter

Hi, I’m Yan. I’m an AWS Serverless Hero and I help companies go faster for less by adopting serverless technologies successfully.

Are you struggling with serverless or need guidance on best practices? Do you want someone to review your architecture and help you avoid costly mistakes down the line? Whatever the case, I’m here to help.

Hire me.

Skill up your serverless game with this hands-on workshop.

My 4-week Production-Ready Serverless online workshop is back!

This course takes you through building a production-ready serverless web application from testing, deployment, security, all the way through to observability. The motivation for this course is to give you hands-on experience building something with serverless technologies while giving you a broader view of the challenges you will face as the architecture matures and expands.

We will start at the basics and give you a firm introduction to Lambda and all the relevant concepts and service features (including the latest announcements in 2020). And then gradually ramping up and cover a wide array of topics such as API security, testing strategies, CI/CD, secret management, and operational best practices for monitoring and troubleshooting.

If you enrol now you can also get 15% OFF with the promo code “yanprs15”.

Enrol now and SAVE 15%.

Check out my new podcast Real-World Serverless where I talk with engineers who are building amazing things with serverless technologies and discuss the real-world use cases and challenges they face. If you’re interested in what people are actually doing with serverless and what it’s really like to be working with serverless day-to-day, then this is the podcast for you.

Check out my new course, Learn you some Lambda best practice for great good! In this course, you will learn best practices for working with AWS Lambda in terms of performance, cost, security, scalability, resilience and observability. We will also cover latest features from re:Invent 2019 such as Provisioned Concurrency and Lambda Destinations. Enrol now and start learning!

Check out my video 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. There is something for everyone from beginners to more advanced users looking for design patterns and best practices. Enrol now and start learning!