SkillSprout
Chapter 5 · Lesson 1
Intermediate
6 min read

CloudWatch Metrics, Alarms and Synthetic Monitoring

Overview

Amazon CloudWatch is the central observability service for AWS. It collects metrics (numbers over time), lets you create alarms that trigger actions, draws dashboards and, together with Logs and X-Ray, answers the question "is my system healthy, and if not, why?".

Think of the dashboard of a car: speed, fuel and engine temperature are metrics; the warning lights are alarms; and the black-box recorder is logs. A good driver (or SRE) watches a small set of meaningful gauges and gets warnings that matter, not a siren every minute.

DOP-C02 tests how metrics are published (agent, custom, Embedded Metric Format), alarm evaluation (periods, datapoints to alarm, missing data), composite alarms, anomaly detection, metric math and automated alarm actions such as EC2 recovery, Auto Scaling and Systems Manager OpsItems.

Key Concepts

  • Default AWS metrics are 1 or 5 minute (detailed monitoring = 1 minute); custom metrics can be high resolution down to 1 second.
  • EC2 metrics exclude memory and disk usage; install the unified CloudWatch agent to publish them (and logs).
  • An alarm has period, evaluation periods, datapoints to alarm (M out of N) and treat missing data setting.
  • Alarm actions: SNS, Auto Scaling, EC2 (stop, terminate, reboot, recover), Systems Manager (OpsItem, incident) and Lambda via SNS/EventBridge.
  • Composite alarms combine alarm states with AND/OR/NOT logic to cut noise.
  • Anomaly detection builds an ML band for a metric; metric math computes expressions such as error rate = errors / requests.
  • Embedded Metric Format (EMF) lets applications emit metrics inside structured log lines, extracted asynchronously without PutMetricData calls.
  • CloudWatch Synthetics canaries run scripts on a schedule to test endpoints and user journeys; Application Signals adds SLO-based service monitoring.

Detailed Notes

Where metrics come from

SourceExamplesNotes
AWS servicesCPUUtilization, RequestCount, ErrorsAutomatic; some need enabling
Unified CloudWatch agentmem_used_percent, disk_used_percent, procstatConfig in SSM Parameter Store
PutMetricData APIBusiness metricsDimensions up to 30; per-metric cost
Embedded Metric FormatLambda and container appsMetrics extracted from logs
Metric StreamsNear-real-time export to Firehose / third partiesUse for external observability

Alarm evaluation

bash
aws cloudwatch put-metric-alarm --alarm-name api-5xx-rate \
  --metrics '[
    {"Id":"e1","Expression":"errors/requests*100","Label":"5xxRate","ReturnData":true},
    {"Id":"errors","MetricStat":{"Metric":{"Namespace":"AWS/ApplicationELB","MetricName":"HTTPCode_Target_5XX_Count","Dimensions":[{"Name":"LoadBalancer","Value":"app/web/abc"}]},"Period":60,"Stat":"Sum"},"ReturnData":false},
    {"Id":"requests","MetricStat":{"Metric":{"Namespace":"AWS/ApplicationELB","MetricName":"RequestCount","Dimensions":[{"Name":"LoadBalancer","Value":"app/web/abc"}]},"Period":60,"Stat":"Sum"},"ReturnData":false}]' \
  --comparison-operator GreaterThanThreshold --threshold 2 \
  --evaluation-periods 5 --datapoints-to-alarm 3 \
  --treat-missing-data notBreaching --alarm-actions $TOPIC_ARN

States are OK, ALARM and INSUFFICIENT_DATA. datapoints-to-alarm 3 of evaluation-periods 5 means 3 breaching points in the last 5 periods. Treat missing data: notBreaching (good for sparse metrics), breaching, ignore, missing. High-resolution alarms can evaluate at 10 or 30 second periods.

Composite alarms

bash
aws cloudwatch put-composite-alarm --alarm-name checkout-down \
  --alarm-rule "ALARM(api-5xx-rate) AND (ALARM(db-cpu-high) OR ALARM(queue-age-high))" \
  --alarm-actions $PAGER_TOPIC

Page on the composite only; child alarms have no actions. This avoids alert storms and can suppress actions during maintenance with an actions suppressor alarm.

Embedded Metric Format

json
{
  "_aws": {
    "Timestamp": 1735000000000,
    "CloudWatchMetrics": [{
      "Namespace": "Orders",
      "Dimensions": [["Service", "Region"]],
      "Metrics": [{ "Name": "OrderLatency", "Unit": "Milliseconds" }]
    }]
  },
  "Service": "checkout", "Region": "us-east-1",
  "OrderLatency": 183, "orderId": "o-9981"
}

In Lambda, printing this JSON to stdout creates the metric with no API call and no added latency, while orderId stays searchable in Logs Insights as high-cardinality context.

