Lesson 16 of 30Modern AWS
Monitoring and Logs
Use CloudWatch metrics, logs and alarms, trace requests with X-Ray, audit API calls with CloudTrail, and set a billing alarm.
Shipping to AWS is half the job. The other half is knowing, before your users tell you, that error rates jumped, the queue is backing up, or someone deleted a bucket. On AWS that knowledge comes from CloudWatch (metrics, logs, alarms), X-Ray (traces) and CloudTrail (who did what). On-call engineers live in these tools, and "how would you know it's broken?" is a standard interview follow-up.
The three signals
Observability rests on three kinds of data:
- Metrics: numbers over time. CPU at 72%, 1,340 requests per minute, p99 latency 480 ms. Cheap to store, great for alarms and graphs.
- Logs: timestamped records of events. "Order A17 failed: card declined". Rich detail, more expensive to store and search.
- Traces: one request's path across services, with timing for each hop. Shows where the time went.
CloudWatch metrics
Amazon CloudWatch collects metrics from almost every AWS service automatically: EC2 CPUUtilization, ALB TargetResponseTime and HTTPCode_Target_5XX_Count, Lambda Errors and Duration, SQS ApproximateAgeOfOldestMessage, RDS FreeStorageSpace. Each metric lives in a namespace (like AWS/Lambda) and is identified by dimensions (like FunctionName=resize).
Metrics are aggregated per period (1 minute is typical) with a statistic: Average, Sum, Maximum, or a percentile like p99. Averages hide pain. If 99 requests take 50 ms and one takes 5 seconds, the average is a cheerful 100 ms while one in a hundred users waits five seconds.
Press Run (⌘ Enter) to see what happens.The average says 385 ms, which matches no real request. The p50 (median) says most users are fine; the p99 says some are not. Alarm on percentiles for latency.
You can publish custom metrics too, like OrdersPlaced or PaymentFailures, with PutMetricData or, cheaper and simpler, by writing logs in Embedded Metric Format that CloudWatch turns into metrics.
CloudWatch Logs and structured logging
Lambda, ECS (with the awslogs driver), API Gateway and many others send output to CloudWatch Logs. Logs are organized as log groups (one per app, like /ecs/api) containing log streams (one per task or Lambda environment). Set a retention period on every group: the default is "never expire", which quietly grows your bill.
Write logs as JSON, one object per line. Then CloudWatch Logs Insights can filter and aggregate on fields instead of grepping strings.
Press Run (⌘ Enter) to see what happens.Include a request ID on every line so you can pull up everything that happened for one request. Never log secrets, tokens or full card numbers.
With JSON logs, a Logs Insights query reads like SQL:
fields @timestamp, order_id, ms
| filter level = "WARNING" and ms > 1000
| stats count(*) as slow, pct(ms, 99) as p99 by bin(5m)
| sort @timestamp descA metric filter turns matching log lines into a metric (count level = "ERROR"), which you can then alarm on.
C-88 last night. Which logging style makes that a one-line query?Logs Insights in practice
During an incident you rarely have time to write a clever query. Keep a few shapes in your head and adapt them. Every query is a pipeline: each | passes rows to the next command.
What is failing, and since when? Count errors in five-minute buckets. A step change tells you when it started, which you then match against deploys.
fields @timestamp, @message
| filter level = "ERROR"
| stats count(*) as errors by bin(5m)Which error? Group by the message and look at the top few. One new message at the top is usually the incident.
filter level = "ERROR"
| stats count(*) as n by msg
| sort n desc
| limit 10Lines that are not JSON. Old services and third-party software log plain text. parse pulls fields out with a glob pattern (each * becomes a field) or a regular expression, and then you aggregate as usual.
filter @message like /took/
| parse @message "* * took *ms" as method, path, ms
| stats avg(ms) as avg_ms, pct(ms, 95) as p95, count(*) as n by path
| sort p95 descLambda's own report lines. Every invocation ends with a REPORT line, and Logs Insights discovers its fields for you: @duration, @billedDuration, @maxMemoryUsed, @memorySize and, on cold starts, @initDuration.
filter @type = "REPORT"
| stats count(*) as invocations,
count(@initDuration) as cold_starts,
pct(@duration, 99) as p99_ms,
max(@maxMemoryUsed / 1000 / 1000) as max_mem_mb
by bin(1h)Three habits make queries fast and cheap. Logs Insights is billed by the amount of data it scans, so pick the shortest time range that answers the question and only the log groups you need. Put filter early so later stages see fewer rows. And save the queries that worked during an incident; next time they are one click away. Logs Insights has also gained other query languages (OpenSearch PPL and SQL) alongside its own; the examples here use the original syntax, which every account has.
Metrics from logs: EMF and metric filters
Alarms need metrics, but your app already writes logs. Two features bridge the gap without a separate metrics client.
Embedded Metric Format (EMF) is a JSON log line with an _aws block that tells CloudWatch which fields are metrics. CloudWatch extracts them when the line is ingested. The same line stays searchable in Logs Insights, so a slow order is both a point on a graph and a record you can find.
Press Run (⌘ Enter) to see what happens.The rule that keeps EMF safe is cardinality. Every unique combination of dimension values is a separate custom metric, and custom metrics are billed per metric. Service has a handful of values. customer_id has millions. Put high-cardinality fields like order_id and customer_id in the line as plain properties, as above, where Logs Insights can still filter on them, and never in Dimensions. A single bad dimension can create more custom metrics in a day than the team planned for in a year. Powertools for AWS Lambda writes EMF for you, as Lambda and Serverless shows.
A metric filter works the other way round: it watches a log group for a pattern and increments a metric for each match. It needs no code change, which makes it the right tool for software you do not own.
aws logs put-metric-filter --log-group-name /ecs/api \ --filter-name api-errors \ --filter-pattern '{ $.level = "ERROR" }' \ --metric-transformations metricName=ApiErrors,metricNamespace=Shop,metricValue=1,defaultValue=0defaultValue=0 matters: without it, quiet minutes publish nothing, and an alarm sees missing data instead of zero. Metric filters only count lines ingested after you create them; they do not backfill.
customer_id to the Dimensions list in the service's EMF logs so they can graph latency per customer. You have 400,000 active customers. What is the main problem?Alarms
A CloudWatch alarm watches one metric (or a math expression) and changes state: OK, ALARM, or INSUFFICIENT_DATA. You set a threshold, a period, and M out of N datapoints: "ALARM if 3 out of the last 5 one-minute periods have 5XX count above 10". Requiring several datapoints avoids paging someone for a single blip. You also decide how missing data is treated (as missing, breaching, not breaching, or ignore).
Alarm actions can notify an SNS topic (email, Slack via AWS Chatbot, PagerDuty), trigger Auto Scaling, or stop an EC2 instance.
Good first alarms for a web app:
| Alarm on | Why |
|---|---|
ALB HTTPCode_Target_5XX_Count or error rate | Users are seeing errors |
ALB TargetResponseTime p99 | Users are waiting |
SQS ApproximateAgeOfOldestMessage | Consumers are falling behind |
DLQ ApproximateNumberOfMessagesVisible > 0 | Something is failing repeatedly |
RDS FreeStorageSpace, CPUUtilization | The database is about to fall over |
EstimatedCharges | Your bill is running away |
Dashboards put these graphs on one screen. Build one per service, with the same graphs your alarms watch.
The alarm needs 2 of the last 3 datapoints above 80. Using the logic below, what is printed?
points = [95, 99, 70, 85, 60]
window = points[-3:]
breaching = sum(1 for p in window if p > 80)
print("ALARM" if breaching >= 2 else "OK")Cutting alert noise
An alarm that pages for nothing trains people to ignore alarms. Two features help you page less without missing real incidents.
Composite alarms combine other alarms with AND, OR and NOT. Keep your detailed alarms, but stop them notifying anyone directly. Let one composite alarm page:
(ALARM("api-5xx-rate-high") OR ALARM("api-p99-high"))
AND NOT ALARM("deploy-in-progress")Now a single incident that trips both the error and latency alarms produces one page, not two, and a planned deploy that briefly raises latency pages nobody. Composite alarms can also use an actions suppressor: while a named alarm (say, "the database is in maintenance") is in ALARM, the composite's actions are held back. A good pattern is one composite per service that represents "users are hurting", with the detailed alarms linked from it for diagnosis.
Anomaly detection replaces a fixed threshold with a band that CloudWatch learns from the metric's history, including daily and weekly cycles. Traffic of 200 requests a minute is normal at 3 p.m. and suspicious at 3 a.m.; a fixed threshold cannot tell the difference, a band can. You set how wide the band is (in standard deviations) and alarm when the metric goes above it, below it, or outside it. A drop below the band is often the more valuable signal: orders per minute falling to near zero during business hours means checkout is broken, even though no error alarm fired.
It is not magic. The model needs a history of the metric to train on, so a brand-new metric gets a poor band at first. It learns whatever happened, including last week's incident, unless you exclude that period. And it does badly on rare, spiky events such as a nightly batch job. Use it for steady, cyclical metrics like request rate and business counts; keep fixed thresholds for hard limits like "DLQ depth above zero" or "disk above 90 percent".
Pick the alarm style for each need.
Set a billing alarm
Billing metrics live only in us-east-1, and you must first enable Receive CloudWatch billing alerts in the Billing console preferences. Then:
aws sns create-topic --name billing-alerts --region us-east-1aws sns subscribe --region us-east-1 \ --topic-arn arn:aws:sns:us-east-1:123456789012:billing-alerts \ --protocol email --notification-endpoint you@example.comaws cloudwatch put-metric-alarm --region us-east-1 \ --alarm-name estimated-charges-over-20 \ --namespace AWS/Billing --metric-name EstimatedCharges \ --dimensions Name=Currency,Value=USD \ --statistic Maximum --period 21600 \ --evaluation-periods 1 --threshold 20 \ --comparison-operator GreaterThanThreshold \ --alarm-actions arn:aws:sns:us-east-1:123456789012:billing-alertsEstimatedCharges is the month-to-date total, updated a few times a day, so a 6-hour period is enough. Pair it with an AWS Budget (from Cloud Basics), which can also alert on forecasted spend.
X-Ray: tracing a request
AWS X-Ray follows a request across services. Each service adds a segment with timings, and calls to downstream services (DynamoDB, an HTTP API, SQL) become subsegments. A trace ID travels in the X-Amzn-Trace-Id header. The service map shows every hop with latency and error rates, so "the API is slow" becomes "the API is slow because the inventory service's DynamoDB query takes 900 ms".
Today the recommended way to instrument is OpenTelemetry (the AWS Distro for OpenTelemetry), which sends traces to X-Ray and the CloudWatch Application Signals views. Lambda and API Gateway can turn on tracing with a checkbox.
OpenTelemetry, ADOT and Application Signals
The instrumentation story changed, and older tutorials still show the old one. The X-Ray SDKs and the X-Ray daemon are in maintenance mode, and AWS recommends OpenTelemetry for new work. Check the X-Ray docs for the current support dates before you plan around the old SDKs.
The pieces fit together like this:
- OpenTelemetry is the vendor-neutral standard: an SDK in your app creates spans and metrics, and the OTLP protocol carries them. Code instrumented once can send to X-Ray, Datadog, Honeycomb or Grafana.
- ADOT (the AWS Distro for OpenTelemetry) packages the SDKs and a collector with AWS-specific parts, such as X-Ray ID formats and resource detection for ECS, EKS and Lambda. On Lambda it is a layer; on ECS it usually runs as a sidecar container; the CloudWatch agent can also receive OTLP.
- Auto-instrumentation wraps common libraries (HTTP clients, web frameworks, database drivers, the AWS SDK) so you get spans without editing every call site. Add manual spans only for the business steps you care about.
CloudWatch Application Signals builds on this. It discovers your services from the telemetry and shows request rate, errors and latency per service and per operation, such as POST /checkout. Its most useful feature is SLOs: you state the goal, for example "99.9 percent of POST /checkout requests succeed, over a rolling 30 days", and it tracks the error budget and how fast you are burning it.
Burn rate is the number seniors alarm on. A burn rate of 1 uses exactly the budget over the window. A burn rate of 15 empties it in about two days.
Press Run (⌘ Enter) to see what happens.Alarming on a high burn rate over a short window (fast, big problems) plus a lower burn rate over a long window (slow leaks) pages for things that threaten the SLO, and stays quiet for a blip that costs a fraction of the budget.
A request flows through the ALB to the API and DynamoDB.
Retention: the cost of "Never expire"
Every new log group starts with retention set to Never expire. Nothing deletes anything, and storage grows every day for as long as the account exists. Debug logging left on in a busy service can write more in a month than everything else in the account combined. Lambda, ECS and many other services create log groups automatically on first write, and those groups inherit the default.
Set retention on purpose, by how the logs are used:
| Log group | Typical retention | Why |
|---|---|---|
Application logs (/ecs/api) | 14 to 30 days | Incidents are investigated within days |
| Lambda function logs | 7 to 30 days | High volume, short-lived value |
| Audit or compliance logs | Policy decides, often a year or more | Export to S3 with lifecycle rules rather than keep in CloudWatch |
| VPC Flow Logs | Days to weeks in CloudWatch, longer in S3 | Very high volume |
aws logs put-retention-policy --log-group-name /ecs/api --retention-in-days 30aws logs describe-log-groups --query 'logGroups[?!retentionInDays].logGroupName' --output textThe second command lists every group with no retention set, which is a good first look in any account you inherit. Better still, create log groups yourself in Terraform or CDK with retention set, before the service first writes, so the automatic default never applies. CloudWatch also has a cheaper Infrequent Access log class for logs you keep but rarely query; it supports fewer features, so check what it gives up before you choose it.
CloudTrail: who did what
AWS CloudTrail records management API calls in your account: who (arn:aws:sts::123456789012:assumed-role/admin/ada), what (DeleteBucket), when, from which IP, and whether it succeeded. The last 90 days are viewable in Event history for free. For longer retention and organization-wide auditing, create a trail that delivers logs to an S3 bucket (ideally in a separate, locked-down logging account). Data events (like every GetObject) are opt-in and billed.
CloudTrail answers security and "what changed?" questions. CloudWatch answers "is my app healthy?". They are different tools.
Which tool answers the question?
CloudWatch alarm state
A CloudWatch alarm looks at the most recent N datapoints (evaluation periods) and goes into ALARM when at least M of them breach the threshold ("M out of N"). Write alarm_state(datapoints, threshold, n, m).
datapointsis oldest first. A missing datapoint isNone/null.- A datapoint breaches when it is greater than
threshold. - Look only at the last
ndatapoints (or all of them if there are fewer). - If that window is empty or every value in it is missing, return
"INSUFFICIENT_DATA". - Otherwise return
"ALARM"if at leastmdatapoints breach, else"OK". Missing values never breach.
alarm_state([40, 85, 91, 70, 95], 80, 3, 2) → "ALARM" (last 3: 91, 70, 95: two breach)
alarm_state([95, 96, 40, 50, 60], 80, 3, 2) → "OK" (old spikes are outside the window)
alarm_state([90, None, None, None], 80, 3, 2) → "INSUFFICIENT_DATA"- metric
- A time series of numbers in CloudWatch, identified by namespace, name and dimensions.
- p99 latency
- The value 99% of requests are faster than. Exposes slow outliers averages hide.
- log group
- A CloudWatch Logs container for one app's log streams, with a retention setting.
- CloudWatch alarm
- Watches a metric and goes to ALARM when M of N datapoints breach a threshold.
- X-Ray trace
- One request's path across services, with timed segments and subsegments.
- CloudTrail
- The audit log of AWS API calls: who did what, when, and from where.
- Embedded Metric Format
- JSON log lines with an
_awsblock that CloudWatch turns into metrics at ingestion. - composite alarm
- An alarm whose state is a rule over other alarms, used to page once and suppress noise.
- burn rate
- How fast you are spending an SLO's error budget; 1 means exactly on budget for the window.