Sub topic 3
A repeatable right-sizing method
This chapter assumes you can launch and stop EC2 instances, run AWS CLI commands, and read a CloudWatch metric graph. It also assumes you know what an Auto Scaling group and a launch template are. The previous chapter showed how to collect utilization data. This chapter turns that data into a procedure you can run on any instance, on any schedule, and get the same kind of answer each time.
Why you need a method
Right-sizing means matching an instance's resources to what the workload actually needs. Done ad hoc, it fails in predictable ways:
- Someone looks at average CPU, sees 8%, and downsizes. The nightly batch job then hits 95% and the instance falls over.
- Someone cuts CPU and never checks memory, because EC2 does not publish memory metrics by default.
- A change goes in, nobody records the before-and-after numbers, and nobody can say whether it helped.
A method fixes this by fixing the order of steps, the statistics you read, and the evidence you need before and after each change.
Step 1: Scope and inventory
Start by deciding which instances you are reviewing and what constraints apply to them. Record the following for each:
- Instance ID, type, purchase option (On-Demand, Spot, or covered by a Savings Plan), and whether it belongs to an Auto Scaling group.
- The workload owner, and what a failure would cost.
- Constraints that limit your choices: software licensed per vCPU, instance store volumes (data is lost when the instance stops), a minimum memory requirement from a vendor, or a hard dependency on a specific CPU architecture.
Skip instances that are very short-lived or already scheduled for retirement. Review Auto Scaling groups at the group level, since the launch template defines the type for every member.
Step 2: Collect metrics over a full cycle
Your observation window must contain the workload's busiest period. Two weeks is a reasonable default because it covers two weekly cycles. Use a month or more when the workload has month-end processing, billing runs, or reporting peaks.
Four resource dimensions matter, and only some are available by default:
| Resource | Metric | Source | Notes |
|---|---|---|---|
| CPU | `CPUUtilization` | `AWS/EC2`, default | Percent of the instance's vCPUs |
| Memory | `mem_used_percent` | `CWAgent`, needs CloudWatch agent | Not published by EC2 itself |
| Network | `NetworkIn`, `NetworkOut` | `AWS/EC2`, default | Bytes per period, so convert to a rate |
| Disk | `EBSReadBytes`, `EBSWriteBytes`, `EBSReadOps`, `EBSWriteOps` | `AWS/EC2`, default | Compare with the type's EBS limits |
Install the CloudWatch agent on instances where memory matters. A minimal agent configuration that collects memory and disk space looks like this:
{
"metrics": {
"append_dimensions": {
"InstanceId": "${aws:InstanceId}"
},
"metrics_collected": {
"mem": {
"measurement": ["mem_used_percent"],
"metrics_collection_interval": 60
},
"disk": {
"measurement": ["used_percent"],
"resources": ["*"],
"metrics_collection_interval": 60
}
}
}
}Let the agent run for the whole observation window before you judge memory. Without it you are guessing.
Burstable instances (T-family) need one more metric. CPUCreditBalance shows whether the instance can sustain its bursts, and CPUSurplusCreditBalance shows whether it is paying for extra credits in unlimited mode. A T instance with low CPU utilization and a steadily falling credit balance is not over-provisioned. It is close to throttling.
Step 3: Find candidates using peak statistics
Average utilization hides the moments that cause outages. Read the p95 and the maximum of your samples, and treat the average as context only.
The first call below returns hourly maxima for CPU over two weeks. A short script then turns them into a p95 and an overall peak:
#!/usr/bin/env bash
# Usage: ./cpu-peaks.sh i-0123456789abcdef0
# Requires GNU date (Linux), the AWS CLI, and jq.
set -euo pipefail
INSTANCE_ID="$1"
START=$(date -u -d '14 days ago' +%Y-%m-%dT%H:%M:%SZ)
END=$(date -u +%Y-%m-%dT%H:%M:%SZ)
aws cloudwatch get-metric-statistics \
--namespace AWS/EC2 \
--metric-name CPUUtilization \
--dimensions Name=InstanceId,Value="$INSTANCE_ID" \
--start-time "$START" \
--end-time "$END" \
--period 3600 \
--statistics Maximum \
--query 'Datapoints[].Maximum' \
--output json \
| jq 'sort | {samples: length, p95_of_hourly_max: .[(length * 0.95 | floor)], peak: .[-1]}'The p95 here is taken over hourly maxima, so it is deliberately conservative. It tells you the CPU level the instance reached in its busiest 5% of hours. If you want a true percentile of the underlying samples, get-metric-statistics accepts --extended-statistics p95 instead of --statistics. You cannot pass both in one call.
Mind the retention rules when you pick a window and period. CloudWatch keeps 1-minute data points for 15 days, 5-minute points for 63 days, and 1-hour points for 455 days. get-metric-statistics also returns at most 1,440 data points per call. Fourteen days at a 3,600-second period is 336 points, which is well inside that limit.
Flag an instance as a candidate when all of these hold over the window. Treat these thresholds as starting points to tune, not rules:
- CPU p95 below roughly 40%, and the peak below 70%.
- Memory p95 below roughly 50%, if the agent is installed.
- Network and EBS throughput well below the limits of the current type and the next size down.
An instance with very low use on every dimension may not need a smaller size at all. It may be idle and a candidate for shutdown, consolidation, or a scheduled stop.
Step 4: Choose a target with headroom
Choose the target by projecting current peaks onto the new size. Moving one size down within a family halves the vCPUs and, for most families, halves memory. The same absolute load then produces roughly double the utilization.
A worked example. An m5.2xlarge has 8 vCPUs and 32 GiB of memory. Over two weeks you measure:
- CPU p95 of 18%, peak of 31%.
- Memory p95 of 30%, which is about 9.6 GiB.
On an m5.xlarge (4 vCPUs, 16 GiB), the projection is:
- CPU p95 about 36%, peak about 62%.
- Memory p95 about 60% (9.6 of 16 GiB).
Both fit under a target of about 70% at peak, so m5.xlarge is a sound choice. A second step down to m5.large would push CPU peak to about 124%, which is not viable. The projection stopped you from over-correcting.
Set an explicit headroom target before you start. A common choice is to keep peak CPU under 70% and memory under 75–80%, so a traffic spike or a failed neighbour in an Auto Scaling group does not push the instance to saturation. Use more headroom for latency-sensitive services and less for batch jobs that tolerate slow runs.
Also check limits that scale with size. Smaller sizes have lower baseline network bandwidth and lower EBS throughput and IOPS caps, and these can bind before CPU does. Choosing a different family, for example memory-optimized instead of general-purpose when memory is the binding resource, is covered in the chapter on instance families.
Step 5: Change one thing and validate
Change one variable at a time. If you resize and switch architecture in the same change and latency worsens, you cannot tell which change caused it.
For an EBS-backed instance outside an Auto Scaling group, changing the type requires a stop and start. Public IPv4 addresses that are not Elastic IPs change, and instance store data is lost:
INSTANCE_ID=i-0123456789abcdef0
aws ec2 stop-instances --instance-ids "$INSTANCE_ID"
aws ec2 wait instance-stopped --instance-ids "$INSTANCE_ID"
aws ec2 modify-instance-attribute \
--instance-id "$INSTANCE_ID" \
--instance-type "{\"Value\": \"m5.xlarge\"}"
aws ec2 start-instances --instance-ids "$INSTANCE_ID"
aws ec2 wait instance-running --instance-ids "$INSTANCE_ID"For Auto Scaling groups, create a new launch template version with the new type and roll it out through an instance refresh, so you replace instances gradually and keep capacity. Before you change anything, write down the rollback: the previous instance type, or the previous launch template version.
Define pass criteria before the change, not after. Examples:
- p99 latency within 10% of the baseline.
- Error rate unchanged.
- CPU peak under your headroom target during the busiest hours.
- No increase in queue depth or consumer lag.
Run the check through a period that contains real load. A resize validated at 3 a.m. proves nothing.
Step 6: Monitor and record
Keep a record per change: instance, old type, new type, date, the measured before-and-after p95 and peak for each resource, and the cost difference. After the change, watch the same metrics for at least one full cycle, since a weekly job might not run for six more days.
Workloads drift. A service that fit comfortably last quarter may have grown, so schedule the review. Quarterly works for stable fleets, and monthly for fast-moving ones.
Common errors
- Reading averages. The average of a spiky workload is low. Use p95 and peak.
- Ignoring memory. A CPU-only review will downsize memory-bound workloads into swapping or out-of-memory kills.
- Too short a window. A window that misses month-end makes the instance look idle.
- Linear assumptions. Halving the size doubles utilization only if the workload scales evenly. Single-threaded applications may already be pegging one core at 12% total CPU on 8 vCPUs.
- Skipping the rollback. A change with no recorded way back turns a small mistake into an incident.
- Bundling changes. Resizing, changing family, and changing architecture together make failures impossible to attribute.
Exercise
An m5.4xlarge (16 vCPUs, 64 GiB) shows over 14 days: CPU p95 of 22% and peak of 38%, memory p95 of 55% (about 35 GiB). You consider an m5.2xlarge (8 vCPUs, 32 GiB). Project the CPU and memory on the smaller size and decide whether it is safe with a 70% peak CPU and 80% memory headroom target.
Show answer
On the 8-vCPU size, CPU roughly doubles: p95 about 44%, peak about 76%. Memory needs about 35 GiB but the instance has only 32 GiB, so it would exceed 100% and the process would swap or be killed. The change is not safe. Memory is the binding resource, and the CPU peak also breaks the 70% target. Keep the current size, or look at a different approach such as fixing the memory footprint.
Exercise
Why does a method that reads the p95 and peak of CPU, and also collects memory, give a safer result than a review of the CPU average alone?
Show answer
The average is dominated by quiet hours and hides short spikes that cause saturation, so the p95 and peak show what the instance must survive. EC2 does not publish memory by default, so a CPU-only review cannot see memory-bound workloads. Reading peaks across all resources avoids downsizing an instance that is idle on average but busy at its busiest moments or limited by memory.