llm.guideChapter 24LLM Observability

LLM Observability

Traces, cost forensics, drift detection and incident runbooks.

Part 6: Production disciplines. 10 sections, about 20 minutes.

0 s1 s2 s3 s4 s5 s6 s7 srequest /support/answerretrieve: hybrid search50 chunksreranktop 5llm: plan3,210 in, 240 outtool: get_order(ORD-4412)200 OKllm: answer, streamed4,020 in, 380 out; first token 0.9 svalidate: schema, citationspassIllustrative spans. Cost, tokens and timings on every span are what make the forensics in this chapter possible.
request: 6.9 s in allretrieve + rerank0.7 s, 50 → 5 chunksllm: plan2.1 s, 3,210 in, 240 outtool: get_order0.4 sllm: answer3.4 s, first token at 0.9 svalidate0.1 s, pass
One request as a trace waterfall, with illustrative numbers. Every span carries its timing, tokens and result; what was not captured cannot be measured, replayed or turned into a test.

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 serviceA language model feature
Same inputSame outputPossibly a different output, even at temperature 0 (section 24.7)
A failureAn exception, a 500, a stack traceA 200 response containing a fluent wrong answer (section 2.11)
What happenedThe log line and the requestEverything that was in the context window at that step
Reproducing itReplay the requestReplay 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."
0 s1 s2 s3 s4 s5 strace support_queryroutersmall model120 msretrievalhybrid + rerank340 msllm step 16,204 in, 96 out1.9 stool get_orderstatus ok210 msllm step 26,890 in, 180 out2.1 s
Figure 24.1 The same trace as a waterfall. The two model steps take 86% of the time, and the second one starts only after the tool returns: the critical path is sequential.

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:

FieldThe question it answers
Full input and output text of every spanWhat did the model actually see and say?
Model identifier and prompt versionDid a prompt or model change cause this (section 13.8)?
Tokens in, out and cachedWhat did it cost, and is caching working (section 11.6)?
Time to first token and total timeWas the wait in reading the input or in writing the output (section 2.7)?
Stop reason and retry countWas the output cut off? Is the model struggling (section 19.3)?
Tool arguments and resultsWhere did a false value enter?
Retrieved chunk IDs, scores and filtersWas the answer retrievable at all?
Trace, session, user and tenant IDsWho 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.

0%25%50%75%100%0.1%1%10%100%share of all spendingshare of tasks, most expensive firsttop 1%: 36% of spendtop 5%: 59%
0%25%50%75%100%0.1%1%10%100%share of spendingshare of taskstop 1%: 36% of spendtop 5%: 59%
  • simulated tasks
  • if every task cost the same
Figure 24.2 Simulation of 100,000 tasks. Tasks are sorted from most to least expensive; the line shows how much of the total spending the most expensive ones account for. The dashed line is what equal costs would give. The horizontal scale is logarithmic.

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.

QuestionRead from traces asWhat it catches
Where does the money go?Cost summed by route, tenant, feature and prompt versionThe 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 tracesInput that grew, which slows reading, or output that grew, which slows writing
Is caching working?Cached tokens as a share of input, by prompt versionA deploy that put a changing value at the start of the prompt
Are agents wandering?Distribution of steps per task; histogram of tool callsLoops 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.

SignalStrengthBias
Thumbs up or downExplicit, already labeledGiven by a few percent of users, more often when annoyed. Good for finding failures, poor for measuring a rate
Regenerate or retryFrequent, behavioralThe user rejected the answer with their hands. Among the strongest cheap signals
Rephrased follow-up (“no, I meant…”)Frequent; needs no buttonMust be detected in the session, often by a small model
Copy, accept, applyFrequent, positiveExists only where the interface has such an action
Escalation, task completionClosest to business valueSlow, and moved by many things besides answer quality
AbandonmentFrequentAmbiguous: 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.

Live trafficCode checks on 100%schema, citation, refusal, cost, latencySample 1 to 10%by sliceJudgespinned, calibratedA trend per slicewith a noise band; alert onsustained change (24.8)
Figure 24.3 Online evaluation arranged by cost: free checks on everything, judges only on a stratified sample, and alerts only on change that outlasts the noise.

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.