Anomaly detection

An anomaly detection alarm uses ANOMALY_DETECTION_BAND(m1, 2) and compares the metric to the expected band, ideal for seasonal traffic where static thresholds would be wrong. It needs a training period and can exclude time ranges such as deployments.

EC2 automatic actions

  • Auto recovery: alarm on StatusCheckFailed_System with action arn:aws:automate:region:ec2:recover moves the instance to healthy hardware, keeping IP, ID and EBS volumes (EBS-backed only).
  • Instance reboot for StatusCheckFailed_Instance.
  • Cross-account alarms: composite alarms can reference alarms in other accounts; use cross-account observability (OAM) to view metrics from source accounts in a monitoring account.

Synthetic monitoring

Canaries (Node.js or Python with Puppeteer/Selenium) run every minute to 'any cron', verify endpoints, broken links or journeys and emit SuccessPercent metrics, with alarms. They detect issues before users do, including from outside the VPC or inside it.

Dashboards and anomalies

Dashboards can be cross-account and cross-Region, and shared via links or SSO. Use Contributor Insights for top-N analysis from logs (top talkers, noisy tenants) and Application Signals / SLOs for burn-rate alarms.

SLO and alert design

Alert on symptoms (error rate, latency percentile, saturation) rather than causes. Use p99/p95 statistics, and tie each alarm to a runbook (SSM Automation or OpsCenter) for repeatable response.

Alarm engineering details

SettingGuidance
Period and EvaluationPeriodsUse "M out of N" datapoints (for example 3 of 5) to avoid flapping
TreatMissingDatanotBreaching for sparse metrics, breaching for heartbeat metrics
Statisticp99/p95 for latency, Sum or Average for errors, never Average alone for tail latency
ActionsSNS, Auto Scaling, EC2 actions (stop, terminate, recover, reboot), Systems Manager OpsItem or Incident Manager response plan
Composite alarmCombine child alarms with AND/OR/NOT to reduce noise and suppress during maintenance
Anomaly detection bandModel seasonality for traffic with daily or weekly patterns
bash
aws cloudwatch put-metric-alarm --alarm-name api-errors --namespace AWS/ApplicationELB \
  --metric-name HTTPCode_Target_5XX_Count --dimensions Name=LoadBalancer,Value=app/web/abc123 \
  --statistic Sum --period 60 --evaluation-periods 5 --datapoints-to-alarm 3 \
  --threshold 20 --comparison-operator GreaterThanThreshold --treat-missing-data notBreaching \
  --alarm-actions arn:aws:sns:us-east-1:111122223333:oncall

Cross-account and cross-Region dashboards and alarms use CloudWatch cross-account observability (monitoring accounts and Observability Access Manager links), so one account sees metrics, logs and traces from many source accounts.

Real World Example

Scenario: a booking platform drowns in alerts. Every instance had CPU, memory and disk alarms that paged on-call at night. The team replaces them with symptom-based alarms: ALB 5XX rate via metric math, p99 latency, and SQS oldest message age. A composite alarm pages only when errors and latency breach together.

Lambda functions emit EMF metrics for business KPIs (bookings per minute) with anomaly detection bands that handle weekday patterns. A canary tests the full booking journey every minute from three Regions. Pages drop 80% and detection time improves.

Architecture Diagram

Metrics, alarms and automated actions
Architecture
AWS Cloud

Sources

EC2 + agent
Lambda EMF
Canary
Metricsmetric math
Composite alarm

Actions

SNS page
Scale / recover
SSM runbook

Telemetry flows into CloudWatch; alarms trigger people and automation.

  1. 1Services, the agent, EMF logs and canaries publish metrics.
  2. 2Metric math derives symptom metrics such as error rate.
  3. 3Child alarms evaluate M-of-N datapoints and handle missing data.
  4. 4A composite alarm combines them to reduce noise.
  5. 5Actions notify on-call, scale capacity or start an automation runbook.

Best Practices

  • ✓Alert on symptoms (errors, latency, saturation) and tie alarms to runbooks.
  • ✓Use composite alarms to reduce noise and an actions suppressor during maintenance.
  • ✓Install the unified agent for memory, disk and logs, and manage its config in SSM.
  • ✓Use EMF for high-volume custom metrics and keep dimensions low-cardinality.
  • ✓Choose treat missing data deliberately for sparse metrics.

Common Interview Questions

Exam Tips

DOP-C02 focus

  • Memory/disk metrics = CloudWatch agent (custom metrics).
  • "Reduce alert noise" = composite alarms; "seasonal baseline" = anomaly detection.
  • "Custom metrics from Lambda without API calls" = Embedded Metric Format.
  • Sparse metric flapping to INSUFFICIENT_DATA = adjust treat missing data.

Finished this lesson?

0 of 44 lessons done · 0% of the course