Tracing and Observability for AI Systems

Michael BrenndoerferDecember 2, 202635 min read

Build span-based traces for AI systems covering latency, cost, sampling, and privacy-aware redaction. Learn to instrument production requests end to end.

Language AI HandbookAll chapters
Part 64 of 67Compound AI System Design
Chapter 488Tracing and Observability for AI Systems
Reading the full chapter · 10 sections · 35 min10 sections · 35 min

All 10 sections · 35 min read

Reading settings

Definitions

Choose how many terms have tooltips.

Article links

Make inline references clickable

Notes & comments

Tracing and Observability for AI Systems

A retrieval assistant takes 1,420 ms to answer a simple request. The tool call looks slow in the logs, but the trace shows that the two generation calls occupy most of the request interval. The trace points you to the operation to investigate and the model version to check. In this chapter we build that trace from a fictional request, then use it to account for time, estimated cost, and quality signals while controlling which fields reach storage.

An application log can record model and tool calls without recording the dependencies or configurations that produced them. Retries and parallel branches become easier to review if the system propagates a trace ID and records the observed operations and their parent, timing, and version. A missing span still leaves an evidence gap.

In earlier chapters we designed the compound system's components: the retrieval pipeline in Part XLIV: Retrieval-Augmented Generation, the tool-calling loop in Part XLVIII: Tool Use and Agents, and the evaluation infrastructure in Evaluation Fundamentals. Evaluation tells you whether the system is good on a fixed dataset. Observability tells you what it is doing in production, with the real distribution of prompts, documents, tools, and failures. The two are complementary: offline evaluation is a controlled experiment, and tracing is the instrumentation that lets you run the same experiments on live traffic.

This chapter implements a small tracing layer for a language system. We’ll record six views of a request (prompt, retrieval, tool, latency, cost, and quality), reconstruct the observed span hierarchy, and distinguish measured latency from the critical path through known dependencies. The final examples use sampling, structured redaction, and retention to limit what is collected and stored.

Trace

A collection of observed spans associated with a trace ID. A trace may span processes and services. The local examples have one root, while missing spans can leave gaps in a stored trace.

Span

A single timed operation within a trace, carrying a start time, duration, attributes, and references to its parent. A model call, a retrieval query, and a tool invocation are each spans.

From Logs to Traces: Why Flat Records Are Not Enough

Traditional application logging emits flat lines: a timestamp, a level, a message. For a request-scoped system, flat logs fail in a specific way. If your agent issues three tool calls and two model calls, the log lines are interleaved with lines from other requests, and reconstructing which lines belong to a single user request requires a correlation ID that you then have to join manually. Worse, timing relationships (which call blocked on which) are absent, so you cannot tell whether the 4-second latency came from the model, the retriever, or a serialized tool chain that never overlapped.

It is worth being precise about why the correlation ID alone is insufficient. A correlation ID lets you group lines into a request, but it does not tell you the structure within the request. Given five lines tagged with the same request ID, you still do not know which line is the parent of which, whether any of them ran concurrently, or which one the request was waiting on when it stalled. You have recovered the set of operations but lost the shape of the computation. Structure is exactly what you need to localize a bug, because a bug is almost always at a specific edge of the execution graph: the retriever returned the wrong document to the generator, the tool returned a malformed result to the planner, the reranker reordered candidates before truncation. Only a representation that preserves those edges shows you the bug.

Within the trace, a span’s parent pointer records the operation that created or directly caused it. Start and end times show which recorded intervals overlap. Sibling operations can still depend on each other, so parent pointers alone do not identify the operations that blocked progress.

The contrast is easiest to see with two small interval schedules. In the serial case, each step waits for the previous one, so the request's wall-clock time is the sum of the step durations. In the parallel case, two independent steps share a time window, so the wall-clock time is driven by the longer one plus whatever must still follow. We compute both schedules from fixed numbers so the comparison is reproducible.

PythonIn [3]
CollapseExpand
serial_steps = [
    ("embed", 0, 35),
    ("retrieve_a", 35, 435),
    ("retrieve_b", 435, 735),
    ("merge", 735, 755),
    ("generate", 755, 1555),
]
parallel_steps = [
    ("embed", 0, 35),
    ("retrieve_a", 35, 435),
    ("retrieve_b", 35, 335),
    ("merge", 435, 455),
    ("generate", 455, 1255),
]
serial_total_ms = max(end for _, _, end in serial_steps)
serial_sum_ms = sum(end - start for _, start, end in serial_steps)
parallel_total_ms = max(end for _, _, end in parallel_steps)
parallel_sum_ms = sum(end - start for _, start, end in parallel_steps)
parallel_saving_ms = serial_total_ms - parallel_total_ms
assert serial_sum_ms == parallel_sum_ms == 1555
assert parallel_total_ms == 1255 and parallel_saving_ms == 300
serial_labels = [f"serial: {name}" for name, _, _ in serial_steps]
serial_lefts = [start for _, start, _ in serial_steps]
serial_widths = [end - start for _, start, end in serial_steps]
parallel_labels = [f"parallel: {name}" for name, _, _ in parallel_steps]
parallel_lefts = [start for _, start, _ in parallel_steps]
parallel_widths = [end - start for _, start, end in parallel_steps]
ConsoleOut [4]
CollapseExpand
Serial wall-clock (ms):      1555
Serial sum of durations (ms): 1555
Parallel wall-clock (ms):    1255
Parallel sum of durations (ms): 1555
Wall-clock saved by overlap (ms): 300