DriftWhat changedIts signature
ModelThe 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
DataYour documents changed: new sources, a new parser, a restructureRetrieval scores and recall move, in step with ingest jobs (section 15.8)
QueryYour users changed: a new feature, segment or languageThe mix of topics, lengths and languages shifts; the test set quietly stops matching traffic
InstrumentYour judge’s model or prompt changedJudge 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.

Did you deploy anything when it moved?yesyour change: diff it, replay traces(24.7)noDid only judge scores move, with code checks flat?yesinstrument drift: recalibrate the judgenoDid retrieval scores move with an ingest job?yesdata drift: check the parser and sourcesnoQuery or model driftshifted topic or language mix → query; a step on a quiet date, format failures first → model
Figure 24.4 The checking order as a flow. The cheapest explanation, your own change, comes first; the provider’s silent update is what remains when the others are ruled out.

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.

  1. 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.
  2. Replay it many times, because you are sampling from a distribution, and count the failures.
  3. 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.
  4. 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.

0%50%100%15101520chance of seeing the failure at least oncereplays of the captured request23%64%
0%50%100%15101520chance of seeing itreplays23%64%
  • fails 50% of the time
  • 15%
  • 5%
Figure 24.5 Computed. The chance that a failure shows up at least once in a given number of replays, for failures that happen 50%, 15% and 5% of the time.

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.

84%88%92%96%1306190judged pass rateday89%: single-day rule90.2%: seven-day ruledrop begins
84%88%92%96%1306190judged pass rateday89%90.2%drop begins
  • one day
  • seven-day average
  • thresholds and the start of the drop
Figure 24.6 Simulation, one of 5,000 ninety-day periods. Dots are daily pass rates from 300 judged traces; the line is the seven-day average. The dashed lines are the two alert thresholds, at 89% for a single day and 90.2% for the average.
RuleFalse alarm in 54 normal daysDays to detect the drop
Any single day below 89%76% of periods1, but it is rarely believed
Seven-day average below 90.2%, three standard deviations below normal5% of periods4 (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.

SymptomFirst checkFast mitigation
Quality drop after a deployPrompt and code versions in the failing tracesRoll back the prompt version behind its flag
Step change with no deployModel identifier and provider statusSwitch to the pinned fallback model (section 19.5)
Harmful outputs, such as unauthorized promises or data exposureWhich tool or route produced themDisable that tool or route with a kill switch; add an output check
Cost spikeSteps per task and the most expensive tracesLower the step and token budgets; route more traffic away from the agent
Latency spikeTime to first token against output length; provider latencyShorter 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.

Trace t_8812 · refunds · prompt v14viewed by reviewer_3, loggedConversationuserI was charged twice for [ORDER_1].assistantRefunds take 30 days for all orders.userThat’s not what [PERSON_1] said.Retrieved passagesDuplicate charges are refundedin 5 days.Standard refunds take up to 30days.VerdictPassFailFailure tagswrong policyignored contextmissed escalationtoneNote: the right passage was retrieved; the answer used the other one.→ faithfulness failure (15.6), add to the incident slice
Figure 24.7 A review screen with the pieces this section asks for: placeholders instead of names, the evidence beside the answer, a verdict, tags that feed error analysis, and a record of who looked.

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.

ToolShapeWhen it fits
LangfuseOpen source and self-hostable: tracing, prompt versions, datasets, evaluations, cost. Acquired by ClickHouse in January 2026When traces hold regulated data and must stay in your infrastructure
LangSmithLangChain’s hosted platform: tracing, datasets, judges, playgroundTeams already using LangChain or LangGraph (Chapter 21)
Braintrust, Arize Phoenix, W&B WeavePlatforms that start from evaluation or from ML operations and add tracingWherever the team’s work already lives
OpenTelemetry into your existing stackDatadog, Grafana, Honeycomb and others with GenAI attributesTeams 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 control

Common 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

  1. 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.

  2. 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.

  3. 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.

↑↓ to move↵ to openesc to close