Amazon CloudWatch Metrics, Alarms and the CloudWatch Agent: Dashboards, Composite Alarms and Anomaly Detection
Metrics Basics
| Term | Meaning |
| Namespace | Container such as AWS/EC2, AWS/RDS, CWAgent or your own |
| Metric | Time-ordered data points, for example CPUUtilization |
| Dimension | Name/value pair that identifies a series (InstanceId=i-0abc). Each unique combination is a separate metric |
| Statistic | Average, Sum, Min, Max, SampleCount, percentiles (p99) |
| Period | Aggregation window in seconds (60 or multiples). High-resolution custom metrics go down to 1 second |
| Retention | 1 s data for 3 hours, 1 min for 15 days, 5 min for 63 days, 1 hour for 455 days (15 months) |
| Regional | Metrics live in one Region. Use cross-Region dashboards or metric streams to combine |
Default Metrics You Must Know
| Service | Included metrics | NOT included by default |
| EC2 | CPUUtilization, NetworkIn/Out, DiskReadOps/WriteOps (instance store), StatusCheckFailed, CPUCreditBalance. 5-minute basic, 1-minute with detailed monitoring | Memory, disk space, swap, processes. Use the CloudWatch agent |
| EBS | VolumeReadOps, VolumeQueueLength, BurstBalance | File system usage |
| ELB | RequestCount, TargetResponseTime, HTTPCode_*, HealthyHostCount | |
| RDS | CPUUtilization, FreeStorageSpace, DatabaseConnections, ReplicaLag | OS detail (use Enhanced Monitoring) |
| Lambda | Invocations, Errors, Duration, Throttles | Memory used (Lambda Insights or logs) |
CloudWatch Agent
The unified CloudWatch agent collects system-level metrics (memory, disk, swap, CPU per core, network, processes) and logs from EC2 and on-premises servers on Linux and Windows. It can also receive StatsD and collectd metrics and OpenTelemetry/X-Ray traces.
- Attach an IAM role with
CloudWatchAgentServerPolicy (and SSM managed core if you use SSM)
- Install the agent (
AWS-ConfigureAWSPackage or package manager)
- Create a configuration (wizard
amazon-cloudwatch-agent-config-wizard) and store it in Parameter Store
- Start the agent with the config (
AmazonCloudWatch-ManageAgent document, or State Manager association for the whole fleet)
- Check metrics in namespace
CWAgent and logs in the log group
json
{
"agent": {"metrics_collection_interval": 60, "run_as_user": "cwagent"},
"metrics": {
"append_dimensions": {"AutoScalingGroupName": "${aws:AutoScalingGroupName}", "InstanceId": "${aws:InstanceId}"},
"metrics_collected": {
"mem": {"measurement": ["mem_used_percent"]},
"swap": {"measurement": ["swap_used_percent"]},
"disk": {"measurement": ["used_percent"], "resources": ["/", "/data"]}
}
},
"logs": {"logs_collected": {"files": {"collect_list": [
{"file_path": "/var/log/messages", "log_group_name": "/prod/web/messages", "log_stream_name": "{instance_id}"},
{"file_path": "/var/log/nginx/error.log", "log_group_name": "/prod/web/nginx-error", "log_stream_name": "{instance_id}", "retention_in_days": 30}
]}}}
}
bash
sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -a fetch-config -m ec2 -c ssm:/cwagent/web -s
sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -m ec2 -a status
tail -f /opt/aws/amazon-cloudwatch-agent/logs/amazon-cloudwatch-agent.log
| Agent not sending data? | Check |
| Permission errors | Instance role lacks CloudWatchAgentServerPolicy |
| Network | Outbound HTTPS to CloudWatch endpoints: NAT or VPC endpoints monitoring and logs |
| Config | JSON syntax, wrong file path, agent not restarted after changes |
| Wrong dimensions in alarms | Alarm dimensions must match exactly (for example including InstanceId, path, device, fstype for disk metrics) |
Custom Metrics
bash
aws cloudwatch put-metric-data --namespace Shop --metric-name OrdersPerMinute --dimensions Service=checkout --value 42 --unit Count
aws cloudwatch put-metric-data --namespace Shop --metric-name QueueLag --value 3 --storage-resolution 1 # high resolutio
- Custom metrics cost per metric per month, and unique dimension combinations multiply cost. Avoid high-cardinality dimensions (user id, request id)
- Embedded Metric Format (EMF): write structured JSON logs and CloudWatch extracts metrics from them (great for Lambda and containers)
- Use
--unit and statistic sets to publish many values efficiently
Alarms
| Concept | Meaning |
| States | OK, ALARM, INSUFFICIENT_DATA |
| Period / evaluation periods / datapoints to alarm | Alarm when M out of N datapoints breach (for example 3 out of 5) to avoid flapping |
| Threshold type | Static, or anomaly detection band |
| Treat missing data | missing (keep state), notBreaching, breaching, ignore. Choose based on the metric (a stopped server may stop sending data, so use breaching for heartbeat metrics) |
| Actions | SNS, Auto Scaling, EC2 actions (stop, terminate, reboot, recover), Systems Manager OpsItem/Incident, Lambda via SNS/EventBridge |
| Alarm action on state change | Can run on ALARM, OK and INSUFFICIENT_DATA |
bash
aws cloudwatch put-metric-alarm --alarm-name web-cpu-high --namespace AWS/EC2 --metric-name CPUUtilization \
--dimensions Name=AutoScalingGroupName,Value=web-asg --statistic Average --period 300 --evaluation-periods 5 --datapoints-to-alarm 3 \
--threshold 80 --comparison-operator GreaterThanThreshold --treat-missing-data notBreaching \
--alarm-actions arn:aws:sns:ap-south-1:111111111111:ops-alerts --ok-actions arn:aws:sns:ap-south-1:111111111111:ops-alerts
aws cloudwatch describe-alarms --state-value ALARM --query 'MetricAlarms[].[AlarmName,StateReason]'
aws cloudwatch set-alarm-state --alarm-name web-cpu-high --state-value ALARM --state-reason "test" # test actions
aws cloudwatch describe-alarm-history --alarm-name web-cpu-high --history-item-type StateUpdate
Composite Alarms, Anomaly Detection and Metric Math
- Composite alarm: combine alarms with
AND, OR, NOT to reduce noise. Example: alert only when ALARM(cpu-high) AND ALARM(latency-high). You can suppress child actions
- Anomaly detection: ML learns normal patterns (daily and weekly seasonality) and alarms when values leave the expected band. Good for traffic that varies by time
- Metric math: calculate across metrics: error rate =
100 * errors / requests, sum across instances, FILL() missing values. Alarms can use metric math
- Metrics Insights: SQL-like query across many metrics (for example top 10 instances by CPU)
text
# Metrics Insights example
SELECT AVG(CPUUtilization) FROM SCHEMA("AWS/EC2", InstanceId) GROUP BY InstanceId ORDER BY AVG() DESC LIMIT 10
# Metric math: error rate percent
e1 = HTTPCode_Target_5XX_Count
e2 = RequestCount
e3 = 100 * (e1 / e2)
Dashboards and Sharing
- Dashboards are global, mix widgets from any Region, include metrics, logs, alarms and text. Create with console or
put-dashboard JSON (store in CloudFormation)
- Automatic dashboards exist for each service
- Share read-only with a link, SSO or public (careful)
- Cross-account and cross-Region observability (OAM): link source accounts to a monitoring account to see metrics, logs and traces in one place
- Metric streams: near real-time stream to Firehose → S3 or third-party tools
Retention and Cost Control
- Metrics expire by age automatically. Log groups default to never expire, so set retention
- Disable unneeded detailed monitoring and unused custom metrics
- Use Alarm and dashboard naming standards and tags
- Check billing metrics (
AWS/Billing in us-east-1) for charge alarms
Alarm Design Tips
- Alert on symptoms users feel (error rate, latency, saturation) before low-level causes
- Use M out of N and composite alarms to avoid alert fatigue
- Every alarm needs an owner, a runbook link (put in description) and a severity
- Test alarms with
set-alarm-state and confirm SNS subscriptions are confirmed
Practice Tasks
- Install the CloudWatch agent through SSM and see
mem_used_percent
- Create a disk usage alarm using the agent's metric dimensions
- Build a composite alarm that needs CPU and latency both high
- Create an anomaly detection alarm on request count
- Build a dashboard with an alarm widget, a metric math widget and a Logs Insights widget
Conclusion
CloudWatch gives default metrics but not memory or disk, so use the unified agent with a config in Parameter Store. Design alarms with M-out-of-N, correct missing-data treatment, composite alarms and anomaly detection, send actions to SNS, Auto Scaling or EC2, and build dashboards across Regions and accounts.
Quick Summary: metrics; default metrics; agent; custom metrics; alarms; composite and anomaly; dashboards; cost; tips.