Both schedules execute the same five operations. In the parallel schedule, the two retrieval calls start at 35 ms, and the merge waits for both to finish. The later retrieval ends at 435 ms. The merge and generation then finish at 1,255 ms, which is 300 ms earlier than the serial schedule.

VisualizationOut [5]
CollapseExpand
Two timelines show serial steps summing to total time while parallel retrieval bars overlap.
Serial versus parallel request schedules on a shared time axis. In the serial schedule, step durations sum to the wall-clock time, while in the parallel schedule the two retrieval calls overlap, so wall-clock time is set by the longer branch plus the join.

The example uses its own Python records. The OpenTelemetry Tracing API defines span context and links. Links can connect spans in the same trace or different traces, for example when a queued batch depends on multiple originating requests. Under W3C Trace Context, the transmitted parent-id identifies the caller's current operation. Instrumentation uses real trace and span IDs when it injects context. The example identifiers are local labels.

The anatomy of a span

Before writing code, fix the conceptual distinctions. A span is a timed operation, not a message. It has:

  • Identity: trace_id (shared by all spans in one request), span_id (unique), parent_span_id (null for the root).
  • Timing: start and end timestamps for placement in the trace. For elapsed time within one process, use a monotonic clock. Compare timestamps across hosts only with adequate clock alignment and an understanding of clock error.
  • Operation category: what type of work the local demo records. Standard OpenTelemetry span kinds represent relationships such as client and server. Common kinds are chain (control flow), llm (model call), retriever, embedding, tool, and reranker.
  • Attributes: a dictionary of string keys to values under a versioned schema. The example accepts Python structures, while an exporter must map them to its supported attribute types. Token counts, model names, document IDs, and scores live here.
  • Status: a recorded outcome. The demo uses success/error labels. OpenTelemetry has a distinct unset state, and exporter rules govern status mapping. A failed span should record the error without leaking sensitive exception text.
  • Events: optional timestamped points within a span (for example, "first token received" for a streaming generation), which we will mention but keep out of the minimal implementation.

Each field supports a different query. Use IDs to join spans, timing to compare intervals, categories to group similar work, and outcome codes to count errors. Span events can mark a point inside an operation, such as the first response token, without making it a separate timed span.

In this example, attributes describe operations and payloads hold content. Either can contain personal information. A tenant ID or document ID can reveal sensitive relationships even when the raw text is absent. Audit both categories before allowing a field into telemetry.

The Six Trace Families

Different parts of a compound system warrant different trace schemas, because the questions you ask of each differ. We can group them into six families. In practice one trace contains spans from several families: the root chain span has llm and retriever children.

It helps to think of each family as answering a distinct diagnostic question rather than as a distinct storage table. When something goes wrong, an engineer silently asks a sequence of questions, and each family is the structured record that lets one of those questions be answered quickly. Reading the families in order of a typical debugging session (what was asked, what was retrieved, what was called, how slow, how expensive, how good) makes the design motivation concrete.

Prompt traces

Record the model and template revision, decoding parameters that affect the request, and available token counts. Rendered prompts and completions can contain user text, retrieval results, or system instructions. Capture content only under an explicit access and retention policy. A template revision or protected reference often provides the first lead without copying the text into routine traces.

Trace the template version and any approved reference to the rendered prompt separately. The template identifies which instructions and placeholders were configured. The actual model input depends on the rendered variables, their message roles, and the retrieved data available at request time. A request can record enough version information to identify a template change without storing the original user text. Evaluation Harnesses and Reproducibility

Retrieval traces

For a retriever span, record the protected query or embedding reference, the index and embedding-model versions, the requested candidate count, and the returned document IDs and scores. Include scores after fusion or reranking and record the retrieval settings that produced them. The resulting list shows each returned document’s rank. A label for the top result alone cannot establish recall.

An approved set of document IDs and scores is enough to compare ranked lists against relevance labels. Recall at kk divides relevant items found in the first kk results by the total number of relevant items. Precision at kk divides by kk for a list of at least kk results. Rank comes from the order of the returned list, and a trace without relevance labels cannot establish recall.

Tool traces

A tool span can record the approved tool name and version, authorization outcome, execution status, and latency. An operation that was attempted, denied, or completed needs a distinct outcome. Keep credentials and customer records out of routine tool telemetry. A controlled evidence capture may hold additional material when an authorized investigation requires it.

Record whether each approved field came from a model proposal, a validated request parameter, or a tool response. Preserve source and trust-boundary information without exposing the argument or response body.

Latency traces

Latency is a derived view of span timings. A complete request span gives elapsed time, and span groups show which operations consumed time. Computing a critical path also requires dependency information, such as which result a join waits for. Latency Optimization covers ways to change those timings.

A p95 alert tells you users are waiting. Inspect traces from the affected route to see whether the retriever, a tool call, or a second generation is a candidate contributor. Compare against traces from unaffected requests before drawing a conclusion.

Cost traces

Derive per-span estimates from the billing units you observed and the price table in effect. The partial sum covers only operations with observed usage and a known price. Preserve the price-table version so you can distinguish changes in rates from changes in usage. Cost Management

