Amazon CloudWatch
Amazon CloudWatch is the monitoring service of AWS. It collects metrics (numbers over time), logs (text lines) and events, lets you graph them on dashboards, and raises alarms that notify people or trigger automatic actions such as scaling.
| Feature | What it does |
|---|---|
| Metrics | Time series like CPUUtilization of an instance, grouped in namespaces (AWS/EC2) with dimensions (InstanceId) |
| Custom metrics | Your own numbers, e.g. orders per minute (PutMetricData) |
| Alarms | Watch a metric and change state: OK, ALARM, INSUFFICIENT_DATA |
| Logs | Log groups and streams from Lambda, ECS, EC2 (CloudWatch agent), API Gateway... |
| Logs Insights | A query language over logs |
| Dashboards | Graphs and numbers on one page |
| Synthetics / RUM | Canary scripts that test your site; real-user monitoring |
Most AWS services publish basic metrics automatically (EC2 at 5-minute intervals by default, 1-minute with detailed monitoring). Memory and disk usage inside an instance need the CloudWatch agent.
Creating an alarm
aws cloudwatch put-metric-alarm --alarm-name web-high-cpu \
--namespace AWS/EC2 --metric-name CPUUtilization \
--dimensions Name=AutoScalingGroupName,Value=web-asg \
--statistic Average --period 60 --evaluation-periods 5 --datapoints-to-alarm 3 \
--threshold 80 --comparison-operator GreaterThanThreshold \
--treat-missing-data missing \
--alarm-actions arn:aws:sns:eu-west-1:123456789012:ops-alerts
aws cloudwatch describe-alarms --alarm-names web-high-cpu --query "MetricAlarms[0].StateValue"Sample output:
"OK"Model: "M out of N" alarm evaluation
The alarm above goes to ALARM when 3 of the last 5 one-minute data points are above 80%. This avoids alerting on a single spike while still catching a real problem:
def evaluate(datapoints, threshold=80, n=5, m=3):
state = "INSUFFICIENT_DATA"
history = []
for i in range(len(datapoints)):
window = [d for d in datapoints[max(0, i - n + 1): i + 1] if d is not None]
if len(window) < m:
new_state = state # not enough data yet: keep the current state
else:
breaching = sum(d > threshold for d in window)
new_state = "ALARM" if breaching >= m else "OK"
if new_state != state:
history.append(f"minute {i}: {state} -> {new_state}")
state = new_state
return state, history
cpu = [35, 40, 95, 42, 38, 85, 91, 88, 60, 93, 97, 70, 50, 45, 40, 38]
final, changes = evaluate(cpu)
print("data:", cpu)
for line in changes:
print(" ", line)
print("final state:", final)data: [35, 40, 95, 42, 38, 85, 91, 88, 60, 93, 97, 70, 50, 45, 40, 38]
minute 2: INSUFFICIENT_DATA -> OK
minute 6: OK -> ALARM
minute 12: ALARM -> OK
final state: OK
The single spike at minute 2 doesn't trigger anything on its own. At minute 6 the last five points (minutes 2–6) contain three above 80% (95, 85 and 91), so the alarm fires (and an SNS notification is sent). It stays in ALARM while the load is high and returns to OK at minute 12, when only two of the last five points breach.
Model: statistics and percentiles
An alarm or graph uses a statistic over each period: Average, Sum, Minimum, Maximum, SampleCount or a percentile like p99. For latency, averages hide pain; percentiles show it:
import statistics
# response times (ms) of 20 requests in one minute
latencies = [42, 45, 39, 51, 48, 44, 40, 47, 43, 46, 41, 49, 44, 45, 1200, 43, 47, 980, 44, 46]
def percentile(values, p):
ordered = sorted(values)
k = max(0, int(round(p / 100 * len(ordered) + 0.5)) - 1) # nearest-rank method
return ordered[min(k, len(ordered) - 1)]
print(f"Average : {statistics.mean(latencies):7.1f} ms")
print(f"p50 : {percentile(latencies, 50):7} ms")
print(f"p90 : {percentile(latencies, 90):7} ms")
print(f"p99 : {percentile(latencies, 99):7} ms")
print(f"Maximum : {max(latencies):7} ms")Average : 149.2 ms
p50 : 45 ms
p90 : 51 ms
p99 : 1200 ms
Maximum : 1200 ms
The average suggests "a bit slow" and the median and p90 say "fine", but p99 and the maximum reveal that some users wait more than a second. (Only 2 of these 20 requests were slow, which is why even p90 hides them.) Alarm on p99 latency and on error rates, not only on CPU.
Logs and Logs Insights
aws logs tail /aws/lambda/orders --since 10m --follow
aws logs start-query --log-group-name /aws/lambda/orders \
--start-time 1772438400 --end-time 1772442000 \
--query-string 'fields @timestamp, @message | filter @message like /ERROR/ | stats count() by bin(5m)'Set a retention period on every log group (the default is to keep logs forever, and you pay for storage).
logs = """2026-03-02T10:00:01Z INFO order 41 created
2026-03-02T10:00:03Z ERROR payment declined order=42
2026-03-02T10:01:10Z INFO order 43 created
2026-03-02T10:02:45Z ERROR timeout calling inventory order=44
2026-03-02T10:02:59Z ERROR payment declined order=45
2026-03-02T10:03:30Z INFO order 46 created"""
# A metric filter turns log lines into a metric: count ERROR lines per minute
from collections import Counter
errors = Counter(line[:16] for line in logs.splitlines() if " ERROR " in line)
for minute, count in sorted(errors.items()):
print(f"{minute} ErrorCount={count}")
reasons = Counter(line.split(" ERROR ")[1].split(" order=")[0] for line in logs.splitlines() if " ERROR " in line)
print(reasons.most_common())2026-03-02T10:00 ErrorCount=1
2026-03-02T10:02 ErrorCount=2
[('payment declined', 2), ('timeout calling inventory', 1)]
Metric filters like this one turn log patterns into metrics that you can alarm on.
Test yourself
Which metric is NOT available for EC2 without the CloudWatch agent?
- CPUUtilization
- NetworkIn
- Memory utilisation
- StatusCheckFailed
An alarm uses 'datapoints to alarm' 3 out of 5. What does that achieve?
- It alarms on every spike
- It ignores short single spikes but catches sustained problems
- It checks every 5 seconds
- It disables the alarm
Why alarm on p99 latency instead of the average?
- It is cheaper
- Averages hide the slow requests that a minority of users experience
- Averages are not supported
- p99 is always lower