AWS Builder Center

From Deployment to Observability: Monitoring AWS Lambda Applications with Amazon CloudWatch

Learn how to monitor AWS Lambda applications using Amazon CloudWatch. This hands-on guide covers logs, metrics, alarms, troubleshooting, and alert notifications to help developers identify failures and improve serverless application reliability.

Introduction

Deploying an application to AWS is only the beginning. Once an application starts handling real requests, developers must understand whether it is working correctly, how quickly it responds, and what happens when something fails.
Serverless applications built with AWS Lambda reduce infrastructure management, but they still require monitoring and troubleshooting. A function can fail because of incorrect configuration, missing permissions, database connectivity problems, unexpected input, or execution timeouts.
Amazon CloudWatch helps developers observe application behavior through logs, metrics, dashboards, and alarms.
In this tutorial, we will build a practical monitoring workflow for an AWS Lambda function using Amazon CloudWatch. By the end, you will know how to inspect execution logs, analyze errors, create alarms, and receive notifications when something goes wrong.

1. Understanding the Architecture

Our example uses a simple Node.js Lambda function that processes order events.
The monitoring architecture is:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Order Event
|
v
AWS Lambda
|
+-----+------+
| |
v v
Application CloudWatch
Output Metrics
| |
v v
CloudWatch Logs CloudWatch
Alarms
|
v
Amazon SNS
|
v
Email Alert
The Lambda function processes an event and writes diagnostic information to CloudWatch Logs. Lambda also publishes standard invocation and performance metrics to CloudWatch. Alarms evaluate selected metrics and can trigger notifications through Amazon SNS.
Lambda automatically sends its standard metrics to CloudWatch; you do not need to add separate metric permissions to the execution role for those standard metrics.

2. Prerequisites

Before starting, ensure that you have:
  • An AWS account.
  • Access to the AWS Lambda and Amazon CloudWatch consoles.
  • Basic knowledge of JavaScript and Node.js.
  • An IAM execution role with the necessary CloudWatch Logs permissions.
  • An email address for receiving optional alarm notifications.
This tutorial uses the AWS Management Console and AWS CLI for selected steps. Resource names and Region values are examples; replace them with your own.

3. Create a Sample Lambda Function

Open the AWS Lambda console and create a function with the following settings:
  • Function name: order-processor-monitor
  • Runtime: Node.js 22, if available in your Region.
  • Architecture: Choose the architecture appropriate for your environment.
  • Execution role: Create or select a role with the required CloudWatch Logs permissions.
For this example, the function processes an order event and intentionally supports a test failure.
Replace the generated code with:
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
exports.handler = async (event) => {
console.log(JSON.stringify({
level: "INFO",
message: "Processing order",
orderId: event.orderId ?? "unknown",
timestamp: new Date().toISOString()
}));

if (event.simulateFailure === true) {
console.error(JSON.stringify({
level: "ERROR",
message: "Simulated order processing failure",
orderId: event.orderId ?? "unknown"
}));

throw new Error("Simulated order processing failure");
}

return {
statusCode: 200,
body: JSON.stringify({
message: "Order processed successfully",
orderId: event.orderId ?? "unknown"
})
};
};
Choose Deploy to save the function.
The function writes structured JSON logs, which makes it easier to identify important fields when troubleshooting. The simulated failure is intended only for testing monitoring behavior.

4. Test Successful and Failed Executions

Open the function's Test tab and create a test event.
Successful test event:
1
2
3
4
{
"orderId": "ORD-1001",
"simulateFailure": false
}
Run the test. The function should complete successfully and return a response containing the order ID.
Next, test a failure:
1
2
3
4
{
"orderId": "ORD-1002",
"simulateFailure": true
}
This execution should fail with the simulated error.
These two executions give us a straightforward way to observe both successful and failed invocations in CloudWatch.

5. Inspect Logs in Amazon CloudWatch

AWS Lambda sends execution logs to CloudWatch Logs when the function's execution role has the necessary permissions.
To inspect the logs:
  1. Open the Lambda function.
  2. Select the Monitor tab.
  3. Choose the option to view logs in CloudWatch.
  4. Open the latest log stream.
  5. Inspect the timestamped messages, request information, and error details.
Lambda normally creates a log group named:
/aws/lambda/order-processor-monitor
You should find messages such as:
  • Processing order
  • Simulated order processing failure
  • The associated exception and execution report
Logs help answer questions that metrics alone cannot resolve. For example, an error metric can tell you that a function failed, while the corresponding log can explain which operation failed and which order was being processed.

Query logs with CloudWatch Logs Insights

CloudWatch Logs Insights can search and analyze log events.
For example, use this query to find error-related messages in the selected log group:
1
2
3
4
fields @timestamp, @message
| filter @message like /ERROR|Error|error/
| sort @timestamp desc
| limit 50
To inspect Lambda execution duration and memory usage, try:
1
2
3
4
fields @timestamp, @duration, @billedDuration, @maxMemoryUsed
| filter @type = "REPORT"
| sort @timestamp desc
| limit 20
Run the query over an appropriate time range. Logs Insights results depend on the available log fields and the selected time window.

6. Monitor Important Lambda Metrics

CloudWatch provides several standard metrics that help identify reliability and performance problems.
MetricWhat it tells you
InvocationsNumber of function invocations
ErrorsNumber of failed function executions
DurationTime spent executing the function
ThrottlesNumber of invocations rejected because of concurrency limits
ConcurrentExecutionsNumber of function executions running simultaneously
For event-driven applications, additional metrics may be relevant depending on how Lambda receives events.
For example, if Lambda processes messages asynchronously, event age and dropped-event metrics can help reveal processing delays or events that were not successfully processed.

How to interpret the metrics