For example, if estimated cost rises on one route, compare prompt length, output length, retry count, model version and rate changes. The trace can expose the contributing operation when those fields are available. Reconcile totals against billing records where actual charges matter.

Quality traces

A quality trace attaches an evaluation signal to a span or trace. Examples include recall at a fixed cutoff, a groundedness score from a judge, a user rating, and a task-success flag. If scoring every request costs too much, use a sampling plan and record which requests received which kind of score. LLM-as-Judge covers judge design.

The specific value of quality traces is that they close the loop between "bad" and "why." A user thumbs-down is a signal with no explanation; when it is linked to a specific generation span, whose inputs are traceable to a specific retrieval span, whose IDs you can inspect offline, the signal becomes a lead. Group the bad traces by the prompt version, index version, or route that appears in their attributes, and you have a hypothesis about the cause without ever having manually read a single request.

Building the Span Tree and Reconstructing Execution

Let's make this concrete. We will build a minimal in-memory tracer that produces spans with the fields above, then reconstruct the tree and compute derived views. Everything is deterministic: fixed timestamps and fixed inputs, so results are reproducible and the chapter's numbers never depend on wall-clock time or randomness.

The fixtures use fixed identifiers and timestamps. This lets us check the derived timings without waiting for operations to run or depending on the speed of the machine.

PythonIn [6]
CollapseExpand
from __future__ import annotations

import json
import uuid
from dataclasses import asdict, dataclass, field
from typing import Any, Optional


# Deterministic span IDs so the chapter is reproducible.
def make_id(prefix: str, n: int) -> str:
    return f"{prefix}-{n:04d}"

The span class keeps descriptive attributes separate from content fields. Export policy applies to both. The fixture uses integer milliseconds. A deployed service can use a monotonic clock to measure elapsed time within a process. The helper to_record returns an in-memory dictionary that includes payload and error fields. Arbitrary attribute values can require explicit serialization. Use an allowlisted exporter for persisted records, as shown below.

PythonIn [7]
CollapseExpand
@dataclass
class Span:
    trace_id: str
    span_id: str
    parent_span_id: Optional[str]
    name: str
    kind: str  # chain | llm | retriever | embedding | reranker | tool
    start_ms: int
    end_ms: int
    attributes: dict[str, Any] = field(default_factory=dict)
    payload: dict[str, Any] = field(
        default_factory=dict
    )  # sensitive; retention-controlled
    status: str = "ok"  # ok | error
    error_message: Optional[str] = None

    @property
    def duration_ms(self) -> int:
        return self.end_ms - self.start_ms

    def to_record(self) -> dict[str, Any]:
        return asdict(self)

A Trace groups spans sharing a trace ID. The helpers read parent pointers from a flat list and assume this fixture contains one root. A deployed store can index the spans by trace ID and the children by parent ID so the tree can be assembled after spans arrive. Use the trace ID together with the span ID when joining records from different traces.

PythonIn [8]
CollapseExpand
@dataclass
class Trace:
    trace_id: str
    spans: list[Span] = field(default_factory=list)

    def root(self) -> Span:
        roots = [s for s in self.spans if s.parent_span_id is None]
        assert len(roots) == 1, "a trace must have exactly one root"
        return roots[0]

    def children(self, span_id: str) -> list[Span]:
        return [s for s in self.spans if s.parent_span_id == span_id]

    def by_id(self) -> dict[str, Span]:
        return {s.span_id: s for s in self.spans}

A worked example: a RAG-with-tool request

Consider a single user request that runs a small RAG pipeline:

  1. A root chain span wraps the whole request.
  2. An embedding span embeds the user query.
  3. A retriever span queries the vector index and returns three candidates.
  4. A reranker span rescores the candidates.
  5. An llm span generates an answer from the top context.
  6. A mock tool span looks up a fictional balance after the first generation requests it.
  7. A second llm span incorporates the mock tool result.

Notice that steps 2 through 7 form a serial pipeline: each step waits for the previous one. This is the simplest possible control flow, which makes it the right first example, but keep in mind that the whole point of the tree representation is to handle the harder case where some of these steps could run in parallel. The diagnostic questions a reviewer asks of this trace are: Was the balance looked up for the right account? Did the first generation correctly decide that a tool was needed? Did the second generation use the tool result faithfully? Each of those questions maps to a specific span, which is the payoff of the structure.

Let's construct it with explicit, plausible timings so the critical path is interesting. The two LLM calls dominate latency; the retriever and reranker are fast; the tool call has network latency.

