The three signals and what each one cannot do
Logs are events, metrics are aggregates, traces are causal trees. Each one answers a question the other two cannot, and a trace id ties them together
At 02:00 your error-rate alert fires: 3 percent of checkouts are returning 500. You open the metrics dashboard and the error rate is confirmed, broken down by service: it is all payments. Which signal gets you to the cause fastest from here?
The last chapter defined observability as a property. This chapter is about the raw material: the three kinds of telemetry a system emits. Each has a shape, a cost profile, and a set of questions it answers well. More usefully for an engineer, each has a set of questions it cannot answer at all, and most wasted hours in incidents come from asking a signal a question it structurally cannot answer. By the end you will know which signal to open first for a given question, and how to pivot from one to the next without losing the request you were looking at.
Three shapes
Peter Bourgon’s 2017 post drew the picture most people now carry in their heads: a Venn diagram where the defining property of metrics is that they are aggregatable, of logs that they are discrete events, and of tracing that it is request-scoped. The three overlap, and much telemetry could be emitted as any of them, but each has a centre of gravity.
A log is an event. Something happened at a time, in a process, and here are the details. It is the oldest signal and the most flexible: a log line can carry any fields, arbitrarily high cardinality (user ids, request ids, SQL text), and free text for a human. Each line stands alone. Nothing links it to the line before or after except proximity.
A metric is an aggregate. A single number that summarises many events over a time window, identified by a name and a set of label key-value pairs: checkout_requests_total{job="gateway", http_response_status_code="200"}. The aggregation happens at the source: the process keeps a counter and increments it; the individual events that incremented it are not kept. What you store is a series of (timestamp, value) points per unique label combination.
A trace is a causal tree. One request, represented as a tree of spans. Each span is a timed operation with a name, a start time, a duration, attributes, and a parent. The gateway’s handling of GET /checkout is the root span; its call to orders is a child; orders’ database insert and its call to payments are children of that; and so on down. All spans in the tree share a trace id, a 128-bit random number minted at the root and propagated in an HTTP header (traceparent, per the W3C Trace Context spec) to every service the request touches.
Cardinality and cost
The reason the three exist as separate signals rather than one is cost, and the cost is governed by cardinality: the number of distinct values a field can take.
| Log | Metric | Trace | |
|---|---|---|---|
| Unit stored | one line per event | one point per series per interval | one span per operation per sampled request |
| Volume grows with | request rate × events per request × bytes per line | number of distinct label combinations (series), not request rate | request rate × spans per request × sample rate |
| High-cardinality fields | fine; it is a field in the line | fatal; every distinct value is a new series kept in memory | fine; it is a span attribute |
| Typical cost at 1000 req/s | 1 kB per request → 86 GB/day, plus indexing | a few thousand series → a few MB/day regardless of load | 5 spans × 500 B × 10% sampled → 22 GB/day |
| Query cost | scan or index lookup over the time range | pre-aggregated; a 30-day graph is cheap | fetch by trace id is cheap; search by attribute depends on the store |
A metric’s cost is independent of traffic: ten requests a second or ten thousand, the counter is still one series, and Prometheus stores a sample at about 1 to 2 bytes after compression. What drives metric cost is labels. Add user_id as a label and you have a series per user: a million users is a million series, each held in memory on the server. The metrics chapter makes this explode on purpose.
A log’s cost is proportional to traffic and to how much you write per request. A chatty service that writes five lines per request at 300 bytes each, at 1000 requests per second, produces 130 GB a day before compression. Loki stores compressed chunks and indexes only labels, which is why its label discipline is strict; Elasticsearch indexes every field, which is why it costs more per gigabyte. The structured-logging chapter is about writing fewer, denser lines.
A trace’s cost sits between the two and has a knob the others lack: sampling. Because a trace is only useful whole, you decide at the root whether to keep this request’s trace at all, and the decision propagates. Keeping 10 percent cuts the bill by 90 percent. It also means 90 percent of requests have no trace, which is the central weakness below.
What each one cannot do
This is the section to remember. Each signal has a question it cannot answer because of what it is, not because of a missing feature.
Metrics cannot tell you which request
An aggregate has, by construction, discarded the individuals. checkout_requests_total went from 184 230 to 184 231; the counter does not know, and cannot be made to know, that the increment was user 42’s request. The same is true of a histogram: it can tell you that 1 percent of requests took over 2 seconds, and it cannot tell you a single one of them. If you try to fix this by adding labels, you add series: user_id as a label on a histogram with 12 buckets and 1000 users is 14 000 series for one metric, and with a million users the server runs out of memory.
Metrics are for the question “how much, how often, how is it trending?” across a population. They are the right thing to alert on and the right thing to put on a dashboard. The moment you need one example, you have left what a metric can do. The link out is the exemplar: Prometheus and OpenTelemetry let a histogram observation carry a trace id alongside it, so a point on the p99 graph can link to one trace that landed in that bucket. The debugging-with-traces chapter in module three uses them.
Logs cannot tell you p99 without aggregation
A log line is one event, and a percentile is a statement about a population. To get p99 latency from logs you have to parse the duration out of every line in the window, collect them, sort them, and index at 99 percent. You did it in the last lab with grep | sort | awk over five minutes of one service; try it over a week of fifty services and it is a batch job. Loki can do it at query time with quantile_over_time, and it is correct, but it is scanning and parsing every line, so a graph covering a day of a busy service takes seconds to minutes to render and the cost scales with the log volume rather than with the number of series. Logs also cannot tell you about absence: the request that never arrived writes no line, and nothing in a log store notices.
Logs are for the question “what exactly happened here, in detail, with the full context?” For one request, a log line can carry the SQL text, the stack trace, the exact input that caused the problem. That detail is what the other two signals lack.
Traces cannot tell you about requests you did not sample
A trace is whole or useless, so the keep-or-drop decision is made at the root span, before anything is known about how the request will turn out. A head-sampling rate of 1 in 100 means 99 percent of requests leave no span anywhere. If the fault you are chasing affects 1 request in 20, you will find one trace of it per 2000 requests, and if you are chasing something that happens once an hour you will almost never see it. Tail sampling, which keeps the decision open until the trace is complete and then keeps all the slow and failed ones, fixes much of this at the price of buffering every trace in the collector; the sampling chapter in module four covers it. Even then a trace tells you about the request’s own operations, not about the state of the machine around it: the garbage-collection pause that caused the 400 ms gap between two spans appears in a trace as a gap.
Traces are for the question “where did the time go, and in what order, for this request?” Nothing else shows you a call tree with timings across process boundaries.
The one-liners
- A metric knows how many, not which.
- A log knows exactly what, not how many.
- A trace knows where the time went, for the requests it kept.
Correlation: the trace id on everything
Three signals in three stores give you three partial pictures of the same request. The question that matters is whether you can get from one to the others without copying timestamps.
The answer is to put the trace id on everything. The span has it by construction. The log line gets it as a field: the OpenTelemetry logging instrumentation for Python injects otelTraceID and otelSpanID into every log record once OTEL_PYTHON_LOG_CORRELATION=true is set; the lab’s own formatter (services/common/logging_setup.py) reads the current span directly instead, and the OTLP log handler stamps the ids on every record it ships to Loki. The structured-logging chapter shows the JSON form. The metric gets it as an exemplar on histogram observations. Now, from any one signal:
- metric → trace: click the exemplar on the spike, get a trace id, open the trace.
- trace → logs: Grafana’s Tempo data source has a “Trace to logs” setting that, from a span, runs a Loki query for the span’s time window with the trace id as a filter and the service name mapped to a Loki label.
- log → trace: Grafana’s Loki data source has derived fields: a regex such as
trace_id=(\w+)run against each log line, or a match on a label or structured-metadata field namedtrace_id, with an internal link to the Tempo data source using${__value.raw}, so the trace id on a log line becomes a button. - trace → metrics: the span’s
service.nameand the span’s time window give you the labels and the range for the service’s RED panels.
The W3C traceparent header is what makes the id the same in every service. It looks like 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01: version, 128-bit trace id, 64-bit parent span id, and flags, where the last bit is “sampled”. Every service that receives it continues the same trace rather than starting a new one. You will exploit this in the lab by sending your own traceparent, so you know the trace id of your request before the system does.
Which signal first
In practice an investigation moves in a fixed direction. Metrics tell you something is wrong and roughly where: this service, this endpoint, since this deploy. A trace tells you where inside the request the time or the error is. Logs tell you the exact detail at that point. Each step narrows from population to individual, and each step needs the shared id to pivot.
The reverse direction also exists and is underused. A customer gives you an order id; a log search finds the request’s canonical line; its trace id opens the trace; the trace shows the slow hop; a metric query shows whether that hop is slow for everyone. Starting from one request and generalising to the population is how you find out whether a complaint is one user or an outage.
Neither direction works if the three signals live in three products that do not share the id. That is the practical content of the three-pillars critique from the last chapter, and it is why every tool choice later in this course is evaluated first on whether the trace id survives the trip.
The demo app, instrumented
From this chapter on, the lab app runs with OTEL_SDK_DISABLED=false and the telemetry compose profile, which starts the OpenTelemetry Collector (OTLP on 4317 and 4318), Prometheus (9090), Loki (3100), Tempo (3200) and Grafana (3000). The three services are auto-instrumented: the FastAPI and HTTP-client instrumentations create spans for every inbound request and outbound call, propagate traceparent, and record an HTTP server duration histogram (http.server.duration under the instrumentations’ default, older conventions; the OpenTelemetry chapter switches on the stable http.server.request.duration). The Collector receives everything over OTLP and fans out: metrics to a Prometheus scrape endpoint, logs to Loki, traces to Tempo. The Collector’s Prometheus exporter turns service.name into the job label, and Loki promotes it to the stream label service_name, so the same name selects the service in all three stores.
You will add two things to the gateway by hand: a counter and a log line that carries the trace id. Then you will send one request with a trace id you chose, and find that request in all three stores.
You will switch telemetry on, add a counter and a correlated log line to the gateway, fire one request with a known trace id, and find it in Prometheus, Loki and Tempo before pivoting between them in Grafana.
1. Start the app with telemetry on.
cd labs/observability
OTEL_SDK_DISABLED=false FAULT_SLOW_PAYMENTS_PCT=5 docker compose --profile telemetry up -d
docker compose ps --format 'table {{.Name}}\t{{.Status}}\t{{.Ports}}'
curl -s localhost:9090/-/ready; echo; curl -s localhost:3100/ready; echo; curl -s localhost:3200/ready; echootel-collector, prometheus, loki, tempo and grafana. The three readiness probes answer Prometheus Server is Ready., ready and ready. Loki can take 15 to 30 seconds to report ready on first start; re-run the probe if it says Ingester not ready.2. Add a counter and a correlated log line to the gateway.
Open services/gateway/app.py. It already imports trace and gets its logger, log, from create_app. Below the line app, log = create_app("gateway", lifespan=lifespan), add:
from opentelemetry import metrics
meter = metrics.get_meter("gateway")
checkout_requests = meter.create_counter(
"checkout.requests", unit="1",
description="Checkout requests handled by the gateway",
)Inside the checkout handler, directly after the line status = body.get("status", ...) and before if resp.status_code >= 400:, so failed checkouts are counted too, add:
ctx = trace.get_current_span().get_span_context()
trace_id = format(ctx.trace_id, "032x")
checkout_requests.add(1, {"http.response.status_code": resp.status_code, "vip": vip})
log.info("checkout done user=%s items=%s order_id=%s status=%s ms=%d trace_id=%s",
user, effective_items, order_id, resp.status_code, ms, trace_id)Rebuild only the gateway:
docker compose up -d --build gatewayOTEL_SDK_DISABLED were still true, get_meter and get_current_span would return no-op objects and the counter would silently go nowhere; the code is the same either way, which is the point of the SDK being switchable by environment. The counter is named with dots in OpenTelemetry style; the collector’s Prometheus exporter will rename it checkout_requests_total, replacing dots with underscores and adding _total because it is a monotonic sum.3. Send one request whose trace id you chose.
TRACE=$(openssl rand -hex 16); SPAN=$(openssl rand -hex 8)
echo "trace id: $TRACE"
curl -s -H "traceparent: 00-$TRACE-$SPAN-01" 'http://localhost:8080/checkout?user=42&items=3' | jq -c .{"order_id":...,"status":"paid","ms":...}. Because you sent a valid traceparent with the sampled flag set, the gateway’s auto-instrumentation continued your trace rather than starting a new one, and propagated the same id to orders and payments. You now know the id of a request before any store has indexed it, which is the cleanest way to test correlation end to end.4. Find the counter increment in Prometheus.
Metrics are the slowest signal to arrive: the Python SDK exports every 60 seconds by default (OTEL_METRIC_EXPORT_INTERVAL, in milliseconds) and Prometheus scrapes the collector every 5 seconds. Wait about 70 seconds, then:
curl -s 'http://localhost:9090/api/v1/query' --data-urlencode 'query=checkout_requests_total{job="gateway"}' | jq '.data.result[] | {labels: .metric, value: .value[1]}'job="gateway", http_response_status_code="200" and vip="false" (plus the resource attributes the Collector copies onto every series, such as service_name and deployment_environment) (and a vip="true" series once the load generator has hit a user divisible by 97). The value is the number of checkouts since the gateway restarted; yours is one of them, indistinguishable from the rest. Nothing in this output can tell you which increment was trace $TRACE: that is the metric’s limitation, seen directly. Open http://localhost:9090/graph, enter rate(checkout_requests_total[1m]), and you have the request rate per second broken down by status, which no log search gives you cheaply.5. Find the log line in Loki.
curl -s -G 'http://localhost:3100/loki/api/v1/query_range' \
--data-urlencode "query={service_name=\"gateway\"} |= \"$TRACE\"" \
--data-urlencode 'since=10m' | jq -r '.data.result[].values[][1]'checkout done user=42 items=3 order_id=... status=200 ms=... trace_id=<your id>. The |= operator is a line filter: Loki scanned the gateway stream for the ten minutes and returned the lines containing your trace id. This is the query you could not run in the last chapter: given a request, here is exactly what the gateway recorded about it, including the user. The line filter works here because you wrote the trace id into the message text; the lab’s other log fields, trace_id included, travel as structured metadata beside the line, which the structured-logging chapter queries. curl -s localhost:3100/loki/api/v1/labels | jq lists the stream labels: service_name, deployment_environment, service_version.6. Find the trace in Tempo.
curl -s "http://localhost:3200/api/traces/$TRACE" \
| jq -r '.batches[].scopeSpans[].spans[] | "\(((.endTimeUnixNano|tonumber) - (.startTimeUnixNano|tonumber)) / 1e6 | floor) ms\t\(.name)"' \
| sort -rnGET /checkout on the gateway and its outbound POST to orders; POST /orders on orders, its three database spans (INSERT, INSERT, UPDATE) and its outbound POST to payments; POST /charge on payments and its Redis GET and SET. Their durations nest: the gateway span is the longest and each child is shorter. If your request was one of the 5 percent, the payments span is 1500 to 3000 ms and everything else is tens of milliseconds, which is the answer to the last chapter’s first question. Run step 3 again until you catch a slow one.7. Pivot between them in Grafana.
Open http://localhost:3000 (admin / admin) and go to Explore. Pick the Loki data source and run {service_name="gateway"} |= "checkout done". Expand your line. The lab’s Loki data source is provisioned with a derived field named trace_id that matches the trace_id structured-metadata field the OTLP log handler attached to the line, with an internal link to the Tempo data source and query ${__value.raw}. It appears in the log details as a trace_id field with a View trace button.
http.method, http.status_code, http.route, plus the lab’s own order.id and payment.amount_cents) and a Logs for this span button, which comes from the Tempo data source’s “Trace to logs” setting: it runs {service_name="payments"} | trace_id="<id>" over the span’s time window, with service.name mapped to the service_name label. Click it and you are back in logs, now looking at payments’ lines for this request. Three stores, one id, and you never typed a timestamp. The lab’s provisioning files are in grafana/provisioning/datasources/; read them to see the two settings that make the pivots work.otel/collector.yaml and add a probabilistic_sampler processor with sampling_percentage: 10 to the traces pipeline, then docker compose up -d otel-collector and repeat step 3 ten times. On average one of your ten trace ids returns a trace from Tempo; the other nine return nothing, although every one of them has a log line in Loki and counted in Prometheus. That is the trace’s weakness made concrete: the signal that best explains a slow request exists only for the requests you chose, in advance and at random, to keep. Then make the opposite mistake: add user as an attribute on the counter, checkout_requests.add(1, {"user": user}), rebuild, and watch curl -s localhost:9090/api/v1/status/tsdb | jq .data.headStats.numSeries climb by one series per distinct user the load generator touches. One thousand users is a thousand series for a counter that used to be two; a million users would be the end of the Prometheus server. Undo both before the next chapter: remove the sampler from otel/collector.yaml and run docker compose restart otel-collector, and change the counter’s attributes back to the step 2 version and rebuild the gateway. The step 2 counter and log line stay; the structured-logging chapter starts from them.A customer-support ticket says: checkout for account 8831 has been intermittently slow for two days, maybe one time in ten. Nobody else has complained. You have metrics, structured logs with trace ids, and traces head-sampled at 1 percent, all in Grafana. Where do you start?
- POST Metrics, tracing, and logging Peter Bourgon, 2017
The Venn diagram this chapter is built on: aggregatable, request-scoped, and events as the defining properties, with the cost gradient between them. Ten minutes; read it before anything else here.
- TALK Three Pillars with Zero Answers: A New Observability Scorecard Ben Sigelman, 2018
The argument that having all three signals in three tools answers nothing unless they connect, and a scorecard for judging a setup by detection and explanation instead. The slides are the primary source; the first third is the critique, the rest the scorecard.
- PAPER Dapper, a Large-Scale Distributed Systems Tracing Infrastructure Sigelman et al., Google, 2010
The paper that defined the trace as a tree of spans with a propagated id, and that chose sampling as the way to make it affordable. The sampling discussion is the origin of the limitation in this chapter. The tracing chapter returns to it in depth. Read: sections 2 (the data model: trees, spans, annotations) and 4.4 (sampling) now; skip the Google-specific deployment detail in 5.
- DOC OpenTelemetry concepts: signals
OpenTelemetry's own definitions of traces, metrics, logs and baggage, which the rest of the course uses. Each sub-page is short; read the traces page for span, span context and context propagation, which the lab exercised with the traceparent header.
- DOC W3C Trace Context
The specification of the traceparent header you hand-built in the lab: the version, trace id, parent id and flags fields, and what a service must do when it receives one. Read section 3 for the header format; the rest is for implementers.
- DOC Configure trace to logs (Tempo data source)
How the span-to-logs pivot in the lab is wired: the Loki data source, the time shifts, the span-attribute-to-label mapping, and the custom query variables. Pair it with the Loki data source page on derived fields for the reverse direction.
- DOC Configure the Loki data source: derived fields
The derived fields section is the log-to-trace link: a regex over the line or a label match, an internal link to a tracing data source and the ${__value.raw} variable. Skip the authentication and caching sections.
- BOOK Distributed Systems Observability Cindy Sridharan, 2018
Chapter 4 is the fairest short treatment of what each of the three signals is good and bad at, written before the vendors took sides. Free from O'Reilly. Read: chapter 4, the three pillars of observability.
All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.