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:

  handler: functions/create-alarms.handler  
    - cloudwatchEvent:
            - aws.apigateway
            - AWS API Call via CloudTrail
              - CreateDeployment
    alarm_actions: arn:aws:sns:#{AWS::Region}:#{AWS::AccountId}:NotifyMe
    ok_actions: arn:aws:sns:#{AWS::Region}:#{AWS::AccountId}:NotifyMe
    - Effect: Allow
      Action: apigateway:GET
        - arn:aws:apigateway:#{AWS::Region}::/restapis/*
        - arn:aws:apigateway:#{AWS::Region}::/restapis/*/stages/${self:custom.stage}
    - Effect: Allow
      Action: apigateway:PATCH
      Resource: arn:aws:apigateway:#{AWS::Region}::/restapis/*/stages/${self:custom.stage}
    - Effect: Allow
      Action: cloudwatch:PutMetricAlarm
      Resource: "*"

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:

  "version": "0",
  "id": "dee9a69c-8166-1ad7-41d4-1dad201e29f6",
  "detail-type": "AWS API Call via CloudTrail",
  "source": "aws.apigateway",
  "account": "374852340821",
  "time": "2018-04-09T00:17:47Z",
  "region": "us-east-1",
  "resources": [],
  "detail": {
      "eventVersion": "1.05",
      "userIdentity": {
          "type": "IAMUser",
          "principalId": "AIDAIRMUZZEGPO27IPFYW",
          "arn": "arn:aws:iam::374852340821:user/yan.cui",
          "accountId": "374852340821",
          "accessKeyId": "ASIAJNZDKN26DXPZFYQE",
          "userName": "yan.cui",
          "sessionContext": {
              "attributes": {
                  "mfaAuthenticated": "false",
                  "creationDate": "2018-04-09T00:17:30Z"
          "invokedBy": ""
      "eventTime": "2018-04-09T00:17:47Z",
      "eventSource": "",
      "eventName": "CreateDeployment",
      "awsRegion": "us-east-1",
      "sourceIPAddress": "",
      "userAgent": "",
      "requestParameters": {
          "restApiId": "8kbasri6v7",
          "createDeploymentInput": {
              "stageName": "dev"
          "template": false
      "responseElements": {
          "id": "cj2y0f",
          "createdDate": "Apr 9, 2018 12:17:47 AM",
          "deploymentUpdate": {
              "restApiId": "8kbasri6v7",
              "deploymentId": "cj2y0f",
              "template": false
          "deploymentStages": {
              "deploymentId": "cj2y0f",
              "restApiId": "8kbasri6v7",
              "template": false,
              "templateSkipList": [
          "deploymentDelete": {
              "deploymentId": "cj2y0f",
              "restApiId": "8kbasri6v7",
              "template": false
          "self": {
              "deploymentId": "cj2y0f",
              "restApiId": "8kbasri6v7",
              "template": false
      "requestID": "6e25bd56-3b8b-11e8-a351-e5e3d3161fe7",
      "eventID": "a150d941-7a54-4572-97b2-0614a81fd25b",
      "readOnly": false,
      "eventType": "AwsApiCall"

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.