Sub topic 14
CloudWatch metrics and alarms that drive scaling
Prerequisites
This chapter assumes you can run AWS CLI commands and know what an EC2 instance, an Application Load Balancer (ALB) and an Auto Scaling group (ASG) are. You should also know that an ASG has minimum, maximum and desired capacity. Scaling policies are covered in the next chapter. Here you learn what feeds them.
Why metrics come first
An Auto Scaling group does not watch your application. It reacts to numbers that Amazon CloudWatch collects. CloudWatch is the AWS service that stores metrics, which are time-ordered data points such as CPU use or request count. If the number is wrong, late or missing, scaling is wrong, late or missing too.
A scaling decision follows this path:
- A service publishes data points to CloudWatch.
- CloudWatch aggregates them over a period.
- An alarm compares the aggregate with a threshold.
- The alarm changes state and calls a scaling policy.
- The ASG changes its desired capacity.
Anatomy of a metric
A metric is identified by a namespace, a name and a set of dimensions.
- The namespace groups related metrics, for example
AWS/EC2,AWS/ApplicationELBorAWS/AutoScaling. - The name says what is measured, for example
CPUUtilization. - Dimensions are name and value pairs that narrow the metric to one resource, such as
AutoScalingGroupName=web-asg.
The same metric name with different dimensions is a different metric. CPUUtilization for one instance and CPUUtilization for the whole ASG are separate series. This is the most common reason an alarm sits in INSUFFICIENT_DATA: the dimension in the alarm does not match what the service publishes.
Statistics and periods
Each alarm evaluates a statistic over a period. The statistic can be Average, Sum, Minimum, Maximum, SampleCount or a percentile such as p99. The period is the length of each aggregation window in seconds.
Choose the statistic to match the meaning of the metric:
| Metric | Sensible statistic | Reason |
|---|---|---|
| `CPUUtilization` | Average | Already a percentage per instance |
| `RequestCount` (ALB) | Sum | Counts requests in each period |
| `TargetResponseTime` | p90 or p99 | Averages hide slow requests |
| `HealthyHostCount` | Minimum | You care about the worst moment |
Metrics that commonly drive scaling
EC2 metrics
EC2 publishes CPUUtilization, NetworkIn, NetworkOut and disk I/O metrics. Memory and disk space are not published by EC2, because the hypervisor cannot see inside the guest operating system. To scale on memory you must install the CloudWatch agent and publish a custom metric.
Basic monitoring sends EC2 metrics every 5 minutes at no charge. Detailed monitoring sends them every 1 minute for a fee. For an ASG, detailed monitoring is enabled in the launch template. With 5-minute data, scale-out can lag a traffic spike by several minutes, so most production groups use detailed monitoring.
Load balancer metrics
The ALB publishes metrics in AWS/ApplicationELB once per minute. The most useful for scaling are:
RequestCountPerTarget: requests divided by the number of registered targets. This reflects load per instance directly.TargetResponseTime: time from the load balancer sending a request to receiving the response.HTTPCode_Target_5XX_Count: errors produced by your targets, useful for alarms that notify you, less so for scaling.
Request count tracks demand more closely than CPU for many web applications. CPU rises only after instances are already busy.
Custom metrics
For application signals such as queue depth, publish your own metric with put-metric-data.
aws cloudwatch put-metric-data \
--namespace "Custom/Web" \
--metric-name QueueDepth \
--dimensions AutoScalingGroupName=web-asg \
--value 42 \
--unit CountA good scaling metric changes in proportion to capacity. If you double the instances, the metric per instance should roughly halve. Queue depth alone does not do that, so a common approach is to divide it by the number of instances and publish backlog per instance.
Alarms
An alarm watches one metric (or a math expression over metrics) and has three states:
OK: the metric is within the threshold.ALARM: the threshold is breached.INSUFFICIENT_DATA: not enough data points to decide.
Three settings control when it fires:
- Period: the length of each window.
- Evaluation periods: how many recent windows are examined.
- Datapoints to alarm: how many of those windows must breach, an "M out of N" rule.
With a 60-second period, 3 evaluation periods and 3 datapoints to alarm, the metric must breach for three consecutive minutes. With 2 datapoints out of 3, it must breach in any two of the last three minutes. Shorter evaluation reacts faster but scales on noise.
Missing data
Choose how the alarm treats periods with no data: missing (the default, which keeps the state), notBreaching, breaching or ignore. For a metric that stops when traffic stops, such as a request count, notBreaching is usually right. Otherwise an alarm could stay in ALARM after traffic drops.
An example alarm
This alarm fires when average CPU across the ASG is above 70 percent for three one-minute periods.
aws cloudwatch put-metric-alarm \
--alarm-name web-asg-high-cpu \
--namespace AWS/EC2 \
--metric-name CPUUtilization \
--dimensions Name=AutoScalingGroupName,Value=web-asg \
--statistic Average \
--period 60 \
--evaluation-periods 3 \
--datapoints-to-alarm 3 \
--threshold 70 \
--comparison-operator GreaterThanThreshold \
--treat-missing-data notBreachingYou can add --alarm-actions with the ARN of a scaling policy. That is how step and simple scaling work. Target tracking works differently: the ASG creates and owns its alarms for you.
Alarms created by target tracking
When you attach a target tracking policy, the ASG creates two alarms with names beginning TargetTracking-. One is a high alarm that scales out. The other is a low alarm that scales in. The scale-in alarm is deliberately conservative: it needs 15 consecutive one-minute datapoints below the target before it acts. Scale-out uses fewer datapoints, typically 3. This asymmetry protects availability, because removing capacity too early is more harmful than adding it too early.
Do not edit or delete these alarms. The ASG manages them and recreates or removes them with the policy.
Common errors
- Alarm stuck in
INSUFFICIENT_DATA. Check namespace, metric name and dimensions againstaws cloudwatch list-metrics. A typo in the ASG name gives a valid but empty metric. - Scaling on a metric that does not track capacity. Total request count does not fall when you add instances, so the alarm never clears and the group scales to its maximum.
- Slow reaction. Basic monitoring, long periods and many evaluation periods add up. Count the delay before alarm, then add instance boot time.
- Memory-based scaling that does nothing. EC2 has no memory metric until the agent is installed.
- Flapping. A threshold close to normal load with short evaluation produces alternating scale-out and scale-in.
Checking what CloudWatch sees
You can read the metric your alarm uses before relying on it.
aws cloudwatch get-metric-statistics \
--namespace AWS/EC2 \
--metric-name CPUUtilization \
--dimensions Name=AutoScalingGroupName,Value=web-asg \
--statistics Average \
--period 60 \
--start-time "$(date -u -d '-15 minutes' +%Y-%m-%dT%H:%M:%SZ)" \
--end-time "$(date -u +%Y-%m-%dT%H:%M:%SZ)"The date -d form shown works with GNU date on Linux. On macOS, use date -u -v-15M. An empty Datapoints list means the dimensions are wrong or the group publishes no data.
Exercise
An alarm on total ALB RequestCount (Sum) triggers scale-out at 5,000 requests per minute. After the group grows from 2 to 6 instances, the alarm stays in ALARM and the group keeps growing to its maximum. Why does this happen, and which metric would fix it?
Show answer
Total request count does not depend on how many instances exist, so adding capacity never brings it below the threshold. Use a per-instance metric such as RequestCountPerTarget, which falls as targets are added, ideally through a target tracking policy.
Exercise
An alarm uses 5 evaluation periods and 5 datapoints to alarm, with a 60-second period. A traffic spike breaches the threshold in minutes 1, 2, 4 and 5, but minute 3 is just under it. Does the alarm fire? What setting would change that?
Show answer
No. All 5 datapoints must breach, and minute 3 did not. Setting datapoints to alarm to 4 out of 5 would make it fire.