Explain it simply
Think of driving a car
Metrics are the gauges on a car dashboard — speed, fuel, engine temperature, numbers that change over time. One glance tells you whether something is wrong, which makes them ideal for alarms. Logs are the trip diary — every detail written down, but slow to read in full.
Traces are the GPS route of a single trip — how one request travelled through your services and where it spent its time. Observability is combining all three so you get from 'what is broken' to 'why' quickly.
Problem → Why → Solution
Forty alarms, and the real incident was missed
The checkout team has 40 alarms on CPU, memory, disk and queue depth. On-call gets woken up around 30 times a night for 'CPU > 80%' — and none of those pages affected a single customer. So engineers start ignoring pages.
Then the real incident arrives: the payment provider is throttling, so checkout requests take 8 seconds and time out. CPU is low because functions are just waiting, so no alarm fires. The team learns about it from customers complaining on social media, then spends over an hour scrolling unstructured text across six log groups in the console to find the cause.
# A "cause" alarm: one noisy datapoint pages a human
aws cloudwatch put-metric-alarm \
--alarm-name web-1-cpu-high \
--namespace AWS/EC2 --metric-name CPUUtilization \
--dimensions Name=InstanceId,Value=i-0a1b2c3d4e5f67890 \
--statistic Average --period 60 \
--evaluation-periods 1 --threshold 80 \
--comparison-operator GreaterThanThreshold \
--alarm-actions arn:aws:sns:us-east-1:111122223333:oncall-pageAlerting on causes, blind to symptoms
High CPU is only a possible cause; customers never see CPU — they see latency and errors. Single-datapoint cause alarms create noise, and with no symptom alarm, a new cause (dependency throttling) is completely invisible.
Three signals, three alarm styles, one objective
- SLO (service level objective)
- A target for an SLI (for example 'percentage of checkout requests that finish under 300 ms without a 5xx') over a time window — for example 99.9% over 28 days.
Use each signal for its strength. Metrics are numbers aggregated over time, cheap to store and fast to alarm on, but they lose per-request detail. Logs keep the full context of each event but are expensive to ingest at volume and are queried after the fact. Traces follow one request across services as spans and show where latency comes from.
CloudWatch alarms come in three styles. A static threshold alarm compares against a fixed line such as 'p99 latency > 1500 ms', and using 'M out of N datapoints' stops a single spike from firing it. An anomaly detection alarm learns a metric's daily and weekly pattern from history, draws an expected band, and fires when the value leaves the band — good for metrics with normal traffic swings.
A composite alarm is a rule that combines other alarms with AND, OR and NOT. Child alarms carry no actions and only the composite pages, so one incident produces one notification.
CloudWatch Logs Insights is a piped query language (fields, filter, stats, sort, parse) billed per GB scanned; logs written as JSON have their fields discovered automatically. Embedded Metric Format (EMF) builds on that: write one JSON log line with _aws metadata and CloudWatch extracts metrics asynchronously, with no PutMetricData calls. High-cardinality fields such as orderId stay in the log for queries without becoming dimensions.
For tracing, AWS X-Ray propagates a trace ID (the X-Amzn-Trace-Id header or a W3C traceparent) across services and draws a service map and span timeline. For new instrumentation AWS recommends an OpenTelemetry-based approach such as AWS Distro for OpenTelemetry (ADOT). Finally, tie it all to an SLO: the SLI measures what users feel, the SLO sets the target, and the error budget (100% minus the SLO) says how much 'failure' you can still afford. CloudWatch Application Signals lets you define such SLOs directly in the console for supported workloads.
| Signal | Best for | Main cost driver |
|---|---|---|
| Metrics | Alarms, trends, dashboards | Number of metrics (dimension combinations) |
| Logs | Per-event context, debugging | GB ingested and GB scanned |
| Traces | Where latency comes from across services | Traces recorded/scanned (sampling) |
FROM SIGNALS TO ONE PAGE
------------------------
[Lambda / ECS / ALB]
| EMF JSON log lines | spans (ADOT / X-Ray)
v v
[CloudWatch Logs] --extract--> [Metrics] [X-Ray traces]
| | |
| Logs Insights +-----+------+ |
| (why?) v v |
| [p99 latency] [5xx rate] |
| static alarm anomaly alarm |
| \ / |
| [composite alarm: OR] |
| | |
+------------------> on-call page <---------------+
(runbook links logs + traces)- Alarm on what users feel (SLI)
- Composite alarm sends one page
- Metrics show when and how much
- Traces show where
- Logs show why
Page on symptoms, debug with causes. Keep cause metrics such as CPU on the dashboard — not on the pager.
The shape of a Logs Insights query
fields @timestamp, @duration
| filter @type = "REPORT"
| stats avg(@duration) as avgMs,
pct(@duration, 99) as p99Ms,
count(*) as invocations
by bin(5m)
| sort @timestamp descA query is a chain of commands joined by '|': fields picks columns, filter keeps rows, stats aggregates, and by bin(5m) groups into 5-minute buckets. Lambda REPORT lines carry @duration, @maxMemoryUsed and, on cold starts, @initDuration.
A Lambda that emits business metrics with EMF
Lambda and API Gateway already provide latency and error rate as built-in metrics. What you must emit yourself are business signals — order value, item count, payment declines. This function prints one EMF line per order; CloudWatch extracts three metrics from it, while orderId and customerId stay in the log for Logs Insights. The payment call is assumed to have happened already, and its result is passed in the event.
import json
NAMESPACE = "Shop/Checkout"
DIMENSION_SETS = [["Service"], ["Service", "PaymentMethod"]]
def emf_line(timestamp_ms, dimensions, metrics, properties):
"""Build one CloudWatch Embedded Metric Format (EMF) log line."""
record = {
"_aws": {
"Timestamp": timestamp_ms,
"CloudWatchMetrics": [
{
"Namespace": NAMESPACE,
"Dimensions": DIMENSION_SETS,
"Metrics": [{"Name": n, "Unit": u} for n, (_, u) in metrics.items()],
}
],
}
}
record.update(dimensions)
record.update({n: v for n, (v, _) in metrics.items()})
record.update(properties)
return json.dumps(record)
def lambda_handler(event, context):
order = json.loads(event["body"])
approved = order["paymentStatus"] == "approved"
total = round(sum(i["price"] * i["qty"] for i in order["items"]), 2)
print(
emf_line(
event["requestContext"]["timeEpoch"],
{"Service": "checkout", "PaymentMethod": order["paymentMethod"]},
{
"OrderValue": (total if approved else 0, "None"),
"ItemCount": (sum(i["qty"] for i in order["items"]), "Count"),
"Declined": (0 if approved else 1, "Count"),
},
{"orderId": order["orderId"], "customerId": order["customerId"]},
)
)
return {"statusCode": 201 if approved else 402}
if __name__ == "__main__":
for n, status in enumerate(["approved", "declined"], start=1):
order = {
"orderId": f"ord-100{n}",
"customerId": "cus-42",
"paymentMethod": "card",
"paymentStatus": status,
"items": [{"price": 19.99, "qty": 2}, {"price": 5.0, "qty": 1}],
}
event = {
"requestContext": {"timeEpoch": 1794096000000},
"body": json.dumps(order),
}
print(lambda_handler(event, None))Not runnable in the browser
This code runs against a real AWS account, so it cannot run in the browser playground. Try it in your own terminal or in AWS CloudShell.
Code breakdown
- The _aws metadata block
"_aws": {"Timestamp": timestamp_ms, "CloudWatchMetrics": [...]}This block is what makes CloudWatch Logs treat the line as EMF. Timestamp is a millisecond epoch — here the request time from requestContext.timeEpoch. Namespace, Dimensions and Metrics say which top-level fields become metrics.
- Dimension sets
DIMENSION_SETS = [["Service"], ["Service", "PaymentMethod"]]Each dimension set creates its own metrics: one with just Service (the overall total) and one per payment method. Every custom metric is billed, so keep the number of sets small.
- Properties are not dimensions
{"orderId": order["orderId"], "customerId": order["customerId"]}orderId and customerId are not dimensions — if they were, every order would create new metrics and the bill would explode. They stay in the log, so 'declined orders for this customer' is still one Logs Insights query away.
- print() is the transport
print(emf_line(...))In Lambda, stdout goes straight to CloudWatch Logs, so there is no API call and no added synchronous latency. In production, the Metrics utility of Powertools for AWS Lambda produces this format for you.
{"_aws": {"Timestamp": 1794096000000, "CloudWatchMetrics": [{"Namespace": "Shop/Checkout", "Dimensions": [["Service"], ["Service", "PaymentMethod"]], "Metrics": [{"Name": "OrderValue", "Unit": "None"}, {"Name": "ItemCount", "Unit": "Count"}, {"Name": "Declined", "Unit": "Count"}]}]}, "Service": "checkout", "PaymentMethod": "card", "OrderValue": 44.98, "ItemCount": 3, "Declined": 0, "orderId": "ord-1001", "customerId": "cus-42"}
{'statusCode': 201}
{"_aws": {"Timestamp": 1794096000000, "CloudWatchMetrics": [{"Namespace": "Shop/Checkout", "Dimensions": [["Service"], ["Service", "PaymentMethod"]], "Metrics": [{"Name": "OrderValue", "Unit": "None"}, {"Name": "ItemCount", "Unit": "Count"}, {"Name": "Declined", "Unit": "Count"}]}]}, "Service": "checkout", "PaymentMethod": "card", "OrderValue": 0, "ItemCount": 3, "Declined": 1, "orderId": "ord-1002", "customerId": "cus-42"}
{'statusCode': 402}Alarms that page on symptoms
Create child alarms with no actions — a static p99 latency alarm, a 5xx alarm, and a low-traffic alarm that tells you when percentiles are unreliable at night. Then a single composite alarm does the paging. The '3 out of 5' datapoint rule ignores a single spike.
aws cloudwatch put-metric-alarm \
--alarm-name checkout-p99-latency \
--namespace AWS/ApiGateway --metric-name Latency \
--dimensions Name=ApiName,Value=shop-api \
--extended-statistic p99 --period 60 \
--evaluation-periods 5 --datapoints-to-alarm 3 \
--threshold 1500 --comparison-operator GreaterThanThreshold \
--treat-missing-data notBreaching
aws cloudwatch put-metric-alarm \
--alarm-name checkout-5xx-rate \
--namespace AWS/ApiGateway --metric-name 5XXError \
--dimensions Name=ApiName,Value=shop-api \
--statistic Average --period 60 \
--evaluation-periods 5 --datapoints-to-alarm 3 \
--threshold 0.02 --comparison-operator GreaterThanThreshold \
--treat-missing-data notBreaching
aws cloudwatch put-metric-alarm \
--alarm-name checkout-low-traffic \
--namespace AWS/ApiGateway --metric-name Count \
--dimensions Name=ApiName,Value=shop-api \
--statistic Sum --period 300 --evaluation-periods 1 \
--threshold 50 --comparison-operator LessThanThreshold
# Only this one has an action: one incident, one page
RULE='(ALARM("checkout-p99-latency") OR ALARM("checkout-5xx-rate"))'
RULE="$RULE"' AND NOT ALARM("checkout-low-traffic")'
aws cloudwatch put-composite-alarm \
--alarm-name checkout-customer-impact \
--alarm-rule "$RULE" \
--alarm-actions arn:aws:sns:us-east-1:111122223333:oncall-page \
--alarm-description "Runbook: https://wiki.example.com/runbooks/checkout"Average of 5XXError is a rate
API Gateway's 5XXError is 0 or 1 per request, so the Average statistic is the error rate directly (0.02 = 2%). Sum would rise naturally with traffic and miss problems when traffic is low.
Keep the dashboard as code too. Put the composite alarm state at the top and business metrics below it, so on-call sees 'are customers affected?' and 'how much?' at a glance.
{
"widgets": [
{
"type": "alarm",
"x": 0, "y": 0, "width": 24, "height": 2,
"properties": {
"title": "Customer impact",
"alarms": [
"arn:aws:cloudwatch:us-east-1:111122223333:alarm:checkout-customer-impact"
]
}
},
{
"type": "metric",
"x": 0, "y": 2, "width": 12, "height": 6,
"properties": {
"title": "Items ordered and declines (5 min sum)",
"region": "us-east-1",
"stat": "Sum",
"period": 300,
"metrics": [
["Shop/Checkout", "ItemCount", "Service", "checkout"],
["Shop/Checkout", "Declined", "Service", "checkout"]
]
}
}
]
}aws cloudwatch put-dashboard \
--dashboard-name checkout \
--dashboard-body file://dashboard.jsonFinding the 'why' with Logs Insights
When a page arrives, the first query asks 'how bad is it' and the second 'who is affected'. EMF logs are JSON, so Declined, PaymentMethod and customerId can be filtered and grouped directly. Cold starts can be counted with @initDuration on REPORT lines.
filter Service = "checkout"
| stats sum(Declined) as declined, count(*) as orders by PaymentMethod
| sort declined descfilter @type = "REPORT" and ispresent(@initDuration)
| stats count(*) as coldStarts, avg(@initDuration) as avgInitMs by bin(1h)QUERY_ID=$(aws logs start-query \
--log-group-name /aws/lambda/checkout \
--start-time "$(date -d '1 hour ago' +%s)" --end-time "$(date +%s)" \
--query-string 'filter Declined = 1 | stats count(*) by customerId | limit 10' \
--query queryId --output text)
aws logs get-query-results --query-id "$QUERY_ID"
# Turn on tracing for the function (X-Ray active tracing)
aws lambda update-function-configuration \
--function-name checkout --tracing-config Mode=ActiveSLOs and error budgets
A 99.9% SLO over 28 days gives an error budget of 0.1% of requests — with 10 million requests a month, up to 10,000 'bad' requests are allowed. Alerting on burn rate (how fast the budget is being spent) beats a fixed threshold: fast burn pages, slow burn opens a ticket. What matters most is the team agreeing in advance that a nearly spent budget pauses feature releases in favor of reliability work.
In production
How production teams run it
Each service has a dashboard with the four golden signals (latency, traffic, errors, saturation) and one owning team. Every paging alarm's description links a runbook, and the runbook contains ready-made Logs Insights queries and trace filters, so on-call at 3 a.m. never writes a query from scratch.
Multi-account organizations use CloudWatch cross-account observability so one monitoring account can see metrics, logs and traces from every workload account. To control log cost they set retention on every log group, turn off DEBUG logging in production, and sample a percentage of traces rather than all of them. SLOs are reviewed in a weekly reliability meeting, and a spent error budget means the next sprint goes to reliability work.
Synthetic checks (CloudWatch Synthetics canaries) help too: they exercise the login and checkout paths every few minutes, even at night with no traffic, so you know something is broken before users report it.
Common mistakes
Common mistakes
Paging on cause metrics
Paging on CPU, memory or queue depth wakes people for problems that do not hurt customers, while incidents with a new cause slip through. Page on symptoms — latency, error rate, success rate — and keep cause metrics on the debugging dashboard.
Using high-cardinality values as dimensions
Putting userId, orderId or requestId into EMF dimensions turns every unique value into a new, separately billed custom metric. Keep them as ordinary properties and query them with Logs Insights.
Leaving log retention at 'never expire'
New log groups default to 'Never expire'. A few years later you are paying storage for terabytes of debug logs nobody reads. Always set retention in the IaC that creates the log group.
Never testing the alarms
An alarm with a misspelled dimension name sits in INSUFFICIENT_DATA forever and never fires. Test the notification path with aws cloudwatch set-alarm-state, and regularly review alarms that stay in INSUFFICIENT_DATA.
💰 Cost & Cleanup
The main CloudWatch cost drivers are: each custom metric (each dimension combination) per month, each alarm (anomaly detection and high-resolution alarms cost more), GB of logs ingested (usually the largest), log storage per GB-month, and GB scanned by Logs Insights. X-Ray bills per trace recorded and retrieved/scanned. The free tier includes a small number of metrics, alarms and log GB — check the pricing page for exact amounts.
After the lab, delete the alarms (composite first), the dashboard and the test log group.
Clean up when you are done
aws cloudwatch delete-alarms --alarm-names checkout-customer-impact
aws cloudwatch delete-alarms \
--alarm-names checkout-p99-latency checkout-5xx-rate checkout-low-traffic \
checkout-declines-anomaly
aws cloudwatch delete-dashboards --dashboard-names checkout
aws logs delete-log-group --log-group-name /aws/lambda/checkoutMini challenge
An anomaly detection alarm for payment declines
Declines are high in the day and low at night, so a static threshold does not work. Create an anomaly detection alarm on the Declined metric (Service=checkout) in Shop/Checkout.
- Use a 5-minute period and the Sum statistic
- Use a band width of 2 standard deviations
- Alarm only above the upper band (fewer declines is not a problem)
- Treat missing data as not breaching
Expected: describe-alarms shows checkout-declines-anomaly with ThresholdMetricId ad1, and the console graph shows a shaded band (the model needs enough history before the band appears).
Show hint
Put two entries in --metrics — the metric query (m1) and the expression ANOMALY_DETECTION_BAND(m1, 2) (ad1) — then use --threshold-metric-id ad1 with the GreaterThanUpperThreshold comparison operator.
Show solution
cat > declines-metrics.json <<'EOF'
[
{
"Id": "m1",
"ReturnData": true,
"MetricStat": {
"Metric": {
"Namespace": "Shop/Checkout",
"MetricName": "Declined",
"Dimensions": [{ "Name": "Service", "Value": "checkout" }]
},
"Period": 300,
"Stat": "Sum"
}
},
{ "Id": "ad1", "Expression": "ANOMALY_DETECTION_BAND(m1, 2)", "ReturnData": true }
]
EOF
aws cloudwatch put-metric-alarm \
--alarm-name checkout-declines-anomaly \
--metrics file://declines-metrics.json \
--threshold-metric-id ad1 \
--comparison-operator GreaterThanUpperThreshold \
--evaluation-periods 3 --datapoints-to-alarm 2 \
--treat-missing-data notBreaching \
--alarm-actions arn:aws:sns:us-east-1:111122223333:oncall-ticketQuick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Metrics = when and how much, traces = where, logs = why
- Page on symptoms (latency, errors) and reduce noise with M-of-N datapoints and composite alarms
- Anomaly detection suits metrics with normal swings; static thresholds suit clear limits
- EMF turns log lines into metrics — never make high-cardinality IDs dimensions
- SLOs and error budgets make 'how reliable is reliable enough' an explicit team agreement
Amazon CloudWatch User Guide — AWS Documentation
CloudWatch Logs Insights query syntax — AWS Documentation
AWS X-Ray Developer Guide — AWS Documentation