AWS Builder Center

Monitoring Serverless Applications with Amazon CloudWatch

Learn how to monitor AWS Lambda applications using Amazon CloudWatch metrics, structured logs, Logs Insights queries, and alarms. Build a practical monitoring workflow and configure Amazon SNS notifications to identify and troubleshoot serverless application failures.

From Deployment to Observability: Monitoring a Serverless Application with Amazon CloudWatch

Introduction

Building a serverless application on AWS simplifies infrastructure management, but it does not eliminate operational problems. A Lambda function can fail because of invalid input, a downstream service error, insufficient permissions, or a timeout. Without proper monitoring, identifying the root cause can become difficult.
Amazon CloudWatch provides the monitoring capabilities needed to understand application behavior, analyze logs, track performance, and receive alerts when something goes wrong.
In this tutorial, we will build a practical monitoring workflow for an AWS Lambda application using Amazon CloudWatch. We will implement structured logging in Node.js, examine Lambda metrics, query logs using CloudWatch Logs Insights, and configure an alarm to detect function errors.
By the end, you will have a foundation for monitoring and troubleshooting a serverless application in a more systematic way.

1. Understanding the Architecture

Our example uses a Node.js Lambda function that processes incoming requests. CloudWatch collects operational metrics and stores application logs, while CloudWatch alarms evaluate metrics against configured thresholds.
Architecture overview
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Incoming Request
|
v
AWS Lambda Function
|
+------+------+
| |
v v
Lambda Metrics Application Logs
| |
v v
CloudWatch CloudWatch Logs
| |
+------+------+
|
v
CloudWatch Alarm
|
v
Amazon SNS Email
(Optional Alerting)
The architecture separates three important responsibilities:
  • Metrics: Identify changes in errors, invocation volume, latency, and throttling.
  • Logs: Explain what happened during an individual invocation.
  • Alarms: Detect predefined conditions and initiate notifications.
AWS Lambda automatically publishes standard invocation and performance metrics to CloudWatch. It can also send application output to CloudWatch Logs when its execution role has the required permissions.

2. Create a Node.js Lambda Function

Start by creating a Lambda function in the AWS Management Console.
  1. Open the AWS Lambda console.
  2. Choose Create function.
  3. Select Author from scratch.
  4. Enter serverless-monitoring-demo as the function name.
  5. Choose a supported Node.js runtime.
  6. Create the function using an execution role that has the AWSLambdaBasicExecutionRole managed policy, or equivalent CloudWatch Logs permissions.
  7. Open the function's code editor.
Replace the default code with the following example.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
exports.handler = async (event) => {
const requestId = event?.requestId || "unknown";

console.info("Request received", {
requestId,
timestamp: new Date().toISOString()
});

try {
// Simulate an application operation.
const operation = event?.operation || "success";

if (operation === "fail") {
throw new Error("Simulated processing failure");
}

const result = {
statusCode: 200,
body: JSON.stringify({
message: "Request processed successfully",
requestId
})
};

console.info("Request processed successfully", {
requestId
});

return result;
} catch (error) {
console.error("Request processing failed", {
requestId,
errorMessage: error.message
});

throw error;
}
};
Deploy the function after saving the code.
This example supports two scenarios:
  • A successful invocation when the operation is success.
  • A failed invocation when the operation is fail.
The function deliberately throws an error in the second scenario. This allows us to observe how Lambda reports failures and how CloudWatch helps us investigate them.
The example is intended for monitoring demonstrations. A production application should validate incoming events, use appropriate error-handling strategies, and avoid logging sensitive information.

3. Generate Successful and Failed Invocations

Open the Lambda console's test interface and create a test event.
For a successful invocation, use:
1
2
3
4
{
"requestId": "request-001",
"operation": "success"
}
Run the test. The function should return a successful response and write informational logs.
Next, create a second test event:
1
2
3
4
{
"requestId": "request-002",
"operation": "fail"
}
Run this test. The function should throw an exception, and Lambda should report the invocation as an error.
These two scenarios give us a simple way to compare normal application behavior with a failure.
Important: This function is deliberately configured to fail for demonstration purposes. It does not represent an actual production incident.

