Sub topic 14
Anomaly detection alarms
This chapter assumes you can create a standard metric alarm, as covered in the earlier chapters on alarms and alarm actions. You should also know how statistics and periods shape a metric, and you should be comfortable passing JSON to the AWS CLI.
Why a fixed threshold is not always enough
A static threshold such as "CPU at or above 80 percent" works when you know what normal looks like. Many metrics have no single normal value. Request counts on a web application might peak at noon on weekdays and fall to a trickle overnight and on weekends. A threshold high enough to avoid false alarms at noon will never catch a failure at 3 a.m., when 500 requests per five minutes would already be a surge.
An anomaly detection alarm compares the metric to a band of expected values that changes over time. The band is built from the metric's own history, so it follows daily and weekly patterns without you picking numbers.
How the model works
CloudWatch trains a machine learning model on up to two weeks of past data for one metric and one statistic. The model captures hourly, daily, and weekly patterns and continues to retrain as new data arrives. The model's output is a band with an upper and a lower bound for each point in time.
Four things define a model:
- The namespace and metric name.
- The dimensions. A model for
InstanceId=i-aaais separate from one forInstanceId=i-bbb. - The statistic, for example
AverageorSum. A model forAveragedoes not apply toMaximum. - The band width, set when you create the alarm.
The band width is a number of standard deviations. The default is 2. A larger number gives a wider band, so fewer values count as anomalies. A smaller number makes the alarm more sensitive and noisier.
Creating the model
You can create a model explicitly with put-anomaly-detector. If you create an alarm that uses a band and no model exists yet, CloudWatch creates one for you. Creating the model first lets you view the band on a graph before you attach an alarm.
aws cloudwatch put-anomaly-detector \
--single-metric-anomaly-detector '{
"Namespace": "AWS/ApplicationELB",
"MetricName": "RequestCount",
"Stat": "Sum",
"Dimensions": [
{ "Name": "LoadBalancer", "Value": "app/web-alb/50dc6c495c0c9188" }
]
}'A new model needs time to learn. In the first hours the band is wide or missing, and it improves as more history is available. A metric with less than a day or two of data gives a poor band.
Creating the alarm
An anomaly detection alarm is a metric math alarm. You define two things in the --metrics list: the metric itself and an expression that returns the band. The ANOMALY_DETECTION_BAND(m1, 2) function takes the metric ID and the band width. You then tell the alarm which ID is the threshold with --threshold-metric-id.
Save this as metrics.json:
[
{
"Id": "m1",
"ReturnData": true,
"MetricStat": {
"Metric": {
"Namespace": "AWS/ApplicationELB",
"MetricName": "RequestCount",
"Dimensions": [
{ "Name": "LoadBalancer", "Value": "app/web-alb/50dc6c495c0c9188" }
]
},
"Period": 300,
"Stat": "Sum"
}
},
{
"Id": "ad1",
"Expression": "ANOMALY_DETECTION_BAND(m1, 2)",
"Label": "RequestCount (expected)",
"ReturnData": true
}
]Then create the alarm:
aws cloudwatch put-metric-alarm \
--alarm-name web-traffic-anomaly \
--metrics file://metrics.json \
--comparison-operator LessThanLowerOrGreaterThanUpperThreshold \
--threshold-metric-id ad1 \
--evaluation-periods 3 \
--datapoints-to-alarm 2 \
--treat-missing-data notBreaching \
--alarm-actions arn:aws:sns:us-east-1:111122223333:ops-alertsNotice what is missing: there is no --threshold value. The band replaces it. The --evaluation-periods and --datapoints-to-alarm options work as they do for a static alarm. Here the alarm goes to ALARM when 2 of the last 3 five-minute data points fall outside the band.
Choosing the comparison operator
Anomaly detection alarms use three operators that refer to the band:
| Operator | Alarms when the value is | Typical use |
|---|---|---|
| `GreaterThanUpperThreshold` | Above the band | Error counts, latency, cost spikes |
| `LessThanLowerThreshold` | Below the band | Traffic that should never drop, such as heartbeats |
| `LessThanLowerOrGreaterThanUpperThreshold` | Above or below the band | Request counts, where both a surge and a drop matter |
Pick the narrowest operator that fits. For latency, a value below the band is good news, so alarming on it creates noise.
Gotchas and common errors
- Using the wrong statistic. The model is tied to the statistic. If the alarm uses
Sumand the model was trained onAverage, CloudWatch trains a separate model, which starts with no history. - Alarming on a new metric. With little history, the band is unreliable. Use a static alarm until the model has at least a few days of data.
- Metrics with no pattern. Anomaly detection suits metrics with regular rhythms or a stable level. A metric that is mostly zero with rare large bursts produces a band that makes the bursts look like constant anomalies.
- Planned events distort the model. A load test, a marketing campaign, or an outage teaches the model that unusual values are normal. You can set excluded time ranges on the model so that CloudWatch ignores those periods during training. Do this for known events.
- Setting the band too narrow. A width of 1 flags many ordinary variations. Start at 2 and adjust after you watch the alarm for a week.
- Missing data. As with other alarms,
--treat-missing-datadecides what happens when no data point arrives. For a metric that stops reporting when traffic is zero,notBreachingavoids false alarms, but then a real outage that stops data can go unnoticed. Decide this deliberately. - Cost. An anomaly detection alarm is billed at a higher rate than a standard alarm because it evaluates the model as well as the metric. Check the current CloudWatch pricing page before you create many of them.
When to use which alarm type
Use a static threshold when you know the limit, such as disk at 90 percent full or a hard service limit. Use anomaly detection when the right limit depends on the time of day or week, or when you would otherwise have to tune thresholds for many resources by hand. Many teams use both on the same service. The static alarm covers the known danger, and the anomaly alarm catches unusual behavior that stays under the limit. If they produce too many overlapping notifications, combine them with a composite alarm.
Exercise
An Application Load Balancer's RequestCount (Sum, 5-minute period) is high on weekday afternoons and near zero overnight. You want an alarm for both unexpected surges and unexpected drops, with no fixed threshold. Which comparison operator do you use, what two entries must the --metrics list contain, and what should you check about the metric's history before relying on the alarm?
Show answer
Use LessThanLowerOrGreaterThanUpperThreshold. The --metrics list needs the metric itself (for example Id m1 with a MetricStat using the Sum statistic and a 300-second period) and an expression entry such as ANOMALYDETECTIONBAND(m1, 2), whose Id is passed to --threshold-metric-id. Before relying on the alarm, check that the metric has enough history (at least several days, ideally close to two weeks) so the model has learned the daily and weekly pattern, and exclude any load tests or outages from training.