Observability: Logs, Metrics & Traces
System Design · Production in the Cloud · Advanced · 22 min
Use logs, metrics and traces on AWS (CloudWatch, Logs Insights, X-Ray / OpenTelemetry), define SLIs with percentiles instead of averages, and build M-out-of-N alarms that page only when it matters.
A hospital patient. The heart-rate monitor is a metric (one number over time), the nurse's notes are logs (detailed events), and following one blood sample from the ward to the lab and back is a trace.
The idea in everyday words
Running a system without observability is like driving at night without a dashboard. Metrics are the speedometer and fuel gauge: quick numbers you glance at. Logs are the trip diary: every detail, but you have to search it. Traces are the GPS route replay: they show where this one journey slowed down. And an alarm is the warning light, which should only blink when you really need to pull over.
The three pillars: logs, metrics, traces
Observability = being able to answer "what is wrong and why?" from the outside, using the data your system emits, without shipping new code.
| Pillar | What it is | Good for | AWS |
|---|---|---|---|
| Metrics | numbers over time (count, latency, errors) | dashboards, alarms, trends; cheap to keep | CloudWatch Metrics |
| Logs | timestamped records of events, ideally JSON | the details of one failure | CloudWatch Logs + Logs Insights |
| Traces | the path of ONE request across services, with timings | finding which hop is slow | AWS X-Ray, OpenTelemetry (ADOT) |
How they work together: an alarm on a metric tells you p99 latency jumped. A trace shows the time is spent in the payment service's database call. The logs for that trace id show "connection pool exhausted".
Key idea: put the same request id / trace id in all three, so you can jump from a spike on a graph to the exact slow requests and their log lines.
CloudWatch: metrics, alarms and Logs Insights
Metrics live in a namespace (AWS/Lambda, AWS/SQS, or your own like Shop/Checkout) and are sliced by dimensions (FunctionName, Region). AWS services publish many metrics automatically. For your own:
- PutMetricData API calls, or
- the Embedded Metric Format (EMF): print a structured JSON log line and CloudWatch extracts the metric. No extra API call from Lambda.
High-cardinality warning: never use user_id or request_id as a metric dimension. Each unique combination is a separate metric (and cost). Put those in logs.
Alarms watch one metric (or a math expression) and are in OK, ALARM or INSUFFICIENT_DATA. Key settings: statistic (Average, Sum, p99…), period, threshold, evaluation periods (N), datapoints to alarm (M) and how to treat missing data. Actions: notify an SNS topic, scale an Auto Scaling group, and more. Composite alarms combine alarms with AND / OR to cut noise.
Logs Insights queries your log groups:
fields @timestamp, route, latency_ms, trace_id
| filter level = "ERROR" or latency_ms > 1000
| stats count() as slow, pct(latency_ms, 99) as p99 by route
| sort slow desc
| limit 20
Log structured JSON ({"level":"ERROR","route":"/pay","latency_ms":1840,"trace_id":"1-abc"}) so fields are searchable without regex.
Traces: X-Ray and OpenTelemetry
A trace follows one request. It is made of spans (X-Ray calls them segments and subsegments): one per service hop or important call, each with a start time and duration. Drawn as a waterfall:
API Gateway |=====================================| 820 ms
Lambda |==================================| 790 ms
DynamoDB |==| 18 ms
Payment API |============================| 700 ms <- here
SQS send |=| 9 ms
The trace context travels with the request in a header (X-Amzn-Trace-Id for X-Ray, traceparent for the W3C / OpenTelemetry standard), so every service adds its spans to the same trace.
- AWS X-Ray collects and shows traces and a service map. Many services integrate directly (API Gateway, Lambda active tracing).
- OpenTelemetry is the vendor-neutral standard for instrumenting code. AWS Distro for OpenTelemetry (ADOT) sends OTel data to X-Ray and CloudWatch. AWS now points new instrumentation toward OpenTelemetry.
- CloudWatch Application Signals builds service dashboards and SLOs on top of this telemetry.
- Sampling: tracing every request is expensive. Sample a small percentage plus all errors.
SLIs, SLOs and why averages lie
- SLI (service level indicator): a measured number that reflects user happiness, e.g. "% of checkout requests under 300 ms" or "% of requests without 5xx".
- SLO (objective): the target, e.g. "99.9% of checkouts under 300 ms over 30 days".
- Error budget: the 0.1% you are allowed to miss. Budget left → ship features. Budget burnt → focus on reliability.
Percentiles: sort the latencies; p95 is the value 95% of requests are at or below. With the nearest-rank method: rank = ceil(p / 100 × n), take the rank-th smallest.
Tiny example, 10 requests (ms): 40, 42, 45, 45, 48, 50, 52, 55, 60, 2000.
- Average = 243.7 ms. Nobody actually waited ~244 ms.
- p50 = rank 5 = 48 ms. p90 = rank 9 = 60 ms. p99 = rank 10 = 2000 ms.
Key idea: the average mixes everyone together and hides the unhappy users. Percentiles describe them. And tails matter more than they look: if one page calls 100 services, each with a 1% chance of being slow, about 63% of page loads hit at least one slow call (1 − 0.99^100).
Other clouds: GCP Cloud Monitoring, Cloud Logging and Cloud Trace; Azure Monitor and Application Insights; open source Prometheus + Grafana, Loki, Jaeger / Tempo and OpenTelemetry everywhere.
Alarms that don't cry wolf: M out of N
A single spike for one minute shouldn't wake anyone up. A real outage should, quickly. M out of N balances the two: go to ALARM when at least M of the last N periods breach the threshold.
| Setting | Behaviour |
|---|---|
| 1 out of 1 | pages on every blip, noisy |
| 3 out of 3 | quiet, but a flapping problem (bad, good, bad) never fires |
| 3 out of 5 | catches sustained or flapping problems, ignores single spikes |
Good alarm habits:
- Alarm on symptoms users feel (p99 latency, error rate, DLQ depth), not on every CPU wiggle.
- Use percentile statistics (p95 / p99) for latency, never Average alone.
- Decide what missing data means: no requests may be fine (notBreaching) or may mean the service is dead (breaching).
- Every page should have a runbook link: what to check first.
- Send alarm actions to an SNS topic that reaches your on-call tool, chat and email.
Go deeper (senior / staff)
Failure modes of the monitoring itself.
- Same failure domain: if your alarms, dashboards and the service all live in one Region, a Regional impairment can blind you exactly when you need eyes. Add probes from outside: CloudWatch Synthetics canaries or Route 53 health checks running from another Region, with their own alarms.
- Silence is not health: a dead service emits no errors. Alarm on missing data (treat it as breaching) or on a heartbeat metric, not only on error counts.
- Low traffic tails: with 20 requests per period, p99 is just the slowest request. Use longer periods or more datapoints before paging.
- Pager fatigue: prefer SLO burn-rate alerts (page when the error budget burns fast over a short and a long window) to dozens of static thresholds. CloudWatch Application Signals supports SLOs and burn-rate alarms.
Multi-account and multi-region. Big AWS estates use CloudWatch cross-account observability: source accounts link to a central monitoring account, which can query their metrics, logs and traces without sharing credentials. Pair it with cross-Region dashboards, and keep the monitoring account's alerting path independent of the workload Region where you can.
Cost reasoning without numbers.
- Log ingestion is usually the biggest line item, not storage. Log at INFO by default, sample noisy debug logs, set retention on every log group, and consider the Infrequent Access log class or shipping cold logs to S3.
- Every unique dimension combination is a separate billed metric. For "top 10 users by errors", log user_id and use Logs Insights or Contributor Insights instead of a metric dimension.
- Trace sampling trades visibility for cost: keep all errors and slow requests, sample the boring ones.
Trade-off to say out loud: more telemetry is not more observability. Instrument the user journeys tied to SLOs first.
Step by step
- Collect:
Minute 1 latencies (ms): 90, 100, 120. Minute 2: 100, 110, 900, 950. Minute 3: 80, 85. Minute 4: 90, 95, 1000, 1200.
- p90 per minute:
Sort each minute and take rank ceil(0.9 × n): minute 1 rank 3 → 120; minute 2 rank 4 → 950; minute 3 rank 2 → 85; minute 4 rank 4 → 1200.
- Compare to threshold:
Threshold 500 ms. Breaching? minute 1 no, 2 yes, 3 no, 4 yes.
- Too early:
The alarm is '2 out of 3'. After minutes 1 and 2 there are fewer than 3 periods → INSUFFICIENT_DATA.
- Minute 3:
Window [no, yes, no] → 1 breach < 2 → OK. One bad minute did not page anyone.
- Minute 4:
Window [yes, no, yes] → 2 breaches ≥ 2 → ALARM. Flapping slowness is real, so we page. An average-based alarm would have hidden much of this.
Code example
import json
def percentile(values, p):
s = sorted(values)
rank = max(1, (p * len(s) + 99) // 100) # nearest rank, integer math
return s[rank - 1]
lat = [40, 42, 45, 45, 48, 50, 52, 55, 60, 2000]
print("avg:", sum(lat) / len(lat))
for p in (50, 90, 99):
print(f"p{p}:", percentile(lat, p))
# Tail at scale: a page that fans out to 100 calls, each slow 1% of the time
print(f"pages hitting a slow call: {1 - 0.99 ** 100:.0%}")
# Embedded Metric Format: print this from Lambda and CloudWatch makes a metric
emf = {
"_aws": {"Timestamp": 1700000000000, "CloudWatchMetrics": [{
"Namespace": "Shop/Checkout", "Dimensions": [["Route"]],
"Metrics": [{"Name": "LatencyMs", "Unit": "Milliseconds"}]}]},
"Route": "/pay", "LatencyMs": 182, "trace_id": "1-abc-123",
}
print(json.dumps(emf)[:70] + "...")Complexity
- Time: O(T log T) for T latencies in total (sorting each period) plus O(P · n) for the alarm windows over P periods
- Space: O(T) for the sorted copies
Interview tips
Define the SLI first: 'p99 checkout latency under 300 ms and error rate under 0.1%', then the alarms and dashboards follow.
Explain why averages lie with a tiny example (one 2 s request among fast ones) and say you alarm on p95 / p99.
Describe the debugging path: alarm on a metric → trace to find the slow hop → logs for that trace id to find the cause.
Mention M out of N alarms, missing-data handling and composite alarms to reduce noise.
AWS stack: CloudWatch Metrics / Alarms / Logs Insights, X-Ray or OpenTelemetry via ADOT, EMF for cheap custom metrics from Lambda.
Challenge: Percentile Alarm Evaluator
Write alarm_states(periods, p, threshold, m, n).
periodsis a list of periods; each period is a list of integer latencies (ms).- For each period compute the nearest-rank p-th percentile: sort it,
rank = ceil(p * len / 100)(at least 1), take therank-th smallest. An empty period has valueNone/null. Tip:(p * len + 99) // 100is ceil with integers. - A period breaches if its value is not null and is strictly greater than
threshold. - After each period
i: if fewer thannperiods have been seen, the state is"INSUFFICIENT_DATA". Otherwise look at the lastnperiods:"ALARM"if at leastmbreach, else"OK".
Return {"values": [...], "states": [...]}.
Example: alarm_states([[90, 100, 120], [100, 110, 900, 950], [80, 85], [1000, 1200, 90, 95]], 90, 500, 2, 3) → {"values": [120, 950, 85, 1200], "states": ["INSUFFICIENT_DATA", "INSUFFICIENT_DATA", "OK", "ALARM"]}
Solve it in the browser with tests, hints and an AI coach.
Practice problems
- Using Amazon CloudWatch alarms
- CloudWatch Logs Insights
- What is AWS X-Ray?
- Find Median from Data Stream (Hard)
More in Production in the Cloud
- Reliability: SLOs, Retries & Circuit Breakers
- Security: Auth, Encryption & Least Privilege
- AWS Well-Architected & Cost Optimization
- Choosing a Cloud: AWS vs GCP vs Azure vs Open Source
Previous: Reliability: SLOs, Retries & Circuit Breakers · Next: Security: Auth, Encryption & Least Privilege