Observability: metrics, logs and traces
What metrics, logs and traces are each for and how a trace id joins them, the golden signals, the cost of a label, W3C trace context and head versus tail sampling tested in C#, logs that help, and how telemetry fails.
ConceptCore23 min readUpdated
- 1 architecture diagram
- 1 sequence flow
- 3 code samples
- 5 interviewer follow-ups
- 4 self-checks
On this page11 sectionsHLDLLDSenior depth
Read first: Latency, throughput and queues, Tail latency and overload
- Say what metrics, logs and traces are each for, and how a trace id joins them.
- Measure the four golden signals as the caller sees them, and read percentiles from histograms.
- Compute how many series a set of labels can create, and say how to keep it bounded.
- Compare head and tail sampling of traces, and say what each costs.
- Name the ways telemetry itself fails and the defence for each.
3 code samples (105 lines), collapsed so the explanation stays in focus.
Every incident review asks the same three questions. How soon did the team know? How did it know? How long did finding the cause take? Observability is the engineering that turns the answers into "within a minute", "from an alert about user pain" and "by following one trace", instead of "a customer told us", "someone noticed a graph" and "three people searching logs". It is also where interviews separate people who have run systems from people who have drawn them: once the boxes are on the whiteboard, "how would you know it is working?" comes next.
This lesson is about the signals: what metrics, logs and traces are each for, what to measure, what a label costs, how traces are sampled, and how telemetry itself fails. The next lesson turns the signals into objectives and alerts. The numbers here come from small programs you can run, so the claims about cost and sampling are tested and not just asserted.
Three kinds of telemetry answer three different questions, and a system needs all of them because none can do the others' job.
| Signal | What it is | Good for | Limits and cost |
|---|---|---|---|
| Metrics | Numbers sampled over time and aggregated: counters, gauges, histograms | Is something wrong, and how badly? Dashboards, alerts, capacity | Cheap per event, but each distinct combination of label values is a separate series, so cardinality is the cost |
| Logs | Discrete events with context: a line or a structured record | What exactly happened for this request or this user? | Expensive at volume, hard to aggregate, easy to fill with noise or personal data |
| Traces | The causal timeline of one request across services, as spans | Where did the time go? Which dependency failed? | Instrumentation in every hop, and storing all of them costs too much, so they are sampled |
Observability is the ability to ask a new question about a running system from its outputs, without shipping new code. Metrics tell you that something is wrong, traces where and logs why, provided the three can be joined. Joining takes a trace id in every log line and a way to jump from a metric spike to an example trace (an exemplar: a trace id attached to a histogram bucket sample). The id travels between services in a header, and the W3C Trace Context standard defines it: traceparent: 00-<32 hex digits of trace id>-<16 hex digits of parent span id>-<flags>, where one flag bit says whether the trace is sampled. Some teams go a step further and emit one wide structured event per request per service, with dozens of attributes, and derive metrics and traces from the events. Any dimension then becomes queryable, at the price of storing much more.
Telemetry leaves the process through an SDK (OpenTelemetry is the vendor-neutral standard for the API, the SDKs and the wire protocol, OTLP) and reaches a local agent or collector that batches, retries and drops when its buffer is full. From there each type goes to a store built for it: a time-series database for metrics, an indexed or columnar store for logs, a store keyed by trace id for traces. Alert rules and dashboards read the stores. Every leg is a system with a capacity, a cost and failure modes of its own, and the later sections come back to them.
Start from the user, not the machine.
- The four golden signals from Google's SRE book: latency (of successful and of failed requests separately, because a fast error flatters the average), traffic (demand), errors (explicit, such as a 500, implicit, such as a 200 with the wrong content, and by policy, such as a response slower than the promise) and saturation (how full the most constrained resource is).
- RED for request-driven services: rate, errors, duration. USE for resources such as disks, links and pools: utilization, saturation, errors. RED asks how the service is doing for its callers, USE asks which resource is the bottleneck.
- Percentiles, not averages. Latency is skewed and the tail is what users feel (see tail latency and overload). Record histograms, because percentiles cannot be averaged: the mean of per-server p99s was 69% too high in the probabilistic data structures lesson, while mergeable histograms or sketches stayed accurate. A bucketed histogram knows only a count per bucket, so a percentile read from it is an estimate whose error is the width of the bucket it falls in. Put a bucket boundary exactly at each latency you promise (300 ms, say, in an objective of the kind the next lesson defines), and then "the share of requests faster than 300 ms" is exact.
- Measure where the caller stands. A server-side timer starts after the request has waited in the network and the load balancer, and it never sees the requests that did not arrive. Measure at the edge or in the client, and add synthetic probes that exercise the whole path from outside.
- Page on symptoms, not causes. High CPU is a cause that may mean nothing. Failing checkouts are a symptom that always means something. Keep cause metrics for dashboards and diagnosis.
A metric with labels is not one time series but one per combination of label values that occurs, and the store pays per series: memory for the index, disk for the samples, CPU for every query that touches it (the time-series databases lesson shows why, and the metrics monitoring case study designs the whole system). The number of series is therefore bounded by the product of the number of values each label can take, which makes it easy to blow up by accident.
C# · The most series a metric can create: the product of the number of values each of its…
using System;
using System.Diagnostics;
using System.Linq;
// The most series a metric can create: the product of the number of values each of its labels can take.
long SeriesCount(params int[] valuesPerLabel) => valuesPerLabel.Aggregate(1L, (all, values) => all * values);
// http_requests_total{endpoint, method, status_class, region, pod}: 25 endpoints, 4 methods, 5 status classes, 6 regions, 50 pods.
long counterSeries = SeriesCount(25, 4, 5, 6, 50);
Debug.Assert(counterSeries == 150_000);
// A histogram stores one series per bucket (12 finite buckets and +Inf) plus a sum and a count: 15 times as many.
long histogramSeries = counterSeries * (12 + 1 + 2);
Debug.Assert(histogramSeries == 2_250_000);
// One careless label with a million values, such as a user id, turns the same counter into 150 billion series.
Debug.Assert(SeriesCount(25, 4, 5, 6, 50, 1_000_000) == 150_000_000_000);The counter is already 150,000 series. As a histogram it is 2.25 million, since every bucket is a series of its own. One label with unbounded values (a user id, a request id, an email address, a raw URL with ids inside it, an error message) multiplies everything by the number of distinct values. This is the usual reason a monitoring bill doubles after a release, or a metrics store runs out of memory.
- Labels take few, bounded values. Use the route template (
/orders/{id}) and not the raw path, the status class, the region, the version. Put unbounded identifiers in logs and traces, where one record costs the same however many distinct values exist. - Watch churn. A pod or instance label creates new series on every deploy and autoscaling event, and the old ones stay in the index until they age out. Aggregate away per-instance labels before long-term storage, and keep them only where instances are debugged.
- Enforce, do not hope. Allow-lists of labels in the shared instrumentation library, a limit on series per team at ingestion, a review of new labels in code review, and a report of the top metrics by series count with an owner for each.
- Use the right tool for high-cardinality questions. "Which customers saw errors?" is a question for events or traces, stores built to filter on any attribute, and not for a metric label.
A trace records one request's path through the system as a tree of spans. A span has the trace id shared by the whole tree, its own span id, its parent's span id, a name, a start time and a duration, attributes (route, status, customer tier, never secrets) and a status. Propagation makes it work: every call carries the trace context to the next hop, in an HTTP header or in the headers of a queue message, and each service creates its spans as children of what it received. A consumer that handles a batch of messages from many traces uses span links to point back at them instead of choosing one parent. A gap in propagation (a thread pool that drops the context, a queue that strips headers, a third party) cuts the tree, and closing those gaps is most of the work of adopting tracing.
Spans are cheap to create and expensive to keep.
traffic: 20,000 requests/s x 12 spans = 240,000 spans/s
x 500 B per span = 120 MB/s, about 10 TB a day
head sampling at 1%: about 100 GB a day
tail sampling buffer: 240,000 spans/s x 10 s x 500 B = 1.2 GBKeeping everything is rarely affordable, so traces are sampled, and when the decision is made matters more than the rate.
- Head sampling decides when the root span starts, before anything is known about the request, and passes the decision down in the trace flags. It is cheap, because a dropped trace costs almost nothing anywhere. It is also blind: it keeps the interesting requests at the same rate as the boring ones.
- Tail sampling decides when the trace is complete: keep every error, every request slower than a threshold and a small share of the rest. It keeps what someone will want to look at. The price is that every span has to be collected and held until the trace finishes, and all the spans of a trace must reach the same decision-maker.
For head sampling to work across services without any coordination, the decision must be a function of the trace id, so every service reaches the same answer and a trace is kept whole or not at all. The usual setup is a "parent-based" sampler: honour the decision in the incoming header, and at the root decide by the trace id. The types below parse the W3C header and implement such a sampler. The statements after them compare head and tail sampling on 200,000 requests, one in a hundred of which fails, with lognormal latency.
C# · The W3C Trace Context header: traceparent: 00-<trace id: 32 hex digits>-<parent span id…
using System;
using System.Globalization;
// The W3C Trace Context header: traceparent: 00-<trace id: 32 hex digits>-<parent span id: 16 hex digits>-<flags: 2 hex digits>.
public sealed record TraceContext(string TraceId, string ParentId, bool Sampled)
{
public static bool TryParse(string header, out TraceContext context)
{
context = null;
var parts = header?.Split('-');
if (parts == null || parts.Length != 4 || parts[0] != "00") return false; // this sketch accepts version 00 only
if (!IsHex(parts[1], 32) || !IsHex(parts[2], 16) || !IsHex(parts[3], 2)) return false;
if (parts[1] == new string('0', 32) || parts[2] == new string('0', 16)) return false; // all zeros is not a valid id
bool sampled = (byte.Parse(parts[3], NumberStyles.HexNumber, CultureInfo.InvariantCulture) & 1) == 1;
context = new TraceContext(parts[1], parts[2], sampled);
return true;
}
public string ToHeader() => $"00-{TraceId}-{ParentId}-{(Sampled ? "01" : "00")}";
// A service that handles the request records a span, then passes the same trace id on with its own span id as the new parent.
public TraceContext Child(Random random)
{
var bytes = new byte[8];
random.NextBytes(bytes);
return this with { ParentId = Convert.ToHexString(bytes).ToLowerInvariant() };
}
private static bool IsHex(string text, int length)
{
if (text.Length != length) return false;
foreach (char c in text)
if (!(c >= '0' && c <= '9') && !(c >= 'a' && c <= 'f')) return false; // the specification asks for lower case
return true;
}
}
public static class Sampler
{
// Head sampling that every service computes on its own: keep the trace if a number made from its id is below the ratio.
// The same id gives the same answer in every service, so a trace is kept whole or not at all, and a trace kept at
// 1% is also kept at any higher ratio, so services with different rates still agree about the traces they share.
public static bool Keep(string traceId, double ratio)
{
ulong low = ulong.Parse(traceId.Substring(16), NumberStyles.HexNumber, CultureInfo.InvariantCulture);
return low < ratio * ulong.MaxValue;
}
}C# · The header survives a hop, and invalid ones are refused.
using System;
using System.Diagnostics;
using System.Linq;
// The header survives a hop, and invalid ones are refused.
const string incoming = "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01";
bool parsed = TraceContext.TryParse(incoming, out var context);
Debug.Assert(parsed && context.Sampled && context.ToHeader() == incoming);
var downstream = context.Child(new Random(3));
bool reparsed = TraceContext.TryParse(downstream.ToHeader(), out _);
Debug.Assert(downstream.TraceId == context.TraceId && downstream.ParentId != context.ParentId && reparsed);
Debug.Assert(!TraceContext.TryParse("00-00000000000000000000000000000000-00f067aa0ba902b7-01", out _)); // an all-zero trace id
Debug.Assert(!TraceContext.TryParse("00-4BF92F3577B34DA6A3CE929D0E0E4736-00f067aa0ba902b7-01", out _)); // upper case
// 200,000 requests: one in a hundred fails, and latency is lognormal with a median of 20 ms. Which requests keep a trace?
var traceRandom = new Random(8);
double Gaussian() => Math.Sqrt(-2 * Math.Log(1 - traceRandom.NextDouble())) * Math.Cos(2 * Math.PI * traceRandom.NextDouble());
string NewTraceId()
{
var bytes = new byte[16];
traceRandom.NextBytes(bytes);
return Convert.ToHexString(bytes).ToLowerInvariant();
}
var requests = Enumerable.Range(0, 200_000).Select(_ => (TraceId: NewTraceId(), Failed: traceRandom.NextDouble() < 0.01, Millis: 20 * Math.Exp(0.6 * Gaussian()))).ToArray();
double slowCutoff = requests.Select(r => r.Millis).OrderBy(m => m).ElementAt(requests.Length * 99 / 100); // the slowest 1%
// Head sampling decides when the request starts, before anyone knows whether it will be interesting.
var head = requests.Select(r => Sampler.Keep(r.TraceId, 0.01)).ToArray();
// Tail sampling decides when the trace is complete: keep every failure, every slow request and 1% of the rest.
var tail = requests.Select(r => r.Failed || r.Millis >= slowCutoff || Sampler.Keep(r.TraceId, 0.01)).ToArray();
double Share(bool[] kept, Func<(string TraceId, bool Failed, double Millis), bool> interesting) =>
(double)Enumerable.Range(0, requests.Length).Count(i => kept[i] && interesting(requests[i])) / requests.Count(interesting);
Debug.Assert(requests.Count(r => r.Failed) == 2_026 && requests.Count(r => r.Millis >= slowCutoff) == 2_000);
Debug.Assert(head.Count(k => k) == 2_059); // about 1% of the traces
Debug.Assert(Share(head, r => r.Failed) < 0.01 && Share(head, r => r.Millis >= slowCutoff) < 0.01); // and about 1% of what matters
Debug.Assert(tail.Count(k => k) == 6_038); // 2.9 times as many traces
Debug.Assert(Share(tail, r => r.Failed) == 1.0 && Share(tail, r => r.Millis >= slowCutoff) == 1.0);
// A trace kept at 1% is kept at any higher ratio too.
Debug.Assert(requests.All(r => !Sampler.Keep(r.TraceId, 0.01) || Sampler.Keep(r.TraceId, 0.10)));Head sampling at 1% kept 2,059 traces and, as it must, about 1% of what mattered: 0.8% of the failures and 0.9% of the slowest requests. Tail sampling kept 6,038 traces, 2.9 times as many, and every failure and every slow request among them. When an incident hits a rare request type, the head-sampled store may hold two traces of it, or none, and the tail-sampled one holds the evidence.
In practice services (or a local agent) send every span to a collector tier. Because all spans of a trace have to meet in one place, the tier routes by trace id, with consistent hashing as in the distributed cache design, to a pool of samplers. Each sampler holds the spans of the traces it owns until a wait time passes or the root span ends, then applies its policies: errors, latency above a threshold, attributes such as a VIP customer, and a probabilistic share of the rest. The buffer is the cost (1.2 GB in the estimate above), and a sampler that restarts loses the traces it was holding. A common compromise is a cheap head sample at the SDK for the highest-volume paths, tail sampling for the rest, and a rate cap so a traffic spike cannot flood the store.
Four mistakes recur.
- Metrics from sampled traces. Request counts, error rates and latency percentiles must be computed from all requests before sampling. Tail sampling over-represents errors and slow requests on purpose, so a latency chart built from kept traces is wrong. If you must estimate from samples, record the sampling probability on each kept trace and weight by its inverse.
- Exemplars that point nowhere. A histogram sample links to a trace id, and if sampling dropped that trace the link is dead. Keep the traces that exemplars reference.
- Collectors that block. A slow or full collector must make the SDK drop spans and count the drops, never block the request path.
- Context lost at async boundaries. Check propagation through every queue, thread pool and callback with a test that asserts the trace id comes out the other side.
Logs are the most flexible signal and the easiest to ruin. What makes them useful:
- Structured. One record per event, with stable field names, and not prose to be parsed with regular expressions. A parsing rule that silently breaks when someone rewords a message is a classic way to lose an alert.
- Correlated. Every line carries the trace id and span id, and the tenant or request id. The error response returned to the user includes the same id, so a support ticket leads straight to the trace.
- Disciplined levels. Error is for what needs attention, not for every handled exception. Debug is off in production, or sampled.
- One line per event, not per iteration. A log line inside a loop over a million items is an incident waiting to happen. Log the summary.
- Safe. Never write secrets, tokens, card numbers or raw personal data, redact in the logging library, and treat the log store as sensitive data with access control and a retention period (privacy law may set a limit).
- Tiered and bounded. A few days on fast searchable storage, months in cheap object storage, and rate limits so that a logging loop cannot fill a disk or the network. Logs are often the largest line in an observability bill, and most of the volume is never read. The logs and streams lesson covers the pipeline underneath.
- Not the source of truth for alerts. Count what matters with a metric at the source. A metric derived from log text is fine for a one-off question.
Telemetry is a system, so it has failure modes of its own, and they tend to appear at the worst moment.
| Failure | What goes wrong | Defence |
|---|---|---|
| Monitoring shares fate with production | The same network, cluster, identity provider or region fails, and dashboards and pager go dark exactly when needed | Run alerting and paging on an independent path, probe from outside, and monitor the monitoring |
| Silence read as health | A dead exporter or a broken pipeline sends nothing, so "errors above x" never fires | Alert on missing data, and run a heartbeat alert that must always fire and pages when it stops (a dead man's switch) |
| Cardinality blow-up | One new label multiplies the series; the store slows, runs out of memory or the bill multiplies | Label review, per-team limits, a top-series report, rules that drop or aggregate |
| Sampling bias | Charts built from sampled traces over-count errors or miss rare paths | Compute metrics before sampling; weight by the sampling probability |
| Telemetry takes the system down | Synchronous logging blocks threads, a log loop fills the disk, a slow collector backs up the service | Asynchronous export, bounded buffers that drop and count, rate limits, separate volumes |
| Clock skew and ordering | Logs from two hosts interleave wrongly, and spans show negative durations | Monotonic clocks for durations, synchronised time, causal ids and not timestamps for order |
Interviewer follow-upL5What is the difference between metrics, logs and traces, and when do you use each?How to answer
Metrics are cheap aggregated numbers over time, used to see that something is wrong and to alert. Traces show the path and timing of one request across services, used to find where the time or the error is. Logs are detailed events, used to find out why. They are joined by a trace id in every log line and by exemplars from metric buckets to traces. The cost per event grows from metrics to logs to traces, which is why traces are sampled and metric labels are restricted.
Interviewer follow-upL6The metrics bill tripled after a release. What happened and what do you do?How to answer
Almost certainly a label with many values (a user or request id, a raw URL, an error message), a new per-pod or per-instance label that churns on every deploy, or a histogram with many more buckets. Find the metrics with the most series, find the new label in the diff, and drop or aggregate it with a relabel rule right away. Then move the dimension to logs or traces, add a label allow-list and a series limit per team, and report series count by owner so it cannot happen silently again.
Interviewer follow-upL6The p99 dashboard looks fine, but users say the product is slow. What do you check?How to answer
Where it is measured (a server-side timer misses the network, queueing and the requests that never arrived), how it is aggregated (a mean of per-server p99s is wrong; merge histograms), whether the slow users are a segment that the aggregate hides (a region, a device, a tenant) and whether the tail beyond p99 is the problem. Also check the SLI itself: errors that return 200, timeouts counted as missing data and retries that hide failures. Add client-side measurement or real user monitoring, and probes from outside.
Interviewer follow-upL6A system handles 20,000 requests a second. How would you sample traces?How to answer
Do the arithmetic first: 20,000 requests × 12 spans is 240,000 spans a second, about 120 MB/s or 10 TB a day at 500 bytes a span, so keeping everything is out. Head sampling at 1% costs about 100 GB a day but keeps only 1% of the failures and slow requests, which are the traces people open. Tail sampling keeps every error and slow request plus a baseline, at the price of a collector tier that routes by trace id and holds about 1.2 GB for a 10-second wait. The usual answer is tail sampling for the bulk, a cheap head sample at the SDK on the busiest paths, a rate cap against spikes, and metrics computed before any sampling.
Interviewer follow-upL7You own observability for 2,000 services. What do you standardize, and what do you leave to teams?How to answer
Standardize the paved road: one instrumentation library (OpenTelemetry) with default metrics, names, labels and trace propagation; generated dashboards; central collectors with tail sampling routed by trace id; retention tiers; and guardrails for cardinality and cost with per-team quotas and attribution. Leave the choice of user journeys, SLIs and runbooks to the service owners, with a review for the critical paths. Measure the platform itself: share of pages that needed action, time to detect and mitigate, telemetry cost per request, and gaps in propagation.
When the prompt is "how would you monitor or debug this?", cover four things, each in a sentence or two.
- What you measure. The golden signals as the caller sees them, RED for services and USE for resources, recorded as histograms.
- How the signals join. A trace id in every log line and exemplars from metrics to traces, so one alert leads to one trace and its logs.
- What it costs. Labels bounded to a few values (five labels already gave 150,000 series), traces tail-sampled to keep errors and slow requests plus a baseline, logs tiered and rate-limited.
- How it fails. Telemetry that degrades before the product does, monitoring on an independent path, and alerts on silence.
Metrics show that something is wrong, traces where, logs why, and a trace id in every log line (with exemplars from metrics to traces) joins them. Measure the four golden signals as the caller sees them, record histograms and not averages of percentiles, and treat every label as a multiplier on cost: five labels made 150,000 series, a histogram of them 2.25 million, and one id label would make 150 billion. Traces are sampled because they are expensive. The W3C traceparent header carries the trace id. Head sampling decides from it at the start and is cheap and blind (1% kept 0.8% of the failures in the test), while tail sampling keeps every failure and slow request at 2.9 times the stored traces, with a buffer, routing by trace id, and metrics that must be computed before sampling. Logs should be structured, correlated, bounded and free of secrets. Telemetry fails like any system, so give it an independent path, alert on silence and let it degrade before the product does.
Try answering out loud before you reveal each answer.
QuestionWhat question does each of metrics, logs and traces answer best, and what joins them?Reveal answer
Metrics show that something is wrong and how badly (cheap, aggregated, good for alerts). Traces show where the time or the error is, across services. Logs show why, in detail for one event. A trace id in every log line, and exemplars (trace ids attached to histogram buckets), join them, so an alert can lead to an example trace and its logs.
QuestionA metric has the labels endpoint (25 values), method (4), status class (5), region (6) and pod (50). How many series can it create, and how many as a histogram with 12 buckets?Reveal answer
25 × 4 × 5 × 6 × 50 = 150,000 series as a counter. A histogram adds a series for each bucket (12 finite buckets and +Inf) plus a sum and a count, 15 times as many, so 2.25 million. A user id label with a million values would multiply the counter to 150 billion.
QuestionThe metrics bill tripled after a release. What do you check first?Reveal answer
The number of series per metric, to find which grew, and the labels of that metric in the diff: an unbounded value (user id, request id, raw URL, message text), a per-pod label that churns on deploy, or many more histogram buckets. Drop or aggregate the label now, then move the dimension to logs or traces and add limits and review so it cannot recur.
QuestionWhy can tail sampling not be decided separately by each service?Reveal answer
The decision depends on the whole trace (was there an error anywhere, how long did it take in total), and each service sees only its own spans. All spans of a trace therefore have to reach one place, which holds them until the trace is done. That is why collectors route by trace id and why the buffer costs memory.
- Beyer, Jones, Petoff and Murphy (eds.), Site Reliability Engineering, O'Reilly, 2016, chapter Monitoring Distributed Systems (opens in a new tab): the four golden signals, symptoms versus causes, white-box and black-box monitoring.
- OpenTelemetry, Sampling (opens in a new tab): head and tail sampling and their trade-offs. W3C, Trace Context (opens in a new tab): the
traceparentandtracestateheaders. - Prometheus documentation, Histograms and summaries (opens in a new tab) (why histograms aggregate and client-side quantiles do not) and Metric and label naming (opens in a new tab) (the warning about high-cardinality labels).
- Benjamin H. Sigelman and others, Dapper, a Large-Scale Distributed Systems Tracing Infrastructure (opens in a new tab), Google technical report, 2010: the origin of the span model and of sampling in production tracing.
- Brendan Gregg, The USE Method (opens in a new tab). Tom Wilkie, The RED Method (opens in a new tab).