How to Attach a CloudWatch Alarm to a Lambda Function

How to get an email when a Lambda function starts failing. A CloudWatch alarm on the Errors metric wired to an SNS topic, built once by hand in the console and once as infrastructure-as-code in serverless.yml.

Originally on DEV.toFebruary 13, 2023
Read the full post on DEV.to

A Lambda that fails silently is worse than one that fails loudly. This post covers the smallest useful piece of Lambda monitoring: an alarm that emails you when the function throws. It's the same job done two ways, clicked together in the CloudWatch console and declared as CloudFormation resources inside serverless.yml, so you can match it to how you already deploy.

The moving parts are a CloudWatch alarm on the AWS/Lambda Errors metric and an SNS topic with an email subscription for delivery. The example alarm fires when the summed error count is at or above 3 over a single 5-minute period (Period: 300, EvaluationPeriods: 1, ComparisonOperator: GreaterThanOrEqualToThreshold), with missing data treated as breaching. To actually watch it trip, the article ships a throwaway Lambda that fails about half the time on a one-minute schedule.

Key takeaways

  • Alarm on Errors with Sum, not Average: you care about failure count in the window, so pick a threshold and period that tolerate normal noise
  • The alarm doesn't notify on its own: needs an SNS topic as alarm action plus a confirmed email subscription (topic, alarm, subscription in IaC)
  • Scope the alarm dimension to a specific FunctionName; treat missing data as breaching for a function on a schedule

Who this is for

Developers running Lambdas in production who want a basic health signal without standing up a full observability stack. It assumes you can create a Lambda and know your way around the AWS console. No prior CloudWatch alarm experience needed. The Serverless Framework section is a straight drop-in if you already use it.

The full walkthrough, with the console screenshots and the complete serverless.yml resources block, is on DEV.to.

Read the full post on DEV.to