By the end you'll know
- What CloudWatch collects for free, and what you add yourself: metrics, logs, alarms and dashboards
- Three ways to turn what your code does into metrics, and when to use each
- How an alarm decides, and why it fires a minute or two after the problem starts
- Why a rate and a count disagree, and why percentiles beat averages
- How to query logs with Logs Insights, and what that costs
- The mistake that turns a cheap metric into an expensive one
Before you start
- You need: the
juniper-ryeprofile, signed in, and Lesson 20's virtual environment. Lesson 21 covers Lambda's logs, and Lesson 2 set up the budget alarm this lesson's alarms work like. - The script:
lab.pyfrom the practice folder'slesson-32. Everything it creates is namedjr-lesson32-*and taggedlesson=32, and itsdeletestep removes it. - Where you run things: your own machine, labeled (Your machine).
- Every output below is from a real run on November 15, 2026, at about 8pm in New York, which is just after midnight UTC.
CloudWatch is cheap until something multiplies
Each custom metric is $0.30 a month, and every different combination of dimension values is a separate metric. Put an order ID or a customer ID in a dimension and a busy service makes thousands of metrics, quietly. Logs are $0.50 per GB ingested and kept forever unless you set a retention. This lab stays far inside the free allowances; the "Spot the problem" section shows how a real one doesn't.
The short version
- Metrics are numbers over time; logs are lines of text; alarms watch metrics and act.
- AWS services publish their own metrics for free. You add custom ones from logs or code.
- Log in JSON, and both Logs Insights and metric filters can use every field.
- An alarm judges each period after it ends, so it fires a minute or two after the trouble starts.
- Alarm on rates and percentiles, not raw counts and averages.
What this lesson costs
| Part | Always-free allowance | This lab |
|---|---|---|
| Custom metrics | 10 | 3 |
| Alarm metrics | 10 | 4, in 3 alarms |
| Dashboards | 3 | 1 |
| Logs ingested, stored and scanned | 5 GB | About 120 KB |
| The function and the alarm topic | Lambda and SNS allowances | About 190 runs |
| This lesson | Nothing |
Three kinds of signal
When something goes wrong at 2am, you need to know three things: that something is wrong, how wrong, and why. CloudWatch keeps the signals that answer each.
| Part | Is | Answers |
|---|---|---|
| Metric | A number over time, in a namespace, with dimensions | How much, how fast, how often |
| Log | Lines of text, grouped in log groups and streams | What exactly happened, and why |
| Alarm | A rule on one metric, with actions when its state changes | Should someone be told? |
| Dashboard | A page of graphs, alarms and log queries | What's the state of things right now? |
| Logs Insights | A query language over log groups | Questions you didn't plan for |
(Your machine)
cd ~/Apps/aws-practice/lesson-32
source ../lesson-20/.venv/bin/activate
python lab.py fence
== Can this account do the lab in us-east-2?
CloudWatch allowed
CloudWatch Logs allowed
Lambda allowed
SNS allowed
== CloudWatch's prices beyond the free allowance, in us-east-2 (from the Price List API)
custom metric, a month $0.3
standard alarm, per metric, a month $0.1
log data ingested, per GB $0.5
Logs Insights, per GB scanned $0.005
dashboard, a month $3
== This lab, against the always-free allowances
3 custom metrics of 10; 3 alarms (4 metrics) of 10; 1 dashboard of 3; well under 5 GB of logs
Build: logs that metrics can read
The function processes five orders a run and prints one JSON line per order:
def log(level, **fields):
print(json.dumps({"level": level, **fields}))
log("INFO", order=order, items=len(items), total=total, ms=round(ms))
log("ERROR", order=order, error="payment declined", ms=round(ms))
python lab.py build
== A topic for alarm notifications
== The function's log group, made first so it has a retention: 3 days
== The order processor: one JSON log line per order, and one metrics line per run
active after 11 seconds
== A metric filter: every log line with level ERROR counts 1 towards JuniperRye/Orders/OrdersDeclined
== Three alarms, each judged on one-minute periods
jr-lesson32-crashes Sum Errors >= 1 now INSUFFICIENT_DATA
jr-lesson32-error-rate metric math: 100 * Errors / Invocations > 20 now INSUFFICIENT_DATA
jr-lesson32-slow p90 Duration > 2000 now INSUFFICIENT_DATA
== Alarm and OK notifications go to jr-lesson32-alarms (0 email subscriptions)
The log group was made before the function, on purpose. If Lambda makes it, on the function's first log line, it keeps everything forever, which is how Lesson 26's checker found log groups that never expire. Made first, it has a 3-day retention from the start.
JSON logs are the habit that pays for itself. Every field, level, order, ms, becomes something Logs Insights can filter and count, and something a metric filter can match, with no parsing.
There are three ways to turn what code does into a metric, and this lab uses all three:
| Way | How | In the lab | Good for |
|---|---|---|---|
| Published by AWS | Nothing to do | Lambda's runs, crashes and duration | Every service's basics, free |
| Metric filter | A pattern on a log group counts matching lines | counts declined orders | Logs you already have, or code you can't change |
| Embedded metric format | The code prints one specially shaped JSON line; CloudWatch extracts the numbers | Orders processed and their value, per run | Your own numbers, without an API call or extra latency |
The embedded metric format line, printed once per run:
{"_aws": {"Timestamp": 1794790300750, "CloudWatchMetrics": [{"Namespace": "JuniperRye/Orders",
"Dimensions": [["Service"]], "Metrics": [{"Name": "OrdersProcessed", "Unit": "Count"},
{"Name": "OrderValue", "Unit": "None"}]}]}, "Service": "orders", "OrdersProcessed": 2, "OrderValue": 20.0}
The third way, calling PutMetricData from code, also works, but every call is an API request that costs money at scale and adds latency to the code that makes it.
| Setting | Is | Here |
|---|---|---|
| Period | How long each data point covers | 60 seconds |
| Statistic | How the period's values become one number | Sum, or the 90th percentile |
| Threshold | The line the number is compared with | 1 crash; 20%; 2,000 ms |
| Datapoints to alarm | How many bad periods, out of how many, before ALARM | 1 out of 1: quick, and noisy |
| Missing data | What a period with no data counts as | notBreaching: no runs means nothing wrong |
| Actions | What happens on ALARM and on OK | Both notify the SNS topic |
A new alarm starts at INSUFFICIENT_DATA: it hasn't seen a full period yet.
Healthy, then trouble
python lab.py traffic
== 00:52:26 UTC: 2 minutes of healthy traffic (5 orders a run, all quick)
healthy: 63 runs in 122 seconds, 0 crashed
== 00:54:28 UTC: 2 minutes of trouble: 20% of orders declined, half the bakes slow, 1 run in 3 crashes
trouble: 29 runs in 121 seconds, 10 crashed
== 00:56:28 UTC: done. CloudWatch's numbers arrive a minute or two behind; run watch next.
Half as many runs fit into the bad two minutes, because each one was slower. That's how trouble usually looks: the same users, less getting done.
Watch the alarms fire
python lab.py watch
== Waiting for the alarms (checking every 15 seconds, for up to 8 minutes)
0s crashes ALARM, error-rate OK, slow ALARM
30s crashes ALARM, error-rate ALARM, slow ALARM
== Alarm history
00:53:33 jr-lesson32-slow INSUFFICIENT_DATA -> OK
Threshold Crossed: 1 out of the last 1 datapoints [418.76475611649573 (16/11/26 00:52:00)] was not greater than the threshold (2000.0) (minimum 1 data
00:53:44 jr-lesson32-crashes INSUFFICIENT_DATA -> OK
Threshold Crossed: 1 out of the last 1 datapoints [0.0 (16/11/26 00:52:00)] was not greater than or equal to the threshold (1.0) (minimum 1 datapoint
00:53:49 jr-lesson32-error-rate INSUFFICIENT_DATA -> OK
Threshold Crossed: 1 out of the last 1 datapoints [0.0 (16/11/26 00:52:00)] was not greater than the threshold (20.0) (minimum 1 datapoint for ALARM -
00:55:33 jr-lesson32-slow OK -> ALARM
Threshold Crossed: 1 out of the last 1 datapoints [3663.111122223333 (16/11/26 00:54:00)] was greater than the threshold (2000.0) (minimum 1 datapoint
00:55:44 jr-lesson32-crashes OK -> ALARM
Threshold Crossed: 1 out of the last 1 datapoints [3.0 (16/11/26 00:54:00)] was greater than or equal to the threshold (1.0) (minimum 1 datapoint for
00:56:49 jr-lesson32-error-rate OK -> ALARM
Threshold Crossed: 1 out of the last 1 datapoints [35.714285714285715 (16/11/26 00:55:00)] was greater than the threshold (20.0) (minimum 1 datapoint
The 3663.111122223333 is the lab's masking, not CloudWatch. The script hides 12-digit numbers so account IDs never appear, and it caught the decimals of this one. The real value was 3,663 ms and some fraction; the script now leaves decimals alone.
Each alarm judged a whole minute, after the minute ended. The trouble began at 00:54:28. The slow and crashes alarms fired at 00:55:33 and 00:55:44, judging the 00:54 minute: about a minute after it closed, the time Lambda's metrics take to arrive. That's the floor on how fast a one-minute alarm can tell you anything, and why "1 out of 1" is as quick as alarms get.
The crash rate waited a minute longer, and that's the interesting part. In the 00:54 minute there were 3 crashes, enough for the crashes alarm, but only 14% of runs: under the 20% line. In the 00:55 minute the rate was 36%, and it fired. A count of 3 in a minute of 2,000 runs is nothing; in a minute of 20 it's a crisis. A rate scales with traffic and a count doesn't, which is why real alarms are usually on rates, with a count alarm only for things that should never happen at all.
| State | Means | Seen here |
|---|---|---|
INSUFFICIENT_DATA | Not enough data to judge | Every alarm, just after it was made |
OK | The last period was on the right side of the line | The healthy minute, 00:52 |
ALARM | Enough periods crossed the line | From 00:55:33 |
Ask the logs
Logs Insights queries log groups with a pipeline of commands, each | feeding the next, and pulls the fields out of JSON lines by itself.
python lab.py query
== How many order lines of each level
> filter ispresent(level)
> | stats count(*) as lines by level
level lines
INFO 430
ERROR 30
460 of 839 records matched, 123,124 bytes scanned, cost $0.0000006
== Order time, minute by minute (successful orders)
> filter level = "INFO"
> | stats count(*) as orders, round(avg(ms)) as avg_ms, round(pct(ms, 90)) as p90_ms by bin(1m) as minute
> | sort minute
minute orders avg_ms p90_ms
2026-11-16 00:52:00.00 90 71 114
2026-11-16 00:53:00.00 155 72 112
2026-11-16 00:54:00.00 101 195 801
2026-11-16 00:55:00.00 56 551 1274
2026-11-16 00:56:00.00 28 427 1281
430 of 839 records matched, 123,124 bytes scanned, cost $0.0000006
== The crashes, newest first
> filter @message like /RuntimeError/
> | fields @timestamp, @message
> | sort @timestamp desc
> | limit 3
@timestamp @message
2026-11-16 00:56:22.97 [ERROR] RuntimeError:
2026-11-16 00:56:10.69 [ERROR] RuntimeError:
2026-11-16 00:55:59.99 [ERROR] RuntimeError:
10 of 798 records matched, 108,491 bytes scanned, cost $0.0000005
Look at 00:54: the average order took 195 ms; the slowest tenth took 801. An average blends the many quick orders with the few slow ones and hides how bad it was for the customers who waited. That's why the slow alarm watches the 90th percentile, and why "p90" and "p99" are what people quote about latency.
The other records in the group, 839 in all, are Lambda's own START, END and REPORT lines and the crash tracebacks; filter ispresent(level) kept only the order lines. The third query's message column was cut at 22 characters by the script's table, before "the oven is on fire"; the script now shows more of it.
Three queries scanned about a third of a megabyte and cost under a millionth of a dollar each. Insights is billed by bytes scanned, so the habits that keep it cheap are a narrow time range and a log group per service, not one huge group for everything.
The numbers, minute by minute
python lab.py metrics
== The last 15 minutes, one row per minute (UTC); blank means no data that minute
minute runs crashed crash_pct p50_ms p90_ms orders declined
19:52 18 0 0 351 435 90 0
19:53 31 0 0 366 452 155 0
19:54 22 3 14 415 2675 101 9
19:55 14 5 36 2479 4970 56 14
19:56 6 2 33 2726 3363 28 7
== Where each column comes from
runs, crashed, p50_ms, p90_ms: AWS/Lambda, published by Lambda for every function, free
orders: JuniperRye/Orders, from the embedded metric format line each run logs
declined: JuniperRye/Orders, from the metric filter counting ERROR lines
crash_pct: metric math, worked out when asked, not stored
The minutes say 19:52 because the script printed them in the Mac's local time, New York, despite the "UTC" in its heading: 19:52 there is 00:52 UTC. The script now converts them.
Three sources, one story. The metric filter counted 9 + 14 + 7 = 30 declined orders; Logs Insights found exactly 30 ERROR lines. The embedded metrics counted 90 + 155 + 101 + 56 + 28 = 430 orders; Insights found exactly 430 INFO lines. When metrics and logs agree like this, you can trust the dashboard; when they don't, something is dropping data.
The duration columns are per run of five orders, so they're bigger than the per-order times in the logs. At 19:55 the median run took 2,479 ms and the slowest tenth 4,970. crash_pct was never stored anywhere: metric math works it out from two stored metrics each time it's asked, at no extra cost.
A dashboard
python lab.py dashboard
== Dashboard jr-lesson32: 5 widgets
metric Runs and crashes
metric Duration, p50 and p90 (ms)
metric Orders processed and declined
alarm Alarms
log Declined orders
== Open it (signed in to the console as juniper-rye):
https://us-east-2.console.aws.amazon.com/cloudwatch/home?region=us-east-2#dashboards/dashboard/jr-lesson32
In the console: CloudWatch > Dashboards, then the dashboard's name. A dashboard is a JSON document of widgets: metric graphs, an alarm status panel, and a Logs Insights query shown as a table. Because it's JSON, it belongs in Terraform or the CDK with everything else, not built by hand in the console.
Recovery
python lab.py recover
== 00:57:06 UTC: 2 minutes of healthy traffic again
healthy: 64 runs in 122 seconds, 0 crashed
== Waiting for the alarms to clear (checking every 15 seconds, for up to 8 minutes)
0s crashes OK, error-rate OK, slow OK
00:58:33 jr-lesson32-slow ALARM -> OK
Threshold Crossed: 1 out of the last 1 datapoints [450.6424164360577 (16/11/26 00:57:00)] was not greater than the threshold (2000.0) (minimum 1 datap
00:58:44 jr-lesson32-crashes ALARM -> OK
Threshold Crossed: 1 out of the last 1 datapoints [0.0 (16/11/26 00:57:00)] was not greater than or equal to the threshold (1.0) (minimum 1 datapoint
00:58:49 jr-lesson32-error-rate ALARM -> OK
Threshold Crossed: 1 out of the last 1 datapoints [0.0 (16/11/26 00:57:00)] was not greater than the threshold (20.0) (minimum 1 datapoint for ALARM -
All three cleared on the first healthy minute, 00:57, and each sent an OK notification to the topic. An OK action matters as much as the ALARM one: it tells whoever was paged that it's over, and it closes the incident in tools that track them.
Take it down
python lab.py delete
== Deleting 3 alarms
== Deleting the dashboard
== Deleting the function
== Deleting the log group, and the metric filter with it
== Deleting the role
== Deleting the alarm topic and its subscriptions
== Anything left from Lesson 32
nothing: all clear
custom metrics still listed in JuniperRye/Orders: OrderValue, OrdersDeclined, OrdersProcessed
(they can't be deleted: with no new data they cost nothing, and disappear from lists after 2 weeks)
Custom metrics can't be deleted. A metric exists as long as data points do; with no new data, it stops costing anything and drops out of listings after two weeks, while its old data points age out over 15 months. That's harmless here and expensive elsewhere: a metric made by mistake, with a dimension that has thousands of values, costs for every month it keeps receiving data.
By hand: the same with the AWS CLI
(Your machine) An alarm on Lambda's crashes, and its history:
export AWS_PROFILE=juniper-rye AWS_REGION=us-east-2
aws cloudwatch put-metric-alarm --alarm-name jr-lesson32-crashes --namespace AWS/Lambda --metric-name Errors --dimensions Name=FunctionName,Value=jr-lesson32-orders --statistic Sum --period 60 --evaluation-periods 1 --threshold 1 --comparison-operator GreaterThanOrEqualToThreshold --treat-missing-data notBreaching
aws cloudwatch describe-alarm-history --alarm-name jr-lesson32-crashes --history-item-type StateUpdate --query "AlarmHistoryItems[].[Timestamp,HistorySummary]" --output table
A metric filter, and a Logs Insights query from the command line:
aws logs put-metric-filter --log-group-name /aws/lambda/jr-lesson32-orders --filter-name jr-lesson32-declined --filter-pattern '{ $.level = "ERROR" }' --metric-transformations metricName=OrdersDeclined,metricNamespace=JuniperRye/Orders,metricValue=1,defaultValue=0
QUERY=$(aws logs start-query --log-group-name /aws/lambda/jr-lesson32-orders --start-time $(date -v-30M +%s) --end-time $(date +%s) --query-string 'filter ispresent(level) | stats count(*) by level' --query queryId --output text)
sleep 5
aws logs get-query-results --query-id $QUERY
The date -v-30M form is macOS's; on Linux it's date -d '30 minutes ago' +%s.
In real systems
- Alarms are on symptoms customers feel, error rates and latency at the front door, more than on causes like CPU. Every alarm that pages someone links to a runbook.
- Alarms need more than one bad period, like 3 out of 5, so one blip doesn't wake anyone. Composite alarms combine several into one page.
- Every log group has a retention, set by Terraform or the CDK when it's made.
- Services log in JSON with a request ID in every line, so one request can be followed across services.
- Traces join the three signals: AWS X-Ray and CloudWatch Application Signals show where a slow request spent its time.
- Dashboards are code, versioned with the service they describe.
- Dimensions are chosen carefully: service, operation, environment; never IDs.
Spot the problem
Work out what's wrong before you read the explanation.
"Our CloudWatch bill went from $3 to $900." A team wants to see each customer's order total, so they add CustomerId as a dimension on their embedded metric format line. It works: the console shows a graph per customer. The next bill has a CloudWatch line of about $900, mostly "metrics". What's wrong? Every different set of dimension values is a separate custom metric, at $0.30 a month each, and 3,000 customers made 3,000 metrics. The fix: keep dimensions to things with a handful of values, like service or environment, and put IDs in the log line as ordinary fields, where Logs Insights can still group by them. Then check: run aws cloudwatch list-metrics --namespace with your namespace and count the results; is it tens, or thousands?
Keep this
| Remember | Why |
|---|---|
| Log in JSON | Every field is queryable and countable |
| Make the log group first, with a retention | Otherwise logs are kept forever |
| Metric filter or embedded metric format | Metrics from logs, with no API calls |
| Alarms judge a period after it ends | About a minute's delay, at best |
| Alarm on rates, not counts | 3 crashes was 14% one minute, 36% the next |
| Percentiles, not averages | 195 ms average, 801 ms for the slowest tenth |
| Send OK as well as ALARM | So people know it's over |
| Insights is billed by bytes scanned | Narrow the time range |
| Never put IDs in dimensions | Each combination is a $0.30 metric |
Where you are now
Juniper & Rye's order processor was watched end to end: JSON logs with a retention, a metric filter and embedded metrics that agreed with the logs to the order, three alarms that fired in the order the trouble deserved and cleared on the first healthy minute, Logs Insights queries for under a millionth of a dollar, and a dashboard to put it all on one page. Next, Lesson 33 asks a different question of the same account: not "is it working?" but "who changed what?", with CloudTrail.
Check yourself
Which metrics did the lab get without writing any code for them?
The trouble began at 00:54:28. Why did the first alarm fire at 00:55:33?
In the 00:54 minute, crashes fired but the crash rate didn't. Why?
Why does the slow alarm use the 90th percentile instead of the average?
Why was the log group created before the function?
What is Logs Insights billed by?
Why can adding CustomerId as a dimension cost so much?
Key terms
- Metric: a number over time, identified by a namespace, a name and dimensions.
- Namespace: a container for metrics, like
AWS/LambdaorJuniperRye/Orders. - Dimension: a name and value that identify one version of a metric, like
FunctionName. - Statistic: how a period's values become one number: sum, average, maximum, or a percentile.
- Percentile: the value a given share of data points fall below; p90 is beaten by only the slowest tenth.
- Log group: where a service's log streams are kept, with one retention for all of them.
- Metric filter: a pattern on a log group that turns matching lines into a metric.
- Embedded metric format (EMF): a JSON log line shape that CloudWatch turns into metrics.
- Logs Insights: CloudWatch's query language for log groups.
- Alarm: a rule on a metric with states and actions.
- Metric math: expressions over metrics, like a rate from two counts, worked out when asked.
- Dashboard: a page of widgets showing metrics, alarms and log queries.
Go deeper
- Earlier lessons: Lambda for its logs and REPORT lines, and the unused-resource checker, which finds log groups with no retention.
- AWS: Using CloudWatch alarms (opens in a new tab), and Logs Insights query syntax (opens in a new tab).
- AWS: the embedded metric format (opens in a new tab), and CloudWatch pricing (opens in a new tab).
- Try: run
build, then change theslowalarm to need 2 out of 3 data points (EvaluationPeriods=3, DatapointsToAlarm=2in the script), runtrafficandwatchagain, and see how much later it fires. Then addEMAIL=you@example.comin front ofbuild, confirm the subscription, and get the ALARM and OK emails. Rundeletewhen you're done.