4. Monitor Lambda Metrics in CloudWatch

Lambda automatically publishes standard metrics under the AWS/Lambda namespace. No custom metric instrumentation is required for the basic metrics in this tutorial.
Open the CloudWatch console and navigate to Metrics. Select the Lambda metrics namespace and locate the function's metrics.
Focus on the following metrics:
MetricWhat it tells you
InvocationsNumber of times the function was invoked
ErrorsNumber of invocations that resulted in function errors
DurationExecution time of the function
ThrottlesNumber of invocation requests rejected because of throttling
Use the Sum statistic for counting metrics such as Invocations, Errors, and Throttles. For Duration, examine the Average and Maximum statistics to understand typical and worst observed execution times.
For this example, the failed test should contribute to the Errors metric. Metric publication and visibility are not necessarily instantaneous, so allow time for the data to appear.

Why these metrics matter

Errors: A sudden increase can indicate application bugs, invalid inputs, or failures in downstream dependencies.
Duration: Increasing execution time can indicate inefficient code, network delays, or slow dependencies. Compare it with the function's configured timeout.
Throttles: Throttling can indicate concurrency limits or account-level capacity constraints.
Invocations: Invocation volume provides context for interpreting other metrics. Ten errors during ten requests indicate a different situation from ten errors during thousands of requests.
A useful monitoring setup evaluates these metrics together rather than treating each metric as an isolated signal.

5. Analyze Logs with CloudWatch Logs Insights

Metrics can tell you that a problem occurred, but logs help you understand why.
Lambda sends its logs to a log group that typically follows this naming convention:
1
/aws/lambda/serverless-monitoring-demo
To inspect the logs:
  1. Open the CloudWatch console.
  2. Navigate to Logs → Log groups.
  3. Open /aws/lambda/serverless-monitoring-demo.
  4. Select a log stream containing your test invocation.
  5. Locate the error message and associated request information.
For more efficient investigation, open CloudWatch Logs Insights and select the function's log group.
The following query searches for application messages containing the word failed:
1
2
3
4
fields @timestamp, @message
| filter @message like /failed/
| sort @timestamp desc
| limit 20
You can also search for the simulated exception:
1
2
3
4
fields @timestamp, @message
| filter @message like /Simulated processing failure/
| sort @timestamp desc
| limit 20
Run the queries over a time range that includes your test invocations.
These examples use the default plain-text logging configuration. If you configure JSON application logging, you can emit structured fields such as requestId, operation, and errorMessage, then query those fields directly.
For example, structured logs make it easier to filter failures by request identifier or group errors by type. They also make automated log analysis more reliable than searching unstructured messages.
Official documentation: Working with Lambda function logs .

6. Create a CloudWatch Alarm for Lambda Errors

Checking metrics manually is useful during development, but it is not a reliable operational strategy. A CloudWatch alarm can evaluate a metric continuously and transition between states when its configured conditions are met.
For this demonstration, we will create an alarm that enters the ALARM state when at least one Lambda error occurs during a one-minute evaluation period.

Configure the alarm

  1. Open CloudWatch and navigate to Alarms.
  2. Choose Create alarm.
  3. Select the AWS/Lambda namespace.
  4. Choose the Errors metric for serverless-monitoring-demo.
  5. Set the statistic to Sum.
  6. Set the period to one minute.
  7. Configure the threshold so the alarm triggers when the metric is greater than or equal to 1.
  8. Configure one evaluation period and one datapoint to alarm.
  9. Choose an appropriate alarm name, such as serverless-monitoring-demo-errors.
  10. Complete the alarm creation process.
The alarm will evaluate the metric data against the threshold. It can enter the ALARM state after CloudWatch receives a qualifying datapoint.
Note: CloudWatch alarms can take time to reflect a new invocation. Metrics are not guaranteed to appear immediately, and alarms may remain in INSUFFICIENT_DATA until enough information is available.

What should you test?

Invoke the function with the successful event and verify that no error is generated by that invocation.
Then invoke it with the failing event. After the corresponding error metric becomes available, check the alarm state.
The goal is to confirm that the alarm detects a real function error rather than simply assuming that creating an alarm makes monitoring operational.

