Interview's MateAI Engineering
Interview's Mate

AI Engineering

LLMs, RAG, agents & evals

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
AI Engineering topics
Lesson 75/ 160
04. Evals

Tracing

Capture spans for prompts, retrieval, tools, and tokens to debug production AI.

BeginnerSpans · Spans Tree3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidHands-onQuiz (3)Practice

In plain words

Tracing saves a step-by-step diary of everything the AI did for one question: what it looked up, what it asked the model, how long each part took and what it cost.

Think of it like…

The flight data recorder of a request: every instrument reading in order, so after an incident you can replay what happened rather than inferring it from the crash site.

Where you’ve seen it

One support request takes 4.2 seconds. Its trace shows a root span for the request with child spans: retrieval 0.35 s (8 chunks), rerank 0.15 s, an LLM generation call 3.40 s (3,100 input tokens, 420 output tokens, prompt version v14, model recorded), post-processing 0.05 s and 0.25 s of orchestration overhead. Cost: 3,100 × $2.50/M + 420 × $10/M = $0.00775 + $0.0042 ≈ $0.012. When the user flags a wrong answer, the engineer opens the trace, sees the retrieved chunk was from the outdated 2023 policy and adds a date filter; the same trace is added to the golden set as a regression case.

Words you’ll hear

Trace
The complete record of one request, identified by a trace id.
Span
One timed operation inside a trace (an LLM call, retrieval, tool call) with attributes.
Attributes / metadata
Key-value details on spans: model, prompt version, tokens, cost, user segment.
Sampling and redaction
Choosing which traces to keep and removing sensitive data from them.

Visual diagram

Loading interactive diagram

Theory & deep dive

What to capture

Instrument every meaningful step as a span with a start and end time, a parent span, a type (LLM, retrieval, tool, guardrail) and attributes. For LLM spans record the model and parameters, the full prompt messages (or a reference to the versioned template plus variables), the completion, token counts for input, output and cached tokens, latency including time-to-first-token for streaming, cost and finish reason. For retrieval spans record the query (and rewritten query), filters, returned document ids with scores and the chunk text. For tool spans record the tool name, arguments, result, errors and retries.

Add metadata that makes traces searchable and comparable: prompt version, model, feature flag or experiment variant, user or session id (hashed), environment, customer tier and release version. Attach scores to traces (user thumbs, LLM-judge results, rule checks), so you can filter "all traces with negative feedback this week". Use consistent naming so dashboards group correctly, and propagate the trace id through background jobs and downstream services to keep one coherent trace across them.

A span record

{"trace_id": "b19f…", "span": "llm.generate", "parent": "handle_question", "model": "provider-model-x", "prompt_version": "v14", "input_tokens": 3100, "output_tokens": 420, "latency_ms": 3400, "cost_usd": 0.0119, "finish": "stop"}

Key takeaway: Span every step, capture inputs, outputs, tokens, cost and versions, and attach scores.

Operating tracing responsibly

Traces contain user data, so design for privacy: redact or hash PII and secrets before export, restrict access by role, set retention limits (for example 30 to 90 days for full payloads), and honour deletion requests. Control volume and cost with sampling (keep 100% of errors, negative-feedback and slow traces, and 5% to 10% of the rest), compression and asynchronous batched export so tracing never adds latency to the request path or fails the request when the backend is down.

Make traces useful day to day: a trace viewer to read a request end to end, filters by version, tag and score, dashboards for latency (p50 and p95), cost and error rates per span type, and one-click add to dataset to turn a bad trace into a regression case. Standardise on open formats such as OpenTelemetry's GenAI semantic conventions or a platform SDK (Langfuse, LangSmith, Arize Phoenix) to avoid lock-in. Tracing complements, but doesn't replace, evals and aggregate metrics: it explains individual cases, while evals and monitors tell you how common they are.

Sampling policy

Keep 100% of traces with errors, thumbs-down, latency above p95 or guardrail triggers, plus 5% of everything else. At 50,000 requests a day that's roughly 2,500 normal traces plus the interesting ones, instead of storing all 50,000 payloads.

Key takeaway: Redact, sample smartly, export asynchronously, and make traces one click from datasets and dashboards.

How it works, step by step

Step 1 of 4
Engineering

1. Instrument each step

Wrap retrieval, rerank, LLM and tool calls in spans under a root request span.

root + 3 child spans
Key numbers at this step
Overhead
async export

When to use it & trade-offs

What it is

Tracing records a structured, hierarchical log of everything that happened while serving one request: a trace containing spans for each step (retrieval, reranking, each LLM call, each tool call, guardrails), with inputs, outputs, timing, token counts, cost, model and prompt versions, errors and metadata. For LLM applications the trace is the unit you debug, evaluate and monitor, because the final answer alone doesn't tell you *why* it was wrong, slow or expensive.

Why it matters: LLM systems are multi-step and non-deterministic. When a user reports a bad answer, you need to see the exact prompt, retrieved chunks and tool results that produced it. Traces enable error analysis, trajectory evals, cost and latency attribution, regression debugging and dataset building from real failures. Without them, teams are guessing; with them, a vague complaint becomes a specific span to fix.

When to reach for it

  • Debugging bad answers and slow requests
  • Attributing cost and latency to steps
  • Building eval datasets from real traffic

When to avoid or be careful

  • Logging raw PII and secrets
  • Synchronous tracing that adds latency or fails requests
  • Keeping only the final answer

Observability signals for LLM apps

Traces
Best for: Debugging individual requests and multi-step flows

Strengths: Full context and timing; links steps.

Watch out: Heavy payloads; privacy and cost concerns.

Metrics
Best for: Aggregate health: latency, cost, errors, quality scores

Strengths: Cheap; alertable.

Watch out: Doesn't explain individual failures.

Logs
Best for: Discrete events and errors

Strengths: Simple and familiar.

Watch out: Hard to reconstruct a multi-step request.

Interview signals & numbers to know

When this topic comes up

  • “A user got a wrong answer and we can't tell why”
  • “Where does the time go?”
  • “Which step costs the most?”
  • Spans and trace ids
  • Prompt versions in logs

Benchmarks & rules of thumb

4.2 s -
end-to-end latency of the example request
~$0.012 -
cost of 3,100 input and 420 output tokens
5% -
sample of ordinary traces, with all problem traces kept

Common mistakes & follow-ups

Common interview mistakes

  • Tracing the LLM call but not retrieval, so stale-context failures stay invisible.
  • Forgetting to record the prompt version and being unable to reproduce a regression.
  • Storing every full payload forever.

Likely interviewer follow-ups

  • What would you put in a trace for a RAG application?
  • How do you handle privacy and cost of tracing?
  • How do traces help evaluation?
Interview tip: Name the three things you always attach: versions, tokens and cost, and user feedback scores. It shows traces are an engineering tool, not just logs.
Loading hands-on exercise

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Tracing with generative AI interview Q&A and hands-on practice.

Open Generative AI Q&A →Tech Learn Q&A
Previous topic
Synthetic Test Data
Next topic
Langfuse