Sub topic 13
Observing functions with CloudWatch and X-Ray
This chapter assumes you can write and deploy a handler, know that the execution role controls what a function may call, and can read a SAM template. Lambda sends three kinds of telemetry to AWS services with almost no setup: logs, metrics and traces.
The three signals
| Signal | Answers | Where |
|---|---|---|
| Logs | What happened in this invocation? | Log group `/aws/lambda/<function-name>` |
| Metrics | How often, how slow, how many failures? | CloudWatch namespace `AWS/Lambda` |
| Traces | Which downstream call was slow? | X-Ray service map and trace view |
Logs
Anything your code writes to standard output or the logging module reaches CloudWatch Logs. Each invocation also ends with a REPORT line showing Duration, Billed Duration, Memory Size, Max Memory Used and, on cold starts, Init Duration. Use Max Memory Used to right-size memory.
Plain text is hard to query. Emit one JSON object per line so CloudWatch Logs Insights can filter on fields.
import json
import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def handler(event, context):
logger.info(json.dumps({
"message": "order received",
"request_id": context.aws_request_id,
"remaining_ms": context.get_remaining_time_in_millis(),
}))
return {"statusCode": 200, "body": "ok"}This Logs Insights query finds the slowest invocations:
filter @type = "REPORT"
| stats max(@duration), avg(@maxMemoryUsed) by bin(5m)Log groups keep data forever by default, so set a retention period.
Metrics
Lambda publishes these metrics without any code:
Invocations: the number of times the function was invoked.Errors: invocations that raised an exception or timed out.Throttles: invocations rejected because of a concurrency limit. They are not counted inErrors.Duration: run time in milliseconds. Alarm on the p99 statistic, not the average.ConcurrentExecutions: environments running at once.IteratorAge: for stream sources, how far behind the function is.
To publish your own numbers, such as orders per minute, write them in CloudWatch Embedded Metric Format as JSON log lines. This avoids a synchronous PutMetricData call inside the handler.
Tracing with X-Ray
Active tracing makes Lambda record a segment for each sampled invocation, showing init time, invocation time and the overhead around them. To see downstream calls, instrument the AWS SDK as well.
Resources:
OrdersFunction:
Type: AWS::Serverless::Function
Properties:
Handler: app.handler
Runtime: python3.12
CodeUri: src/
Tracing: Active
LoggingConfig:
LogFormat: JSONSAM adds the xray:PutTraceSegments permission to the role when Tracing: Active is set. In code, add the aws-xray-sdk package and patch the libraries you use:
from aws_xray_sdk.core import patch_all
patch_all() # traces boto3 and requests calls as subsegmentsEach DynamoDB or HTTP call then appears as a subsegment with its own latency. A trace also follows a request across API Gateway, Lambda and SQS when each service has tracing enabled.
Common errors
- No logs appear. The execution role lacks
logs:CreateLogStreamandlogs:PutLogEvents. AttachAWSLambdaBasicExecutionRole. - Alarm on
Errorsstays quiet during an outage. Throttled calls count underThrottles. Alarm on both. - Traces are missing downstream calls. Tracing is enabled but the SDK was not patched.
- Logs from one request are scattered. Include
aws_request_idin every line. - Surprising CloudWatch bill. Debug-level logging on a high-traffic function. Log at INFO and sample verbose output.
Exercise
A function's Errors metric is zero, but callers report failed requests during a traffic spike. Which metric do you check next, and why?
Show answer
Check Throttles. When concurrency limits are reached, Lambda rejects invocations before the code runs, so they count as throttles and not as errors. You would then review reserved concurrency and the account limit.