PythonIn [9]
CollapseExpand
def build_example_trace() -> Trace:
    tid = "trace-0001"
    spans = [
        Span(
            tid,
            make_id("s", 1),
            None,
            "rag_agent.run",
            "chain",
            0,
            1420,
            attributes={"route": "rag_with_tool", "tenant": "acme"},
        ),
        Span(
            tid,
            make_id("s", 2),
            make_id("s", 1),
            "embed_query",
            "embedding",
            10,
            45,
            attributes={"model": "embed-v3", "dim": 384},
        ),
        Span(
            tid,
            make_id("s", 3),
            make_id("s", 1),
            "vector_search",
            "retriever",
            50,
            140,
            attributes={
                "index": "kb-2025-01",
                "top_k": 3,
                "doc_ids": ["d17", "d42", "d09"],
                "scores": [0.81, 0.77, 0.74],
            },
        ),
        Span(
            tid,
            make_id("s", 4),
            make_id("s", 1),
            "rerank",
            "reranker",
            145,
            210,
            attributes={"model": "rerank-v2", "kept": ["d42", "d17"]},
        ),
        Span(
            tid,
            make_id("s", 5),
            make_id("s", 1),
            "generate_answer",
            "llm",
            215,
            900,
            attributes={
                "model": "gen-large",
                "prompt_tokens": 910,
                "completion_tokens": 120,
                "temperature": 0.0,
            },
            payload={
                "prompt": "Context: [d42...] Question: What is my balance?"
            },
        ),
        Span(
            tid,
            make_id("s", 6),
            make_id("s", 1),
            "tool.get_balance",
            "tool",
            905,
            1150,
            attributes={"tool": "get_balance", "status_code": 200},
            payload={"result": "balance=1250.00 USD"},
        ),
        Span(
            tid,
            make_id("s", 7),
            make_id("s", 1),
            "generate_final",
            "llm",
            1155,
            1420,
            attributes={
                "model": "gen-large",
                "prompt_tokens": 1040,
                "completion_tokens": 60,
                "temperature": 0.0,
            },
            payload={
                "prompt": "Tool result: balance=1250.00. Answer the user."
            },
        ),
    ]
    return Trace(tid, spans)


example_trace = build_example_trace()

Each row shows one operation with its parent, kind, and duration. The first child starts 10 ms after the root, and there are five 5 ms gaps between children. The final child ends with the root. The fixture leaves those gaps unattributed. In a real trace, add instrumentation around a recurring gap if you need to identify what ran there.

ConsoleOut [10]
CollapseExpand
span              parent    kind         start   end   dur
rag_agent.run     None      chain            0  1420  1420
embed_query       s-0001    embedding       10    45    35
vector_search     s-0001    retriever       50   140    90
rerank            s-0001    reranker       145   210    65
generate_answer   s-0001    llm            215   900   685
tool.get_balance  s-0001    tool           905  1150   245
generate_final    s-0001    llm           1155  1420   265

The output shows the seven spans of one request. The root rag_agent.run spans from 0 to 1,420 ms. The child intervals account for 1,385 ms, leaving 35 ms without a child span. The fixture does not label that time, so we keep it as unattributed.

Reconstructing the tree and rendering it

The renderer follows the recorded parent pointers to print an indented span hierarchy. The nesting shows the recorded parent relationships. It can help you locate an operation before consulting timing or dependency evidence.

PythonIn [11]
CollapseExpand
def render_tree(trace: Trace) -> list[str]:
    lines = []
    root = trace.root()

    def walk(span: Span, depth: int) -> None:
        indent = "  " * depth
        lines.append(f"{indent}{span.name} [{span.kind}] {span.duration_ms}ms")
        for child in sorted(
            trace.children(span.span_id), key=lambda s: s.start_ms
        ):
            walk(child, depth + 1)

    walk(root, 0)
    return lines
ConsoleOut [12]
CollapseExpand
rag_agent.run [chain] 1420ms
  embed_query [embedding] 35ms
  vector_search [retriever] 90ms
  rerank [reranker] 65ms
  generate_answer [llm] 685ms
  tool.get_balance [tool] 245ms
  generate_final [llm] 265ms

The tree shows the recorded parent relationships. All six operations are direct children of the root. The fixture defines their execution order separately. A deeper trace can represent a tool with child operations. This recursive renderer assumes an acyclic structure and is limited by Python’s recursion depth. A production renderer can use an explicit stack and cap the depth displayed.

Computing latency and the critical path

For this serial fixture, group the six immediate child durations by span kind. Each duration already includes any nested work, so this view counts immediate children only. With overlapping siblings, the category sums measure recorded span time and can exceed elapsed request time.

PythonIn [13]
CollapseExpand
kind_totals_ms = {}
for span in example_trace.children(example_trace.root().span_id):
    kind_totals_ms[span.kind] = (
        kind_totals_ms.get(span.kind, 0) + span.duration_ms
    )
kind_labels = sorted(kind_totals_ms)
kind_values_ms = [kind_totals_ms[kind] for kind in kind_labels]
kind_bar_labels = [f"{duration} ms" for duration in kind_values_ms]
ConsoleOut [14]
CollapseExpand
embedding        35 ms
llm             950 ms
reranker         65 ms
retriever        90 ms
tool            245 ms

The two model calls dominate, with the tool and retrieval spans contributing modest amounts. The figure makes that ordering visual at a glance.

VisualizationOut [15]
CollapseExpand
A bar chart ranks span kinds by total milliseconds, led by model calls.
Inclusive duration of the six immediate child spans summed by kind. Model calls dominate, followed by the tool call, while retrieval and embedding are comparatively cheap.

The root interval contains all six child intervals. The labeled rows preserve their offsets, which makes gaps and nesting visible.

