Skill 4.2.2

Implement code that emits custom metrics.

Key Concepts

Using the SDK, code calls PutMetricData, ideally batching several values per call. Using the embedded metric format, code writes structured JSON log lines that CloudWatch turns into metrics, which is preferred in Lambda because it adds no API calls. Powertools for AWS Lambda provides a Metrics utility that buffers metrics and flushes them as EMF at the end of each invocation.

Metrics should use a clear namespace, meaningful dimensions such as Service and Environment, and correct units. They can then drive alarms, dashboards and Auto Scaling policies.

You can publish custom metrics with the PutMetricData API, choosing a namespace, metric name, dimensions, unit and resolution (standard 60 seconds or high resolution down to 1 second). Calling the API synchronously adds latency and request cost to every invocation.

The embedded metric format (EMF) avoids this: your code writes a JSON log line with a special _aws metadata block, and CloudWatch extracts the metrics from the log asynchronously. EMF works from Lambda, ECS and EC2 (with the CloudWatch agent), and libraries such as Powertools for AWS Lambda produce it for you. Each unique combination of dimensions is a separate metric, so high-cardinality dimensions such as user IDs increase cost.