7. Send Notifications with Amazon SNS

An alarm becomes more useful when it notifies someone who can investigate the problem.
Amazon Simple Notification Service (SNS) can deliver alarm notifications through supported subscription protocols, including email.
To configure email notifications:
  1. Open the Amazon SNS console.
  2. Create a standard topic, for example serverless-monitoring-alerts.
  3. Create an email subscription using an address you control.
  4. Confirm the subscription through the verification email.
  5. Return to your CloudWatch alarm.
  6. Edit its notification actions and select the SNS topic for the ALARM state.
  7. Save the configuration.
Trigger the test failure again and wait for the metric and alarm state to update. Verify that the notification arrives.
Keep in mind that an alarm notification is not the same as an alert for every individual failed invocation. The alarm sends notifications according to its state transitions and configured actions. For production systems, consider the alarm's evaluation settings, missing-data behavior, notification routing, and whether repeated failures require escalation.

8. Troubleshooting Common Monitoring Problems

Logs are missing

Check that the Lambda execution role has the necessary CloudWatch Logs permissions. The AWSLambdaBasicExecutionRole managed policy provides the standard permissions used to write logs.
Also verify that the function has actually been invoked, that you are looking in the correct AWS Region, and that you selected the correct log group.

The error alarm does not trigger

Verify that the failed invocation generated a Lambda error, that you selected the correct function and metric dimensions, and that the threshold and evaluation period are configured as intended.
Check the metric data and alarm history before changing the threshold.

The function is slow but does not report errors

Inspect the Duration metric and compare it with the configured timeout. Review the function's logs for slow operations and examine downstream dependencies.
A function can return successfully while still performing poorly. Error monitoring alone is not enough to identify latency problems.

The alarm triggers too often

A threshold that is too sensitive can create alert fatigue. Evaluate the normal workload, error rate, evaluation period, and impact of failures before choosing production thresholds.
For a high-volume service, an error count may be less useful than an error rate. You may need a CloudWatch metric-math alarm that compares errors with invocations, while handling periods with no invocations appropriately.

9. Production Monitoring Recommendations

The example above is deliberately small. A production monitoring strategy should account for more than a single error metric.
Consider these practices:
  • Use structured logging: Include request identifiers and useful contextual fields, but never log credentials, access tokens, or sensitive personal data.
  • Monitor latency: Use average and maximum duration metrics, and evaluate percentiles when the workload and metric support them.
  • Monitor throttling: Investigate concurrency settings, service quotas, and workload spikes.
  • Set appropriate retention: Configure CloudWatch Logs retention to meet operational, compliance, and cost requirements.
  • Control costs: Logs ingestion, retention, queries, dashboards, and alarms can incur charges. Check current AWS pricing for your expected workload.
  • Test alert delivery: An alarm that has never been tested is not a dependable notification mechanism.
  • Choose meaningful thresholds: Avoid alerting on every minor fluctuation without considering business impact.
  • Consider distributed tracing: For applications involving multiple services, AWS X-Ray can help connect execution paths and identify latency across service boundaries.

Conclusion

Monitoring is a core part of building reliable serverless applications on AWS. Amazon CloudWatch provides a practical combination of metrics, logs, alarms, and dashboards that helps developers understand application behavior and respond to failures.
In this tutorial, we created a Node.js Lambda function, generated successful and failed invocations, inspected CloudWatch metrics, queried logs using Logs Insights, and configured an error alarm with optional SNS notifications.
The key lesson is that effective monitoring connects three questions: What happened? Why did it happen? Who needs to know?
Starting with these fundamentals creates a foundation for more advanced observability, including service-level objectives, distributed tracing, and automated incident response.

References

  1. AWS Lambda – Using CloudWatch metrics 
  2. AWS Lambda – Sending logs to CloudWatch Logs 
  3. AWS Lambda – Working with function logs 
  4. AWS Lambda – Monitoring and troubleshooting 
  5. Amazon SNS – Monitoring with CloudWatch 
  6. Amazon CloudWatch pricing 
The examples in this article are intended for learning and should be tested in your own AWS account before being used in production.
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article