PythonIn [16]
CollapseExpand
timeline_spans = example_trace.spans
timeline_names = [span.name for span in timeline_spans]
timeline_starts = [span.start_ms for span in timeline_spans]
timeline_durations = [span.duration_ms for span in timeline_spans]
timeline_root = timeline_names[0]
VisualizationOut [17]
CollapseExpand
A 1,420 ms request bar encloses six sequential operation bars.
Timeline of a synthetic retrieval-and-tool request. The 1,420 ms root span encloses six sequential child operations from embedding through the final generation, and the blank intervals show 35 ms of unattributed time, including 10 ms before the first child.

The root duration measures wall-clock time from the request's start to its end. The six children in this fixture are sequential by construction. They occupy 1,385 ms of the 1,420 ms root interval. The remaining 35 ms consist of a 10 ms leading interval and five 5 ms intervals between children.

PythonIn [18]
CollapseExpand
root = example_trace.root()
children = example_trace.children(root.span_id)
totals = {}
for span in children:
    totals[span.kind] = totals.get(span.kind, 0) + span.duration_ms

assert all(
    left.end_ms <= right.start_ms for left, right in zip(children, children[1:])
)
assert (
    root.start_ms <= children[0].start_ms <= children[-1].end_ms <= root.end_ms
)
recorded_ms = sum(totals.values())
print("Root latency (ms):", root.duration_ms)
print("Child durations by kind (ms):", totals)
print("Unattributed interval (ms):", root.duration_ms - recorded_ms)
ConsoleOut [18]
CollapseExpand
Root latency (ms): 1420
Child durations by kind (ms): {'embedding': 35, 'retriever': 90, 'reranker': 65, 'llm': 950, 'tool': 245}
Unattributed interval (ms): 35

The two generation calls occupy 950 ms in total. In this serial fixture they form part of the blocking sequence. The second generation waits for the tool result, so moving it earlier would change the request's behavior.

A critical path is the longest duration-weighted chain in a dependency graph. Parent spans generally include child time. Summing durations down a parent-child chain therefore counts nested time more than once, and timestamp overlap alone cannot reveal which operation a later step waited for. Use causally justified edges and include necessary queue or coordination work when you need to compute the path. For example, two independent calls that start together and take 700 ms and 250 ms require 700 ms before a join that waits for both. If the join depends only on the shorter call, its dependency chain is different even when the calls' intervals are identical.

Latency numbers depend on the clock and the tree

Document the clock assumptions and the location of first-token events. Overlapping siblings can make the sum of their durations exceed elapsed time. Uninstrumented gaps can instead make the sum smaller. Label which measurement you are presenting so readers can distinguish elapsed time from aggregated span durations or a computed critical path.

Cost and Quality as Derived Views

Cost and quality are not separate data; they are computed from, or attached to, spans. We version the price table so historical costs remain interpretable. The version stamp on a cost record is not bureaucratic overhead; without it, a price cut mid-quarter makes it impossible to tell whether your bill fell because you optimized or because your provider reduced prices, and an analysis that mixes both price regimes silently produces an average of two incompatible numbers.

PythonIn [19]
CollapseExpand
# Prices in USD per 1M tokens, versioned. Fictional models.
PRICE_TABLE = {
    "v2025-01": {
        "gen-large": {"input": 3.00, "output": 15.00},
        "embed-v3": {"input": 0.02, "output": 0.00},
        "rerank-v2": {"input": 0.05, "output": 0.00},
    }
}


def span_cost_usd(span: Span, price_version: str) -> float | None:
    if span.kind not in ("llm", "embedding", "reranker"):
        return None
    model = span.attributes.get("model")
    prices = PRICE_TABLE[price_version].get(model)
    pt = span.attributes.get("prompt_tokens")
    ct = span.attributes.get("completion_tokens")
    if prices is None or pt is None or ct is None:
        return None
    return (pt * prices["input"] + ct * prices["output"]) / 1_000_000


def trace_cost_usd(trace: Trace, price_version: str) -> float:
    costs = [span_cost_usd(span, price_version) for span in trace.spans]
    return sum(cost for cost in costs if cost is not None)
ConsoleOut [20]
CollapseExpand
Priced spans (USD): {'generate_answer': 0.00453, 'generate_final': 0.00402}
Unpriced operations: ['embed_query', 'rag_agent.run', 'rerank', 'tool.get_balance', 'vector_search']
Estimated charges for priced spans (USD): 0.00855

The example prices two generations using fictional rates. At USD 3 per million input tokens and USD 15 per million output tokens, their estimated charges are USD 0.00453 and USD 0.00402. Track whether each span is priced using its trace ID and span ID. This helper returns None for unpriced operations or missing usage. An unknown price-table version raises KeyError for a priced span kind. The estimate omits cache tiers, tool fees, and charges without usable token observations.

Quality scores attach to the span or trace that was evaluated. The target identifies what was scored. Establishing the cause of a poor score requires separate evidence. Keeping them as independent records with a source field preserves the scores from a heuristic, a judge, and a human reviewer when they disagree.

PythonIn [21]
CollapseExpand
@dataclass
class QualitySignal:
    trace_id: str
    target_span_id: str
    metric: str
    score: float
    source: str  # heuristic | judge | user


def attach_quality_example(trace: Trace) -> list[QualitySignal]:
    return [
        QualitySignal(
            trace.trace_id,
            make_id("s", 3),
            "retrieval_recall_at_3",
            1.0,
            "heuristic",
        ),
        QualitySignal(
            trace.trace_id, make_id("s", 7), "groundedness", 0.92, "judge"
        ),
        QualitySignal(
            trace.trace_id, make_id("s", 7), "helpfulness", 1.0, "user"
        ),
    ]