High error count: Inspect recent logs for exceptions, invalid input, dependency failures, or configuration problems.
Increasing duration: Check for slow database queries, external API calls, inefficient processing, or insufficient memory allocation.
Increasing throttles: Review concurrency limits, traffic volume, and execution duration.
Growing processing delay: Investigate retries, throttling, downstream dependencies, and the rate at which incoming events are processed.
A metric is a signal, not a complete diagnosis. Combine it with logs and application context to determine the root cause.

7. Create a CloudWatch Alarm for Lambda Errors

An alarm can detect when the function's error count exceeds a defined threshold.
For this example, we will create an alarm that triggers when the function records at least one error during a five-minute period.
Open the CloudWatch console:
  1. Navigate to Alarms and choose Create alarm.
  2. Select the Lambda metric namespace.
  3. Choose the Errors metric for order-processor-monitor.
  4. Set the statistic to Sum.
  5. Set the period to five minutes.
  6. Configure the threshold as Greater/Equal to 1.
  7. Configure the alarm action and notifications.
  8. Give the alarm a descriptive name, such as order-processor-error-alarm.
  9. Create the alarm.
When the configured evaluation conditions are met, the alarm enters the ALARM state.
The exact response time depends on metric publication, evaluation periods, and alarm configuration. This is not a guaranteed instantaneous alert.

Why alarms matter

Without alarms, developers may discover failures only after a customer reports a problem or someone manually checks the logs.
With alarms, the system can notify the responsible team when a monitored condition requires attention.
A useful production setup generally includes alarms for errors, throttles, and execution duration, with thresholds chosen according to the application's normal workload and service requirements.

8. Send Notifications with Amazon SNS

Amazon SNS can deliver CloudWatch alarm notifications to an email subscription.
To configure email notifications:
  1. Open the Amazon SNS console.
  2. Create a standard topic named lambda-monitoring-alerts.
  3. Create an email subscription using an address you control.
  4. Open the confirmation email and confirm the subscription.
  5. Copy the topic ARN.
  6. Return to your CloudWatch alarm.
  7. Add an alarm action that publishes to the SNS topic.
The notification configuration must use the correct topic ARN and an IAM configuration that permits the alarm to publish to the topic.
When the alarm transitions into its configured notification state, SNS can send an email describing the alarm.
For production environments, avoid sending every low-priority event to the same destination. Group alerts by severity and make sure each alert identifies the affected function, the condition, and the next troubleshooting step.

9. Troubleshoot Common Problems

Monitoring becomes useful when developers can translate signals into corrective actions.
ProblemWhat to investigate
Lambda execution failsCloudWatch error logs, stack traces, input validation, permissions
Function times outTimeout setting, slow dependencies, network calls, database queries
Function is throttledConcurrency limits, request volume, execution duration
Logs are missingExecution role permissions, selected Region, log group and time range
Alarm does not triggerMetric dimensions, threshold, evaluation period, missing-data treatment
Email notification is not receivedSNS subscription confirmation, topic ARN, alarm action configuration

Example: Debugging a failed order

Suppose the error count rises after a deployment.
A practical investigation would be:
  1. Identify the Lambda function and the time when errors increased.
  2. Open the matching CloudWatch log streams.
  3. Search for the exception and affected order ID.
  4. Determine whether the failure is related to application logic, configuration, or a dependency.
  5. Correct the root cause.
  6. Run successful and failure test cases.
  7. Confirm that the error metric returns to normal and the alarm transitions appropriately.
This process is more reliable than repeatedly redeploying code without evidence about the failure.

10. Security and Cost Considerations

Monitoring should be designed alongside the application rather than added as an afterthought.

Security

  • Grant the Lambda execution role only the permissions it needs.
  • Avoid logging passwords, access tokens, personal information, or sensitive order details.
  • Use appropriate access controls for CloudWatch log groups and dashboards.
  • Apply suitable log retention settings.
  • Protect SNS topics so only authorized principals can publish or subscribe.

Cost

CloudWatch usage can incur charges for log ingestion and storage, dashboards, alarms, custom metrics, and Logs Insights queries, depending on usage and applicable free-tier allowances.
To manage cost:
  • Set log retention instead of keeping logs indefinitely.
  • Avoid unnecessarily verbose production logging.
  • Review the number of alarms and custom metrics.
  • Use appropriate query time ranges when analyzing logs.
  • Check current AWS pricing for the Region and services you use.
Monitoring is valuable, but an uncontrolled logging strategy can increase cost without improving operational visibility.

11. Best Practices for Production Applications

For a production-ready serverless application, consider the following practices:
  1. Use structured logs: Include useful fields such as request IDs, operation names, and error categories.
  2. Create actionable alarms: Alert on conditions that require investigation or intervention.
  3. Monitor trends: Review duration, errors, throttles, and event-processing delays.
  4. Set retention policies: Keep logs for an appropriate period based on operational and compliance requirements.
  5. Test failure scenarios: Verify that alarms and notification paths work before relying on them.
  6. Protect sensitive information: Keep secrets and unnecessary personal data out of logs.
  7. Document recovery procedures: Make it clear who responds to an alert and how to investigate it.
For more complex workloads, consider distributed tracing and application-level metrics to understand how requests move across multiple AWS services.

Conclusion

Deploying an AWS Lambda function is not enough to ensure that an application remains reliable. Developers also need to understand what happens during execution, detect failures, and respond before problems affect users.
Amazon CloudWatch provides the core building blocks for this workflow: logs for investigation, metrics for measuring behavior, alarms for detecting abnormal conditions, and integrations such as Amazon SNS for notifications.
By applying these techniques to a simple order-processing function, developers can establish a practical monitoring foundation and build more observable serverless applications.
Official AWS resources
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