LLM Observability
Traces, cost forensics, drift detection and incident runbooks.
Chapter 23 tested the system before it shipped. This chapter watches it afterward. Ordinary monitoring answers whether a service is up, fast and free of errors, and a language model feature can pass all three while giving wrong answers to a third of its users. Observability for these systems means recording what the model saw and what it produced, at every step, and building the signals that ordinary monitoring does not provide.
The experiments are simulations: a hundred thousand tasks read as a bill, the arithmetic of replaying a failure, and ninety days of a sampled quality metric with a real drop hidden in its noise.
24.1A different kind of system
Nothing throws, and the context is the state.
| An ordinary service | A language model feature | |
|---|---|---|
| Same input | Same output | Possibly a different output, even at temperature 0 (section 24.7) |
| A failure | An exception, a 500, a stack trace | A 200 response containing a fluent wrong answer (section 2.11) |
| What happened | The log line and the request | Everything that was in the context window at that step |
| Reproducing it | Replay the request | Replay the exact prompt many times and look at the distribution |
Three consequences follow. The unit worth recording is the prompt and its response, not the HTTP request: “the call took 800 ms” explains nothing, while “these 14,000 tokens produced this output” is evidence. Quality failures raise no errors, so the signals that reveal them have to be built: proxies, sampled judges, user feedback. And debugging is archaeology across steps. A bad answer at step 12 often began with a false tool result at step 4 (section 19.2), so you need every step, not the last one.
Common take“We monitor latency and error rate, so the feature is observed.”
Sharper take“Those miss every quality failure, because a wrong answer is a successful request. I record what the model saw and produced at every step. In these systems the context is the state, and if I didn’t record it, an incident can’t be explained at all.”
24.2Traces and spans
One trace per task, one span per call, each with its full input and output.
A trace records one task from start to finish. Inside it, every model call, tool call and retrieval is a span, nested to show what caused what.
trace support_query id=t_8812 tenant=44 user=u_19 session=s_20 4.7 s $0.031
├─ router small model 120 ms in 412 out 8
│ "where is my order" -> {"route": "agent", "confidence": 0.91}
├─ retrieval hybrid + rerank 340 ms
│ chunks [c_991, c_44, c_102] scores [0.81, 0.77, 0.71] filters {tenant: 44}
├─ llm step 1 mid-tier model 1.9 s in 6,204 (5,800 cached) out 96
│ prompt_version=v14 tool_call get_order("O-991")
├─ tool get_order 210 ms status ok
│ {"order_id": "O-991"} -> {"status": "shipped", "eta": "2026-08-04"}
└─ llm step 2 mid-tier model 2.1 s in 6,890 out 180 stop=end_turn
"Your order shipped and should arrive on 4 August."The tree turns earlier chapters’ diagnostic moves into lookups. Was the right passage retrieved (section 15.9)? Read the retrieval span. Which step first carried a false value (section 19.2)? Walk the spans in order. The fields that earn their storage:
| Field | The question it answers |
|---|---|
| Full input and output text of every span | What did the model actually see and say? |
| Model identifier and prompt version | Did a prompt or model change cause this (section 13.8)? |
| Tokens in, out and cached | What did it cost, and is caching working (section 11.6)? |
| Time to first token and total time | Was the wait in reading the input or in writing the output (section 2.7)? |
| Stop reason and retry count | Was the output cut off? Is the model struggling (section 19.3)? |
| Tool arguments and results | Where did a false value enter? |
| Retrieved chunk IDs, scores and filters | Was the answer retrievable at all? |
| Trace, session, user and tenant IDs | Who was affected, and how widely? |
The emerging standard for these names is OpenTelemetry’s semantic conventions for generative AI, attributes such as gen_ai.request.model and gen_ai.usage.input_tokens on ordinary OpenTelemetry spans, so model calls join the traces your services already emit. Use them, but expect changes. As of late 2026 every one of the conventions is still marked Development, and in June 2026 they moved into a repository of their own so that they could change faster.
Common take“We log every request and response.”
Sharper take“Per task, as a tree, with the prompt version, the tokens and the retrieved chunks on every span. A customer’s ‘wrong answer on Tuesday’ then takes three minutes to diagnose: find the session, read what was retrieved, see that the right passage never arrived.”
24.3Cost and latency forensics
Read the same traces as a bill and as a critical path.
Spans carry tokens and timings, so the traces are already the measurement layer for Chapter 28. What they show most often is that averages mislead. I simulated 100,000 tasks on three routes: 70% answered directly, 25% with retrieval, and 5% by an agent loop whose context grows with every tool result (section 20.3), with a small share of loops wandering until they hit a 25-step cap. Prices were set at an illustrative $3 per million input tokens and $15 per million output tokens.
- simulated tasks
- if every task cost the same
The mean task cost 2.5 cents and the median 0.8. The most expensive 1% of tasks took 36% of all spending, and the agent route, 5% of traffic, took 59%. The 307 loops that ran to the cap, a third of one percent of tasks, cost $1.85 each and accounted for 23% of the bill. None of this is visible in an average. Watch distributions, and read the most expensive traces individually every week.
| Question | Read from traces as | What it catches |
|---|---|---|
| Where does the money go? | Cost summed by route, tenant, feature and prompt version | The small share of traffic that spends most of the budget |
| Why did slow requests get slower? | The span that dominates the critical path of the slowest traces | Input that grew, which slows reading, or output that grew, which slows writing |
| Is caching working? | Cached tokens as a share of input, by prompt version | A deploy that put a changing value at the start of the prompt |
| Are agents wandering? | Distribution of steps per task; histogram of tool calls | Loops and repeated searches, as a rate instead of an anecdote |
Common take“Our average cost is 2.5 cents per task, which is fine.”
Sharper take“The median is under a cent. A third of a percent of tasks are loops hitting the step cap at nearly two dollars each, and they are almost a quarter of the bill. I fix those first.”
24.4Feedback
Every signal is biased, and each one belongs on its trace.
| Signal | Strength | Bias |
|---|---|---|
| Thumbs up or down | Explicit, already labeled | Given by a few percent of users, more often when annoyed. Good for finding failures, poor for measuring a rate |
| Regenerate or retry | Frequent, behavioral | The user rejected the answer with their hands. Among the strongest cheap signals |
| Rephrased follow-up (“no, I meant…”) | Frequent; needs no button | Must be detected in the session, often by a small model |
| Copy, accept, apply | Frequent, positive | Exists only where the interface has such an action |
| Escalation, task completion | Closest to business value | Slow, and moved by many things besides answer quality |
| Abandonment | Frequent | Ambiguous: satisfied and done, or gave up |
Store feedback as an event attached to its trace, not in a separate analytics tool. A thumbs-down on its own is an opinion. A thumbs-down joined to the context, the retrieved chunks and the prompt version is a labeled test case waiting to be added (section 23.4).
Read explicit numbers with suspicion. “Our approval rate is 94%” usually means 94% of the 2% who clicked. Check the retry and rephrase rates before believing it.
Common take“Thumbs-up rate is 94%, so users are happy.”
Sharper take“Of the few who clicked. Retries and rephrased questions cover everyone, so I watch those, and every thumbs-down arrives with its trace so it can become a test case.”
24.5Online evaluation
Code checks on everything, judges on a sample, trends per slice.
The test set gates deploys (Chapter 23). Live traffic needs continuous measurement as well, with the same graders arranged by cost.
Stratify the sample so that small slices are not drowned by large ones. A slice that is 2% of traffic gets almost nothing from a uniform 5% sample, and the margin of a daily score is set by the number of judged traces in that slice, not by total traffic. Decide how small a change you need to see, and size each slice’s sample to match: at 300 judged traces a day, a 92% pass rate moves by about 1.6 points from one day to the next through sampling alone.
Judges used online are the same instruments as offline, with the same discipline: pinned versions, measured true positive and true negative rates, recalibration when anything changes.
Common take“We judge 1% of traffic at random.”
Sharper take“Then the small slices get a handful of judgments a day. I run code checks on everything, and sample by slice so that each one I protect gets enough judged traces to show the change I care about.”
24.6Four kinds of drift
Quality moved: work out which of four things changed before fixing anything.
| Drift | What changed | Its signature |
|---|---|---|
| Model | The provider updated the model behind a name (section 1.6) | A step change on a date when nothing was deployed; format failures and retries usually move first |
| Data | Your documents changed: new sources, a new parser, a restructure | Retrieval scores and recall move, in step with ingest jobs (section 15.8) |
| Query | Your users changed: a new feature, segment or language | The mix of topics, lengths and languages shifts; the test set quietly stops matching traffic |
| Instrument | Your judge’s model or prompt changed | Judge scores move while code checks and behavioral proxies stay flat |
When a quality metric moves, check in this order: your own deploy log (prompt versions and code), the ingest log, the distribution of queries, and the judge’s version. Three of the four causes are not the model getting worse, and each has a different owner. Pair every quality chart with its guardrails, cost, latency and retry rate, so that a trade is visible as a trade.
Common take“Quality dropped, so the model must have got worse. Let’s switch providers.”
Sharper take“First our deploys, then the ingest log, then the query mix, then the judge’s version. Only if all four are clean do I suspect the provider, and the date of the step tells me whether they shipped something.”
24.7Capture and replay
Record the exact request, replay it many times, and count.
“We couldn’t reproduce it” is nearly always a gap in what was captured. The procedure that makes intermittent failures tractable has four steps.
- Capture the exact request: the full message array after templating, the model and its version, every sampling setting, the tool definitions and the prompt version.
- Replay it many times, because you are sampling from a distribution, and count the failures.
- Perturb to isolate the cause: the same request without the retrieved chunks, without the history, with the previous prompt version, at a lower temperature. Each removal that stops the failure points at a component.
- Promote the case into the test set with its slice tag, so the failure has a permanent tripwire (section 23.4).
Temperature 0 does not make outputs repeatable. It selects the most likely token at each step, and the probabilities themselves can vary between runs. A 2025 study from Thinking Machines Lab traced most of this variation to batching: a server groups your request with others, and the arithmetic, and so the result, depends on the size of the group. Sent 1,000 times at temperature 0, one prompt to one open model produced 80 different completions. So the aim is not to remove variation but to measure it.
- fails 50% of the time
- 15%
- 5%
The arithmetic is unforgiving. A failure that happens 5% of the time does not appear at all in five replays 77% of the time. Twenty replays catch it about two times in three. And the count tells you what kind of problem you have. One failure in twenty puts the true rate somewhere between 1% and 24%: a rare tail, handled by validation and a retry (section 19.3). Eighteen in twenty, between 70% and 97%: a systematic fault in the prompt, the retrieval or the model choice, and a retry will not help.
Common take“It’s flaky. We tried it five times and couldn’t reproduce it.”
Sharper take“Five clean replays hide a 5% failure most of the time. I replay the captured request twenty times. ‘Fails three times in twenty’ is something I can act on; ‘flaky’ isn’t.”
24.8Alerts, objectives and incidents
Alert on sustained change, and write the runbook before you need it.
A sampled quality metric is noisy, and nondeterminism guarantees blips. I simulated ninety days of a judged pass rate, 300 traces a day, at 92%, with a real four-point drop starting on day 61, and compared two alert rules over 5,000 such periods.
- one day
- seven-day average
- thresholds and the start of the drop
| Rule | False alarm in 54 normal days | Days to detect the drop |
|---|---|---|
| Any single day below 89% | 76% of periods | 1, but it is rarely believed |
| Seven-day average below 90.2%, three standard deviations below normal | 5% of periods | 4 (median); 5 at most in nine periods out of ten |
The single-day rule fires in three periods out of four with nothing wrong, and an alert that is usually false is soon ignored. The rolling rule is wrong once in twenty periods and finds the real drop in about four days. For harmful failures, such as a promised refund or leaked data, four days is too slow; those get code checks on every trace and alert on the first occurrence.
Write quality targets the way reliability engineers write service level objectives: a measurable rate over a window, per slice. “The groundedness pass rate on refund questions stays at or above 90% over any seven days, measured on sampled traces by a pinned, calibrated judge.” The gap between the target and perfection is an error budget, and spending it fast is what pages someone.
Then plan the response before the first incident.
| Symptom | First check | Fast mitigation |
|---|---|---|
| Quality drop after a deploy | Prompt and code versions in the failing traces | Roll back the prompt version behind its flag |
| Step change with no deploy | Model identifier and provider status | Switch to the pinned fallback model (section 19.5) |
| Harmful outputs, such as unauthorized promises or data exposure | Which tool or route produced them | Disable that tool or route with a kill switch; add an output check |
| Cost spike | Steps per task and the most expensive traces | Lower the step and token budgets; route more traffic away from the agent |
| Latency spike | Time to first token against output length; provider latency | Shorter outputs, a smaller model for the affected route, fall back |
Every incident ends the same way: the failing traces become cases in the test set, so the gate catches the next one before users do.
Common take“We alert whenever the daily quality score dips.”
Sharper take“That fires most weeks for nothing. I alert on a rolling window per slice, set from the measured noise, and on the first occurrence of anything harmful. And the rollback switch exists before the incident does.”
24.9Sensitive traces and human review
The most useful log is also the most sensitive one.
Traces hold whatever users typed and whatever was retrieved for them: names, addresses, health details, contracts. Design for that from the first day.
- Redact before storing. Detect and mask personal data such as emails, phone numbers and card numbers on the way in. Replace identifiers with keyed hashes, so traces can still be grouped by user without naming anyone.
- Separate retention. Full text for weeks, numbers and metadata for longer.
- Control and log access. Reading traces is reading customer data; restrict it by role and record who looked.
- Make deletion reach traces. A deletion request covers traces and test cases built from them, not only the database (Chapter 27).
A privacy review that removes all free text from traces leaves them useless for diagnosis. Redaction keeps them useful and safe.
People still need to read traces, for error analysis, for labeling, and for the failures no automatic check knows to look for. Spreadsheets make that slow. Teams that review well build a small interface of their own: the conversation shown as the user saw it, with the retrieved passages and tool results beside it, one key for pass or fail, a list of the known failure modes to tag, and a box for notes. Feed it a queue that mixes random samples with traces flagged by proxies and by judge failures, so reviewers see both the typical and the troubling.
Common take“Legal made us drop prompt text from the logs, so we log only metadata.”
Sharper take“Then nothing can be diagnosed. I redact personal data on the way in, hash identifiers, keep full text for a short window under access control, and make deletion reach the traces too.”
24.10Tools and the day-one contract
Buy the plumbing; the judgment stays yours.
| Tool | Shape | When it fits |
|---|---|---|
| Langfuse | Open source and self-hostable: tracing, prompt versions, datasets, evaluations, cost. Acquired by ClickHouse in January 2026 | When traces hold regulated data and must stay in your infrastructure |
| LangSmith | LangChain’s hosted platform: tracing, datasets, judges, playground | Teams already using LangChain or LangGraph (Chapter 21) |
| Braintrust, Arize Phoenix, W&B Weave | Platforms that start from evaluation or from ML operations and add tracing | Wherever the team’s work already lives |
| OpenTelemetry into your existing stack | Datadog, Grafana, Honeycomb and others with GenAI attributes | Teams with strong observability practice, willing to build the LLM-specific views |
Judge tools on capture of full inputs and outputs, export of your data, a self-hosted or regional option, and whether someone who is not an engineer can read a failing conversation in the interface. None of them supplies your test set, your slices or your definition of good.
Whatever the tool, the contract below is about a day’s work, and adding it after the first incident costs far more.
every model, tool and retrieval call -> a span with its full input and output
every span -> model, prompt version, tokens in / out / cached, latency,
cost, stop reason, retries, tool arguments and results,
chunk IDs with scores and filters
every trace -> trace ID, session ID, user ID, tenant ID
every feedback -> an event attached to its trace
every boundary -> an audit record: tool calls, outbound requests
from the start -> redaction, retention windows, access controlCommon take“Tracing is phase two.”
Sharper take“Phase two arrives after the first incident, and that incident will be unexplainable. Tracing ships with the first endpoint.”
Key takeaways
- A wrong answer is a successful request. Error rates and latency miss every quality failure.
- Trace each task as a tree of spans with full inputs and outputs, prompt version, tokens, retrieved chunks and IDs that reach the tenant.
- Watch distributions. In simulation, 1% of tasks took 36% of spending, and loops hitting the step cap, a third of a percent of tasks, took 23%.
- Every feedback signal is biased. Attach each to its trace, where it becomes a test case.
- Run code checks on all traffic and calibrated judges on a sample stratified by slice.
- When quality moves, rule out your deploys, your data, your users and your judge before blaming the model.
- Temperature 0 is not repeatable. Replay a captured request many times and count: five clean replays hide a 5% failure 77% of the time.
- Alert on sustained change per slice. A single-day threshold raised false alarms in three periods out of four; a seven-day rule in one in twenty, catching a real drop in about four days.
- Traces are your most sensitive log: redact on the way in, limit retention and access, and make deletion reach them.
Check your understanding
-
A customer says the assistant gave the wrong refund window on Tuesday afternoon. Your traces record latency, model and token counts, but not prompt text, retrieved chunk IDs or prompt version, because a privacy review removed free text. What can you no longer do, and what design satisfies both privacy and diagnosis?
Answer outline
You cannot check whether the right policy passage was retrieved (section 15.9), find the first step that carried a false value (section 19.2), tell whether a prompt change caused it, or turn the failure into a test case. Reproducing it locally does not substitute: without the exact request there is nothing to replay, and even with it, temperature 0 is not repeatable. The design: redact personal data before storage, replace identifiers with keyed hashes, keep chunk IDs, prompt versions and model identifiers indefinitely (they are not personal data), keep full text for a short window under role-based, logged access, and make deletion requests reach the traces. If you could add one field first, add the retrieved chunk IDs with the prompt version: together they settle most “wrong answer” reports.
-
Over three weeks, with nothing deployed on your side: schema-validation retries rise from 3% to 14%, the judged groundedness score is flat, citation checks are flat, regenerations are up 1.2 points, cost per task is up 21% and 95th-percentile latency is up 900 ms. A colleague wants to switch providers. What do you check, in what order, and what does the pattern already suggest?
Answer outline
Retries tripling while groundedness stays flat says the content is still right but its form is breaking: the model emits invalid structure, the harness retries, and the retries add cost and latency. That points at model drift, a provider update behind the same name, or at a change in your own requests, such as a tool schema or a dependency upgrade. Check your deploy and dependency logs first, then the model identifier on the failing spans and the provider’s change notes, then whether the failures concentrate on one schema or route. Regenerations rising shows users feel it even though the judge does not, because the judge grades only the answers that eventually succeeded. Mitigate by pinning the previous snapshot or falling back while you confirm; switching providers is a large change made on a guess.
-
Roughly one agent task in fifteen ends in a confidently wrong answer. It cannot be reproduced on demand, always happens after eight or more steps, and always involves the lookup_account tool. Plan the investigation.
Answer outline
Query traces for tasks with lookup_account and eight or more steps, and compare the wrong ones with the right ones: steps, context size at each step, the size and content of lookup_account’s results, and the step where the final claim first appears. Capture several failing requests and replay each twenty times; three in twenty is a tail for validation and retry, eighteen in twenty is systematic. Then perturb: trim the tool result to the fields needed (section 18.2), clear older tool results from the context (section 20.4), and check the tool’s output against the account record (section 19.2). Whichever change stops the failure names the cause. Promote the failing tasks into the test set under a long-task, account-lookup slice, asserting on the final state, not the path (section 23.10).
Further reading
- Shreya Shankar and Hamel Husain, Evals for AI Engineers (O’Reilly, 2026): the chapters on continuous integration and on interfaces for human review.
- Chip Huyen, AI Engineering, chapter 10: monitoring, feedback and the architecture of AI applications in production.
- OpenTelemetry, semantic conventions for generative AI: the span and attribute names, with their current stability status.
- Horace He and Thinking Machines Lab, “Defeating Nondeterminism in LLM Inference” (2025): why temperature 0 still varies, and what it takes to stop it.
- Betsy Beyer and others, Site Reliability Engineering (O’Reilly, 2016): the chapter on service level objectives and error budgets.