Monitoring tells you whether something is wrong, using dashboards and alerts on questions you predicted in advance. Observability is the ability to ask new questions about why it is wrong, from the outside, without shipping new code. It rests on three kinds of telemetry: logs (discrete events), metrics (numbers over time) and traces (the path of one request across services). In a system of dozens of services, it is the difference between a five-minute diagnosis and a five-hour war room.
Think of it like
A patient in a hospital
The bedside monitor tracks vital signs and beeps when the heart rate spikes: that is metrics and alerting. The nurse's chart records timestamped events ("10:42, gave 5 mg, patient nauseous"): those are logs. A contrast dye followed through the bloodstream on a scan shows exactly where the blockage is: that is a trace. Monitoring is the alarm; observability is being able to diagnose a condition nobody has seen before.
Monitoring vs observability
Monitoring
- Answers predefined questions: "Is the error rate above 1%?"
- Dashboards and alerts on known failure modes (known unknowns)
- Aggregated, low-cardinality metrics
- Tells you that something broke
Observability
- Lets you ask arbitrary new questions after the fact
- Explores failure modes nobody anticipated (unknown unknowns)
- High-cardinality, high-dimensional data: user, tenant, build, region
- Tells you why: "only Android users on build 4.2 in eu-west hitting shard 7"
Logs, metrics and traces
| Signal | What it is | Great for | Weak at | Cost driver |
|---|---|---|---|---|
| Logs | Timestamped records of discrete events | Detail and context for one event; errors and audits | Aggregation and trends; expensive at high volume | Bytes ingested and indexed |
| Metrics | Numeric measurements aggregated over time | Dashboards, alerting, trends, capacity planning | Explaining individual requests | Number of unique time series (cardinality) |
| Traces | The causal tree of operations for one request across services | Finding where latency and errors come from in a call graph | Aggregate statistics; usually sampled | Spans stored (sampling rate) |
The signals are most powerful when they are linked: a metric spike leads to example traces (exemplars), and a slow span leads to the logs written during it, all joined by a shared trace ID. Press play to follow an incident from alert to root cause.
Logs
Free-text logs (User 42 placed order 81f2 in 31ms) are easy to write and painful to query. Structured logs emit key-value pairs, usually JSON, so you can filter and aggregate on any field without fragile regular expressions.
{
"ts": "2026-10-29T14:03:11.482Z",
"level": "error",
"service": "checkout",
"version": "4.2.0",
"msg": "payment failed",
"trace_id": "4bf92f3577b34da6a3ce929d0e0e4736",
"span_id": "00f067aa0ba902b7",
"order_id": "ord_81f2",
"customer_tier": "gold",
"error": "card_declined",
"duration_ms": 412
}- Log events, not narratives: one line per meaningful event with all its context, rather than five lines telling a story.
- Use levels deliberately:
errormeans someone should look;infofor business events;debugoff (or sampled) in production. - Never log secrets or raw personal data: passwords, tokens, card numbers. Redact at the source.
- Control volume: logs are usually the most expensive signal. Sample noisy success logs; keep all errors.
Correlation IDs and context propagation
A single user action may produce log lines in ten services. Give the request an ID at the edge, pass it along on every call, and include it in every log line, so one search returns the whole story. The W3C Trace Context standard defines the header used by OpenTelemetry and most vendors:
POST /v1/charges HTTP/1.1
Host: payments.internal
traceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01Metrics
- Counter
- A value that only goes up (and resets to zero on restart): requests served, errors, bytes sent. You almost always query its rate, such as
rate(http_requests_total[5m]). - Gauge
- A value that goes up and down: memory in use, queue depth, active connections, temperature.
- Histogram
- Counts observations into buckets (≤ 10 ms, ≤ 50 ms, ≤ 100 ms...). Percentiles are estimated at query time, and buckets from many instances can be summed, so you get a fleet-wide p99.
- Summary
- Computes quantiles inside each process. Accurate per instance, but quantiles cannot be aggregated across instances (averaging p99s is meaningless). Prefer histograms.
# Rate: requests per second, per route
sum by (route) (rate(http_requests_total[5m]))
# Errors: fraction of requests that returned 5xx
sum(rate(http_requests_total{status=~"5.."}[5m]))
/ sum(rate(http_requests_total[5m]))
# Duration: p99 latency across all instances, from histogram buckets
histogram_quantile(0.99, sum by (le) (rate(http_request_duration_seconds_bucket[5m])))What to measure: RED, USE and the golden signals
RED (for services)
- Rate: requests per second
- Errors: failed requests per second
- Duration: latency distribution (percentiles)
- Tom Wilkie's method for request-driven services
USE (for resources)
- Utilization: % of time the resource is busy
- Saturation: queued work it can't serve yet
- Errors: device or resource error counts
- Brendan Gregg's method for CPUs, disks, pools, NICs
Four golden signals
- Latency
- Traffic
- Errors
- Saturation (from Google's SRE book)
Distributed tracing
A trace is the tree of work done for one request. Each node is a span: an operation with a name, start time, duration, status, attributes (http.route, db.system) and a parent. All spans share the trace ID, which is how a backend stitches together spans reported independently by many services.
| Span | Service | Starts at | Duration |
|---|---|---|---|
POST /checkout (root) | gateway | 0 ms | 2,150 ms |
create_order | orders | 5 ms | 2,130 ms |
reserve_stock | inventory | 12 ms | 40 ms |
charge_card | payments | 15 ms | 2,100 ms |
POST card-network /authorize | payments | 20 ms | 1,900 ms |
OpenTelemetry
OpenTelemetry (OTel), a CNCF project formed in 2019 by merging OpenTracing and OpenCensus, is the vendor-neutral standard for telemetry: APIs and SDKs in every major language, auto-instrumentation for common frameworks, the OTLP wire protocol, and the Collector, a pipeline that receives, processes and exports data to any backend. Instrument once, then switch vendors by changing Collector configuration rather than code.
Sampling
Head-based sampling
- Decide at the start of the trace (keep 1%) and propagate the decision
- Cheap: unsampled requests record almost nothing
- Consistent: either every span is kept or none
- Blind: the decision is made before you know the request will fail
Tail-based sampling
- Buffer all spans, decide after the trace completes
- Keep every error and every slow trace, plus a small baseline
- All spans of a trace must reach the same Collector instance
- Costs memory and network to buffer everything briefly
Alerting on SLOs
Alert on symptoms users feel (errors, latency) rather than on causes (high CPU), which may be harmless or may never fire for a real outage. The best symptom alerts are built on service level objectives. See Availability & Reliability.
- SLI
- Service level indicator: a measured ratio of good events, such as the fraction of checkout requests that succeed in under 500 ms.
- SLO
- The target for an SLI over a window, such as 99.9% over 30 days.
- Error budget
- The allowed unreliability: 1 − SLO. At 99.9%, 0.1% of requests (about 43 minutes of full outage per 30 days) may fail.
- Burn rate
- How fast the budget is being consumed relative to plan. A burn rate of 1 uses exactly the whole budget over the window.
| Severity | Long window | Short window | Burn rate | Budget consumed |
|---|---|---|---|---|
| Page | 1 hour | 5 minutes | 14.4 | 2% |
| Page | 6 hours | 30 minutes | 6 | 5% |
| Ticket | 3 days | 6 hours | 1 | 10% |
groups:
- name: checkout-slo
rules:
- alert: CheckoutErrorBudgetFastBurn
expr: |
(
sum(rate(http_requests_total{job="checkout",status=~"5.."}[1h]))
/ sum(rate(http_requests_total{job="checkout"}[1h]))
) > (14.4 * 0.001)
and
(
sum(rate(http_requests_total{job="checkout",status=~"5.."}[5m]))
/ sum(rate(http_requests_total{job="checkout"}[5m]))
) > (14.4 * 0.001)
for: 2m
labels:
severity: page
annotations:
summary: "Checkout is burning its 30-day error budget 14x too fast"
runbook_url: "https://runbooks.example.com/checkout-errors"The tooling landscape
| Category | Open source | Notes |
|---|---|---|
| Instrumentation | OpenTelemetry SDKs and Collector | The de facto standard; supported by every major vendor |
| Metrics | Prometheus; Thanos, Mimir or VictoriaMetrics for scale | Pull-based scraping, PromQL; add-ons provide long-term, multi-cluster storage |
| Logs | ELK (Elasticsearch, Logstash, Kibana), Grafana Loki | Elasticsearch indexes full text (powerful, costly); Loki indexes labels only (cheap) |
| Traces | Jaeger, Grafana Tempo, Zipkin | Tempo stores traces in object storage and looks them up by ID |
| Visualization | Grafana, Kibana | Grafana can query and correlate all three signals |
| Managed | Datadog, New Relic, Honeycomb, Splunk, cloud-native suites | Trade cost for less operational work; Honeycomb pioneered high-cardinality event analysis |
Implementation
Store the request ID in request-scoped context so every log line includes it automatically, and forward it on downstream calls.
import contextvars
import json
import logging
import time
import uuid
import requests
request_id_var: contextvars.ContextVar[str] = contextvars.ContextVar("request_id", default="-")
class JsonFormatter(logging.Formatter):
def format(self, record: logging.LogRecord) -> str:
entry = {
"ts": self.formatTime(record, "%Y-%m-%dT%H:%M:%S") + f".{int(record.msecs):03d}",
"level": record.levelname.lower(),
"logger": record.name,
"msg": record.getMessage(),
"request_id": request_id_var.get(),
}
entry.update(getattr(record, "fields", {})) # structured extras
return json.dumps(entry)
handler = logging.StreamHandler()
handler.setFormatter(JsonFormatter())
log = logging.getLogger("checkout")
log.addHandler(handler)
log.setLevel(logging.INFO)
def handle_checkout(headers: dict[str, str]) -> None:
# Reuse the caller's ID so the whole call chain shares one ID
request_id_var.set(headers.get("x-request-id") or uuid.uuid4().hex)
start = time.perf_counter()
log.info("order placed", extra={"fields": {"order_id": "ord_81f2", "amount_cents": 4999}})
requests.post(
"http://payments.internal/charges",
headers={"x-request-id": request_id_var.get()}, # propagate downstream
timeout=2.0,
)
log.info("request finished",
extra={"fields": {"duration_ms": round((time.perf_counter() - start) * 1000, 1)}})Key takeaways
- Monitoring answers predefined questions; observability lets you investigate failures nobody predicted.
- Logs give detail, metrics give cheap aggregates and alerts, traces show where time goes across services; link them with trace IDs.
- Use structured logs with correlation IDs, and keep high-cardinality identifiers out of metric labels.
- Prefer histograms over summaries so percentiles can be aggregated across instances; track p99, not averages.
- Use RED for services, USE for resources, and the four golden signals as a checklist.
- Alert on SLO burn rates with multiple windows so pages are rare, significant and actionable.
Common pitfalls
- Putting user IDs, request IDs or raw URLs in metric labels and exploding cardinality.
- Alerting on causes (CPU at 80%) instead of user-facing symptoms, producing noisy pages.
- Averaging latency, or averaging per-instance p99s, which hides the tail.
- Not propagating trace context through queues and async jobs, leaving traces broken in half.
- Logging secrets or personal data, or logging so much at
infothat the bill dwarfs the compute cost.
Interview tips
- Name the three signals and what each is good for, then describe how you would link them.
- Define an SLO for the critical user journey and explain burn-rate alerting in one or two sentences.
- Mention head vs tail sampling if tracing comes up at scale: you keep errors without storing everything.
Real-world applications
- Prometheus and Grafana as the default metrics stack for Kubernetes clusters.
- OpenTelemetry instrumentation feeding Jaeger, Tempo or commercial backends across microservice fleets.
- SRE teams paging on multiwindow burn-rate alerts derived from SLOs.
Test yourself
You need fleet-wide p99 latency across 50 pods. Which metric type should each pod export?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.