quality = attach_quality_example(example_trace)
ConsoleOut [22]
CollapseExpand
retrieval_recall_at_3  span=s-0003   score=1.0   source=heuristic
groundedness           span=s-0007   score=0.92  source=judge
helpfulness            span=s-0007   score=1.0   source=user

These quality numbers are invented labels. A recall of 1 for a request with a single labeled relevant document means that document was found in the three results. Low groundedness would then suggest inspecting which evidence reached generation, how it was used, and whether the evaluator scored the expected behavior.

Sampling: Tracing Without Going Broke

Tracing every request at full payload fidelity is expensive: storage for prompts and completions is large, and computing judge scores on every trace is costly. Sampling is the standard answer, but sampling strategy affects what conclusions you can draw, so state it explicitly. The main strategies:

  • Head-based sampling makes an early decision using information already available. The example below uses a fixed probability and can miss failures that happen after the decision.
  • Tail-based sampling decides after observing more of the trace, for example by keeping traces with recorded errors or high latencies. The decision uses spans received within the configured wait and capacity limits.
  • Stratified sampling: sample at different rates per route or tenant so small but important populations are represented.

A tail sampler downstream of a head drop cannot recover the traces that never reach it. To combine a traffic sample with additional diagnostic traces, mark the probability sample separately and give the tail policy access to the candidate stream before that drop. The tail policy can keep observed errors and slow requests, subject to incomplete exports, late spans, or capacity limits. Use the probability sample for traffic-wide estimates, with appropriate inclusion and labeling assumptions.

A quality average on retained traces describes the retained population. To estimate a traffic-wide average, use a probability sample with known positive inclusion probabilities for all eligible requests and account for missing evaluation labels. A tail policy that discards every ordinary successful request leaves no retained evidence about their quality.

PythonIn [23]
CollapseExpand
import hashlib


def head_sample(trace_id: str, rate: float) -> bool:
    """Deterministic head sampling by hashing the trace id."""
    if not 0.0 <= rate <= 1.0:
        raise ValueError("rate must be in [0, 1]")
    digest = hashlib.sha256(trace_id.encode("utf-8")).hexdigest()
    bucket = int(digest[:8], 16) / (1 << 32)  # uniform buckets in [0, 1)
    return bucket < rate


def tail_keep(trace: Trace, max_latency_ms: int = 1000) -> bool:
    """Keep traces that errored or exceeded a latency budget."""
    errored = any(s.status == "error" for s in trace.spans)
    slow = trace.root().duration_ms > max_latency_ms
    return errored or slow
ConsoleOut [24]
CollapseExpand
head_sample(trace-0001, 0.10): False
head_sample(trace-0002, 0.10): True
tail_keep(example_trace): True

The tail helper keeps the observed 1,420 ms trace because it exceeds the 1,000 ms budget. It can make this decision only if the trace reaches it. Deterministic head sampling by hashing the trace ID makes sampling reproducible and independent of arrival order, which matters when you re-run analysis. Identical inputs and sampler settings reproduce the decision. In a multi-service system, propagate the decision under the tracing policy, and expect partial traces if spans are lost or boundaries apply different settings.

In this deterministic fixture, raising the threshold preserves every ID already selected at a lower threshold and can add more. The realized fraction need not match the configured probability exactly.

PythonIn [25]
CollapseExpand
sampling_ids = [f"simulation-{n:04d}" for n in range(600)]
sampling_rates = [n / 20 for n in range(21)]
actual_sampling_rates = [
    sum(head_sample(trace_id, rate) for trace_id in sampling_ids)
    / len(sampling_ids)
    for rate in sampling_rates
]
VisualizationOut [26]
CollapseExpand
The observed sampling curve stays near the diagonal reference line.
Observed head-sampling fraction versus configured rate for 600 fictional request IDs. The diagonal shows equality between realized and configured rates. This fixed collection of IDs illustrates the sampler and does not measure representativeness in deployed traffic.
Sampling bias is an evaluation assumption

If you compute a metric only over sampled traces, report the sampling scheme and rate alongside the metric. A quality number computed over tail-sampled (error-biased) traces is not an estimate of overall quality; it is an estimate of quality conditional on the tail condition.

Privacy-Aware Retention and Structured Redaction

Traces are a privacy hazard by construction. A single prompt payload can contain the user's question, retrieved documents (which may include personal data), and system instructions. Tool payloads can contain credentials and customer records. Yet the same payloads are what make traces useful for debugging. The resolution is not to choose between utility and privacy but to classify fields and apply per-field policy: redact with structure rather than dumping raw text.

The approach has three parts. First, schema-first tracing: declare which fields are safe attributes and which are sensitive payloads, so redaction is not an afterthought applied to opaque strings but a policy over typed fields. Second, structured redaction: replace sensitive values with typed placeholders keyed by category (for example <EMAIL:hmac-3f2a>), preserving a type label and, when needed, a scoped equality tag so the trace remains useful for debugging (you can see that an email was present and that it was the same email across two spans, without seeing it). Third, retention tiers: raw payloads expire quickly (hours to days) while aggregates, IDs, and redacted traces persist longer. This is the trace-level analog of the PII removal strategies from PII Removal.

Schema-first tracing is the part most often skipped and the part that matters most. If payloads are opaque strings, redaction becomes a best-effort scan over free text, and any pattern the scanner misses leaks in full. If instead the schema says "this field is a document body, this field is a tool argument named email, this field is a model name," redaction becomes a policy that can be exhaustive and auditable per field. The schema also makes access control enforceable: you can grant a support engineer access to attributes and redacted payloads without granting access to raw payloads at all.

Detecting and redacting sensitive fields

The next cell illustrates string replacement on wholly fictional text. It recognizes particular email and phone formats and an invented secret marker. A match is a pattern hit. The demonstration does not establish that other sensitive strings will be caught.

PythonIn [27]
CollapseExpand
import hmac
import re

REDACTION_KEY = (
    b"trace-redaction-key-demo"  # in production: from a secrets manager
)

PATTERNS = {
    "EMAIL": re.compile(r"[\w.+-]+@[\w-]+\.[\w.-]+"),
    "PHONE": re.compile(r"\b\d{3}[-.]?\d{3}[-.]?\d{4}\b"),
    "APIKEY": re.compile(r"\bfixture-key-[A-Za-z0-9]{8,}\b"),
}


def _hmac_tag(value: str) -> str:
    return hmac.new(
        REDACTION_KEY, value.encode("utf-8"), hashlib.sha256
    ).hexdigest()[:24]


def redact_text(text: str) -> tuple[str, dict[str, int]]:
    counts: dict[str, int] = {}
    for label, pat in PATTERNS.items():

        def repl(m: re.Match, _label=label) -> str:
            counts[_label] = counts.get(_label, 0) + 1
            if _label == "APIKEY":
                return "<SECRET>"
            return f"<{_label}:{_hmac_tag(m.group(0))}>"

        text = pat.sub(repl, text)
    return text, counts
ConsoleOut [28]
CollapseExpand
Original : Contact jane.doe@example.com or 555-123-4567; key fixture-key-9f8e7d6c.
Redacted : Contact <EMAIL:ba8a6cb4f04f91aec4bde5ab> or <PHONE:897923b2c3da46c19da560cf>; key <SECRET>.
Counts   : {'EMAIL': 1, 'PHONE': 1, 'APIKEY': 1}

The same exact email string produces the same keyed tag under one key. Different strings can collide because the tag is truncated, and equal tags let a reader link records. The fictional secret marker uses a constant placeholder because it needs no linking tag.

Applying structured redaction to the trace payloads

A routine export can use a whitelist of typed fields and discard everything else before handing the record to a storage or transport queue. The following example opts into one approved field containing a structured balance class. It also illustrates pattern substitution on a fictional preview, which we keep outside the routine export.

PythonIn [29]
CollapseExpand
def export_tool_span(span: Span) -> dict[str, Any]:
    """Export only approved status and balance classes from this fixture."""
    record = {"schema_version": 1, "operation": "get_balance"}
    status = span.attributes.get("status_code")
    if type(status) is int and status in {200, 403, 503}:
        record["status_code"] = status
    balance_class = span.payload.get("balance_class")
    if type(balance_class) is str and balance_class in {
        "positive",
        "zero",
        "negative",
    }:
        record["balance_class"] = balance_class
    return record
ConsoleOut [30]
CollapseExpand
Approved tool fields: {'schema_version': 1, 'operation': 'get_balance', 'status_code': 200, 'balance_class': 'positive'}

The nested account entry and the original payload are absent from the export. The allowlist applies to values as well as keys. A new field or value needs an explicit schema decision.

Retention tiers

Redaction reduces but does not eliminate risk: a redacted trace still contains structural information, and placeholders leak whether a value was present. Combine redaction with time-based retention tiers. The following configuration describes what to keep and for how long. Selected attributes can be retained for analysis under policy; redacted payloads are kept for a short debugging window; raw payloads are never persisted at all.

Attributes can link records to people or tenants. Apply retention and access controls to approved fields, including identifiers, and review what those fields expose when joined with other records. Redacted payloads retain structure and can still support linkage. The example discards raw payloads at ingest and gives redacted payloads a 72-hour limit. Set an investigative window using how long it takes to detect and respond to incidents, and check which evidence will remain accessible at that point.

PythonIn [31]
CollapseExpand
RETENTION_POLICY = {
    "raw_payload": {
        "ttl_hours": 0,
        "note": "never persisted; redacted at ingest",
    },
    "redacted_payload": {"ttl_hours": 72, "note": "debugging window"},
    "attributes": {"ttl_hours": 24 * 90, "note": "aggregate analysis"},
    "aggregates": {"ttl_hours": 24 * 365, "note": "dashboards and trends"},
}


def should_keep(field_class: str, age_hours: float) -> bool:
    ttl = RETENTION_POLICY[field_class]["ttl_hours"]
    return 0 <= age_hours < ttl
ConsoleOut [32]
CollapseExpand
raw_payload        keep@1h=False keep@30d=False
redacted_payload   keep@1h=True  keep@30d=False
attributes         keep@1h=True  keep@30d=True
aggregates         keep@1h=True  keep@30d=True

The fixture retains redacted payloads after one hour and expires them at 72 hours. After that, the selected attributes and aggregates each remain until their own expiry, at 90 and 365 days respectively. If you rely on stored IDs for a controlled replay, check that the historical input and component versions still exist and that investigators are authorized to retrieve them.

Redaction is not anonymization

A keyed HMAC placeholder can retain equality within the tag’s scope. A service with the key can test a guessed value, and repeated tags can reveal frequencies even when the original value stays hidden. Review that linkage when deciding whether to retain tags. Differential Privacy discusses an approach to protecting released aggregate statistics.

Investigating Observed Requests

The synthetic request now has a useful record of which stages ran, how long they took, and what their versions were. A trace can identify a plausible source of delay or a candidate change to investigate. Establishing why a model made a particular error still takes controlled comparison or other evidence.

For an incident, a trace can support an investigation, and the shared identifiers can help find independent audit records. Export policy should minimize the data collected and apply the same protections to exporters, retries, queues, and backups. OpenTelemetry guidance on sensitive telemetry

Use clock-quality metadata when timestamps come from different hosts. A streaming operation can add a first-token event so you can measure time to first token separately from time to completion. Queue or batch processing can link related work even when it belongs to another trace. If a required span is missing, record the gap rather than filling it with an assumed time or cause.

During an investigation, check whether the retained data identifies the affected stage, measures its timing and estimated cost, and reaches responders while they still have access. Record which questions the available data cannot answer. Those gaps help you decide what to instrument or test next.

Summary

  • A trace groups the spans observed for a logical operation. Span relationships describe the recorded hierarchy or links. Use them to find the relevant operation, then check for missing spans and clocks that cannot be compared.
  • For a complete request root, its duration measures request latency. A critical path follows the longest weighted dependency chain when the necessary edges are known.
  • The six trace families are prompt, retrieval, tool, latency, cost, and quality. Latency and cost are derived views computed from span timings and token counts; quality scores record the span or trace that was evaluated.
  • Cost must be computed from a versioned price table, and the estimate needs a record of charges and operations it omits.
  • Sampling (head, tail, stratified) makes tracing affordable, but every sampled metric must carry its sampling frame or it will be misread.
  • Privacy-aware retention combines schema-first tracing, structured redaction with keyed placeholders that preserve correlation, and retention limits that reflect the stored fields and the needs of the investigation.
  • Tracing is observational, not causal; it complements, but does not replace, offline evaluation and online experiments. Access control, redaction at ingest, and clock discipline are prerequisites, not hardening.

As you move forward, treat tracing as the connective tissue of the compound system: it is how the model, retrieval, tool, and control-flow choices from this part become visible, measurable, and debuggable in production rather than only on a benchmark.

Quiz

Ready to test your understanding? Take this quick quiz to reinforce what you've learned about tracing and observability for AI systems.

Tracing and Observability for AI Systems

Question 1 of 80 of 8 completed
According to the chapter, what does a correlation ID alone fail to recover when analyzing flat application logs?
Join the discussionAsk a question or share what you learned.

Comments

Add to the conversation

A question, a correction, or an example from your own work.

No comments yet. Be the first to share your thoughts!

A different angle
All writing
Language AI Handbook · Vol. 20

Reliability and Cost Engineering

Design reliable, cost-aware AI services with SLOs, retries, idempotency, Little's law, caching, and fault injection under real deadlines.

29 min read
Language AI Handbook · Vol. 20

Evaluation-Driven Development

Build an offline evaluation harness for language systems: versioned task suites, traces, slice scores, and regression gates that block hidden drops.

27 min read
Language AI Handbook · Vol. 20

Versioning Models, Prompts, Data, and Tools

Version AI systems with typed manifests, compatibility checks, canary rollouts, and lineage records that connect requests to their recorded configurations.

28 min read

About the author

Reference

Citation details

Cite or share this article.

BIBTEXAcademic
@misc{brenndoerfer2026tracingobservability, author = {Michael Brenndoerfer}, title = {Tracing and Observability for AI Systems}, year = {2026}, url = {https://mbrenndoerfer.com/writing/tracing-and-observability-for-ai-systems}, organization = {mbrenndoerfer.com}, note = {Accessed: 2026-12-03} }
APAAcademic
Michael Brenndoerfer (2026). Tracing and Observability for AI Systems. Retrieved from https://mbrenndoerfer.com/writing/tracing-and-observability-for-ai-systems
MLAAcademic
Michael Brenndoerfer. "Tracing and Observability for AI Systems." 2026. Web. December 3, 2026. <https://mbrenndoerfer.com/writing/tracing-and-observability-for-ai-systems>.
CHICAGOAcademic
Michael Brenndoerfer. "Tracing and Observability for AI Systems." Accessed December 3, 2026. https://mbrenndoerfer.com/writing/tracing-and-observability-for-ai-systems.
HARVARDAcademic
Michael Brenndoerfer (2026) 'Tracing and Observability for AI Systems'. Available at: https://mbrenndoerfer.com/writing/tracing-and-observability-for-ai-systems (Accessed: December 3, 2026).
SimpleBasic
Michael Brenndoerfer (2026). Tracing and Observability for AI Systems. https://mbrenndoerfer.com/writing/tracing-and-observability-for-ai-systems
Newsletter

Stay up to date

Get new articles, book updates, and notes on AI and technology.

Unsubscribe at any time. Privacy policy