Amazon CloudWatch Metrics, Alarms and the CloudWatch Agent: Dashboards, Composite Alarms and Anomaly Detection

AWS SysOps Associate 55 min min read Updated: Nov 17, 2026 Intermediate
Amazon CloudWatch Metrics, Alarms and the CloudWatch Agent: Dashboards, Composite Alarms and Anomaly Detection
Intermediate Topic 1 of 4

Metrics Basics

TermMeaning
NamespaceContainer such as AWS/EC2, AWS/RDS, CWAgent or your own
MetricTime-ordered data points, for example CPUUtilization
DimensionName/value pair that identifies a series (InstanceId=i-0abc). Each unique combination is a separate metric
StatisticAverage, Sum, Min, Max, SampleCount, percentiles (p99)
PeriodAggregation window in seconds (60 or multiples). High-resolution custom metrics go down to 1 second
Retention1 s data for 3 hours, 1 min for 15 days, 5 min for 63 days, 1 hour for 455 days (15 months)
RegionalMetrics live in one Region. Use cross-Region dashboards or metric streams to combine

Default Metrics You Must Know

ServiceIncluded metricsNOT included by default
EC2CPUUtilization, NetworkIn/Out, DiskReadOps/WriteOps (instance store), StatusCheckFailed, CPUCreditBalance. 5-minute basic, 1-minute with detailed monitoringMemory, disk space, swap, processes. Use the CloudWatch agent
EBSVolumeReadOps, VolumeQueueLength, BurstBalanceFile system usage
ELBRequestCount, TargetResponseTime, HTTPCode_*, HealthyHostCount
RDSCPUUtilization, FreeStorageSpace, DatabaseConnections, ReplicaLagOS detail (use Enhanced Monitoring)
LambdaInvocations, Errors, Duration, ThrottlesMemory 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.

  1. Attach an IAM role with CloudWatchAgentServerPolicy (and SSM managed core if you use SSM)
  2. Install the agent (AWS-ConfigureAWSPackage or package manager)
  3. Create a configuration (wizard amazon-cloudwatch-agent-config-wizard) and store it in Parameter Store
  4. Start the agent with the config (AmazonCloudWatch-ManageAgent document, or State Manager association for the whole fleet)
  5. 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 errorsInstance role lacks CloudWatchAgentServerPolicy
NetworkOutbound HTTPS to CloudWatch endpoints: NAT or VPC endpoints monitoring and logs
ConfigJSON syntax, wrong file path, agent not restarted after changes
Wrong dimensions in alarmsAlarm 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

ConceptMeaning
StatesOK, ALARM, INSUFFICIENT_DATA
Period / evaluation periods / datapoints to alarmAlarm when M out of N datapoints breach (for example 3 out of 5) to avoid flapping
Threshold typeStatic, or anomaly detection band
Treat missing datamissing (keep state), notBreaching, breaching, ignore. Choose based on the metric (a stopped server may stop sending data, so use breaching for heartbeat metrics)
ActionsSNS, Auto Scaling, EC2 actions (stop, terminate, reboot, recover), Systems Manager OpsItem/Incident, Lambda via SNS/EventBridge
Alarm action on state changeCan 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

  1. Install the CloudWatch agent through SSM and see mem_used_percent
  2. Create a disk usage alarm using the agent's metric dimensions
  3. Build a composite alarm that needs CPU and latency both high
  4. Create an anomaly detection alarm on request count
  5. 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.

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators