Lesson 2 of 5 Amazon CloudWatch Metrics and Alarms

Publishing Custom Metrics and Using Metric Math and Anomaly Detection

This lesson covers publishing custom metrics for application behaviour that default metrics miss, combining metrics with metric math, and using anomaly detection when a fixed threshold does not fit.

Learning outcomes

After completing this lesson, you will be able to:

  • Publish custom metrics with PutMetricData and the embedded metric format.
  • Combine metrics with metric math.
  • Alarm on anomaly detection bands.
  • Scale on backlog per instance.

Publishing custom metrics

Applications and scripts publish custom metrics with the PutMetricData API (aws cloudwatch put-metric-data), specifying a namespace that must not begin with AWS/, the metric name, dimensions, a value and a unit. Standard resolution metrics have 1-minute granularity; high-resolution metrics (StorageResolution 1) keep 1-second granularity and allow alarms with 10-second or 30-second periods. Each unique metric is billed monthly, so high-cardinality dimensions such as a user ID multiply cost quickly.

The embedded metric format (EMF) is an alternative: the application writes a structured JSON log line to CloudWatch Logs, and CloudWatch extracts the metrics asynchronously. EMF suits Lambda functions and containers because it avoids synchronous API calls and keeps the detailed log event for investigation. Metric filters, covered in the CloudWatch Logs module, are a third way to derive metrics from log text.

aws cloudwatch put-metric-data --namespace MyApp/Orders \
  --metric-name OrdersPlaced --unit Count --value 12 \
  --dimensions Environment=prod,Service=checkout
Sort into groups

How should it be published?

Exam skills 1.1.1 · 1.1.2

Choose how each custom measurement should reach CloudWatch.

Log in to try this activity Interactive activities are free with an account.

Metric math

Metric math combines metrics with arithmetic and functions to create new time series that can be graphed or alarmed on without publishing anything extra. Typical uses are an error rate (100*errors/requests), a backlog per instance (queue_depth/running_instances) and the sum of a metric across many resources with SUM(METRICS()). Metrics Insights queries metrics with SQL, for example the top ten instances by CPU, and can drive alarms that automatically include new resources matching the query.

# Error rate of an ALB target group as a percentage
e1 = 100 * m1 / m2
# m1 = SUM of HTTPCode_Target_5XX_Count, m2 = SUM of RequestCount, both for the same target group

# Metrics Insights: highest average CPU by instance
SELECT AVG(CPUUtilization) FROM SCHEMA("AWS/EC2", InstanceId)
GROUP BY InstanceId ORDER BY AVG() DESC LIMIT 10
Fill in the value

Metric math results

Exam skills 1.1.1 · 2.1.1

Work out what a metric math expression returns.

Log in to try this activity Interactive activities are free with an account.

Anomaly detection

Some metrics have no sensible fixed threshold: request counts rise every morning and fall at night, so a static alarm at 1,000 requests per minute either fires every day or misses real problems at night. CloudWatch anomaly detection trains a model on up to two weeks of history, including daily and weekly seasonality and trends, and produces an expected band. An anomaly detection alarm fires when the metric goes above, below or outside the band. The band width is set in standard deviations, and periods such as holidays can be excluded from training. AWS recommends anomaly detection as the replacement for Amazon DevOps Guru, which closes to new customers on 29 October 2026.

Scenario questions

Static threshold or anomaly band?

Exam skills 1.1.3 · 1.2.1

Decide when an anomaly detection alarm suits a metric better than a fixed threshold.

Log in to try this activity Interactive activities are free with an account.
Worked example

Scaling on backlog per instance

Worker instances process messages from an SQS queue. Scaling on CPU reacts too late, and scaling on queue depth alone ignores how many workers exist. The recommended metric is backlog per instance: ApproximateNumberOfMessagesVisible divided by the number of InService instances. If each instance handles 20 messages per minute and the acceptable latency is 5 minutes, the target backlog per instance is 100. A target tracking policy with a customised metric specification uses metric math to compute the ratio, so no separate publishing script is required.

"CustomizedMetricSpecification": {
  "Metrics": [
    {"Id": "m1", "ReturnData": false, "MetricStat": {"Stat": "Sum", "Metric": {
      "Namespace": "AWS/SQS", "MetricName": "ApproximateNumberOfMessagesVisible",
      "Dimensions": [{"Name": "QueueName", "Value": "orders"}]}}},
    {"Id": "m2", "ReturnData": false, "MetricStat": {"Stat": "Average", "Metric": {
      "Namespace": "AWS/AutoScaling", "MetricName": "GroupInServiceInstances",
      "Dimensions": [{"Name": "AutoScalingGroupName", "Value": "workers"}]}}},
    {"Id": "backlog", "Expression": "m1 / m2", "Label": "BacklogPerInstance", "ReturnData": true}
  ]
},
"TargetValue": 100
Check yourself

Which alarm periods do high-resolution custom metrics allow?

Show answer

10 seconds and 30 seconds, in addition to multiples of 60 seconds.

Exam Tips

Remember for the exam

  • Custom metrics use PutMetricData or the embedded metric format; namespaces cannot start with AWS/.
  • High-resolution metrics allow 10-second and 30-second alarm periods.
  • Metric math computes rates and ratios without publishing new metrics.
  • Use anomaly detection for metrics with daily or weekly patterns.
  • Scale queue workers on backlog per instance, not on CPU.