Observability: logs, metrics, traces

In one sentence

Metrics tell you *that* something is wrong, traces *where*, logs *why*. Instrument with OpenTelemetry, alert on RED and USE, and keep high-cardinality detail on spans, not metric labels.

Analogy: Metrics are the car's dashboard gauges, a trace is the GPS log of one specific trip, and logs are the driver's notes about what happened at each stop.

One trace_id travels in the traceparent header; every service exports spans, metrics and logs over OTLP to a Collector that fans out to backends.

How it works

  • A trace follows one request: its spans share a trace_id, passed between services in the W3C traceparent header.
  • Make logs structured JSON with trace_id and tenant_id, so you query them instead of grepping.
  • RED per service: rate, errors, duration; USE per resource: utilization, saturation, errors.
  • Cardinality: every unique label combination is a series; adding user_id (1M users) turns 5,000 series into 5 billion.
  • LLM apps need a span per step (retrieval, rerank, model and tool calls) carrying tokens, cost and latency.

Check yourself

Answer to mark it learned; your answers aren't scored.

A RAG assistant's p95 latency jumps from 3 s to 9 s overnight. On the RED dashboard, rate and errors are flat; only duration rose. What's your next move?

Go deeper

Full explanation

Observability is being able to answer new questions about production from the telemetry it already emits, without shipping new code.

  • Metrics: cheap, aggregated time series (counters, gauges, histograms) for dashboards and alerts. Prometheus, Datadog.
  • Logs: discrete events. Make them structured (JSON with trace_id, tenant_id, level) so you query them instead of grepping.
  • Traces: one request's path across services. Each unit of work is a span (name, start, duration, parent, attributes); all spans share a trace_id. Context propagation carries the ids between services in the W3C traceparent header, and through queue messages.
  • Profiles: continuous CPU and memory profiling, being added to OpenTelemetry as a fourth signal.

What to measure:

  • RED per service: Rate, Errors, Duration (as p50/p95/p99).
  • USE per resource (CPU, GPU, disk, pool): Utilization, Saturation, Errors.

OpenTelemetry (OTel) is the vendor-neutral standard: one SDK plus the OTel Collector, exporting to any backend (Jaeger, Grafana Tempo, Honeycomb, Datadog).

Cardinality is the cost trap: every unique label combination is a separate time series. Put user_id or a prompt on a metric and storage explodes; keep that detail on spans and logs.

LLM apps need a span per step (retrieval, rerank, each model and tool call) carrying model, input/output tokens, cost and latency. See LLM observability & tracing.

Code Per-step spans with token and cost attributes
pythonPer-step spans with token and cost attributes
from opentelemetry import trace
from openai import OpenAI

# Assumes a TracerProvider + OTLP exporter configured at startup.
MODEL = "gpt-4.1-mini"                       # any chat model
PRICE_IN, PRICE_OUT = 0.40e-6, 1.60e-6       # $/token, check your price sheet
tracer = trace.get_tracer("support-bot")
client = OpenAI()

def answer(question: str) -> str:
    with tracer.start_as_current_span("answer"):              # root span
        with tracer.start_as_current_span("retrieve") as s:
            docs = retrieve(question, k=20)
            s.set_attribute("retrieval.hits", len(docs))
        with tracer.start_as_current_span(f"chat {MODEL}") as s:
            r = client.chat.completions.create(
                model=MODEL, messages=build_prompt(question, docs))
            u = r.usage
            # OTel GenAI semantic conventions; per-request detail lives on spans,
            # never as metric labels (cardinality)
            s.set_attribute("gen_ai.request.model", MODEL)
            s.set_attribute("gen_ai.usage.input_tokens", u.prompt_tokens)
            s.set_attribute("gen_ai.usage.output_tokens", u.completion_tokens)
            s.set_attribute("app.cost_usd",
                u.prompt_tokens * PRICE_IN + u.completion_tokens * PRICE_OUT)
        return r.choices[0].message.content
Real example

A RAG assistant's p95 latency jumps from 3 s to 9 s overnight. The RED dashboard shows rate and errors flat, duration up: something is slow, not broken. A slow trace shows the retrieve span unchanged at ~200 ms, but the chat span now carries ~28k input tokens instead of ~6k: a config change raised top-k from 5 to 25 chunks. Cost per request rose ~4× too. Without per-step spans carrying token counts, the team would have blamed the model provider.

Trade-offs +3 · −3

+ You gain

  • Traces turn "it's slow" into the exact span and service in minutes.
  • OpenTelemetry avoids lock-in: switch backends without re-instrumenting code.
  • RED and USE give every team the same small, alertable dashboard.

− You pay

  • Telemetry costs real money: ingest and retention can rival compute for chatty services.
  • One high-cardinality label can blow up a metrics backend and its bill.
  • Tracing everything is expensive at scale, so you sample and may miss rare requests.

Use it when

Any system with more than one service, and every LLM app in production: you can't debug or price a multi-step chain you can't see.

Avoid it when

Skip heavy custom instrumentation on a single-process prototype. Never log raw prompts or PII at 100% without redaction, sampling and retention limits.

Numbers to know 4
  • Series count = product of label values: 50 routes × 5 status codes × 20 pods = 5,000 series; add user_id with 1M users and it's 5 billion.
  • W3C traceparent carries a 16-byte trace-id and an 8-byte parent span-id.
  • Google SRE's four golden signals: latency, traffic, errors, saturation.
  • Rule of thumb: head-sample ~1–10% of traces at high volume, but tail-sample to keep 100% of errors and slow requests.
Common pitfalls 4
  • Unstructured log lines without trace_id: you can't join a log to the request that produced it.
  • User ids, prompts or raw URLs as metric labels: cardinality explosion and a surprise bill.
  • Alerting on averages: a mean hides the tail; use p95/p99 from histograms.
  • Context not propagated through queues and async workers, so traces stop at the first hop.
Interview questions 3

Answer out loud first, then reveal.

How would you instrument an LLM agent in production?Show answer

Every request becomes a trace with one span per step: retrieval, rerank, each model call, each tool call, using OpenTelemetry so I can switch backends. Model spans carry model id, input and output tokens, cost, latency and finish reason, following the GenAI semantic conventions. From those I derive low-cardinality metrics: RED per endpoint, cost per tenant and per feature. Prompts and outputs go to sampled, redacted logs linked by trace_id, because error analysis needs them and that's exactly where the PII risk lives.

Metrics, logs or traces: if you could keep only one?Show answer

For one service, metrics: cheap, and they tell me something is wrong. For distributed or LLM systems, traces, because a span with rich attributes can be aggregated into metrics and carries the context a log line would; that's the "wide events" view. The trade-off is cost: tracing 100% gets expensive, so I tail-sample, keeping all errors and slow requests plus a small share of the rest. In practice I want all three, correlated by trace_id.

Your metrics bill tripled overnight. What happened?Show answer

Almost certainly a cardinality explosion: someone added a high-cardinality label such as user_id, a URL path with ids in it, or a model name that varies per request, and every unique value created a new time series. I'd find it by querying series count per metric and label, drop or rewrite that label at the Collector, and move the detail to spans or logs, where per-event fields are cheap. Then I'd add a guard that caps distinct label values per metric.