Production LLM systems need more than uptime checks. This guide shows what to trace, which metrics to calculate, how to log requests without collecting unnecessary sensitive data, and how to use evidence to separate prompt, retrieval, provider, and application failures.
Overview
LLM observability is the practice of making an AI application's behavior measurable and diagnosable. A useful observability setup connects a user request to the complete execution path: prompt construction, retrieval, model invocation, tool calls, validation, response delivery, and user feedback.
Traditional web monitoring can tell you that an endpoint returned an error or became slow. LLM tracing must also explain why the result was poor. A response may be valid JSON but contain unsupported claims, use irrelevant retrieved passages, exceed a latency target, or consume more tokens than expected. These are different failures and require different remedies.
At minimum, monitor four dimensions:
- Correctness: whether the output meets task requirements and agreed evaluation criteria.
- Performance: latency, time to first token, timeout rate, retry rate, and throughput.
- Efficiency: input and output tokens, requests per workflow, cache use, and estimated cost.
- Safety and reliability: refusals, policy violations, prompt injection signals, tool errors, malformed output, and provider failures.
Observability is not a reason to store every prompt forever. The goal is to retain enough structured evidence to debug and improve the system while limiting exposure of personal, confidential, or customer data. For related quality practices, see the LLM evaluation guide and the AI output monitoring guide.
How to estimate
Start with a request-level trace and calculate metrics from the same unit of work. A trace can represent one chat turn, document-processing job, support ticket, or agent task. Spans within that trace should represent meaningful steps rather than every internal function.
1. Define the trace boundary
Record a stable trace ID when the request enters your application. Pass it through retrieval, model, and tool layers. Use a separate span ID for each operation. If a workflow makes several model calls, keep them under the same trace so you can measure both individual calls and total workflow time.
2. Calculate core metrics
Use consistent formulas so dashboards remain comparable:
- End-to-end latency = response completion time minus request start time.
- Model latency = model response completion time minus model request start time.
- Retrieval latency = retrieval completion time minus retrieval start time.
- Time to first token = first streamed token time minus model request start time.
- Error rate = failed traces divided by total traces, measured over the same interval.
- Retry rate = retried model or tool calls divided by total calls.
- Average tokens per trace = total input and output tokens divided by completed traces.
- Estimated usage cost = input tokens multiplied by the input rate plus output tokens multiplied by the output rate. Store the rates used for the calculation rather than assuming they remain unchanged.
Percentiles are usually more informative than averages for latency. Track a median for typical behavior and a high percentile for the slow requests users experience during load, long prompts, retrieval misses, or provider congestion. Choose an interval and keep it stable when comparing releases.
3. Connect metrics to outcomes
Technical metrics alone do not show whether an AI feature is useful. Add a small set of outcome signals, such as validator success, citation coverage, escalation rate, user correction, task completion, or evaluator score. Segment them by model, prompt version, retrieval strategy, tenant, language, and workflow type where those dimensions are operationally relevant.
Inputs and assumptions
A trace is only useful when its fields have clear definitions. The following request-trace model is a practical starting point:
| Field group | Recommended fields | Purpose |
|---|---|---|
| Identity | trace_id, span_id, parent_span_id, environment, service_version | Reconstruct the execution path and compare releases. |
| Request | workflow, route, tenant_hash, locale, request_size_class | Segment behavior without retaining unnecessary identifiers. |
| Prompt | prompt_id, prompt_version, system_prompt_hash, template_variables_hash | Identify which prompt configuration produced the result. |
| Model | provider, model_id, temperature_or_sampling_config, finish_reason | Compare model behavior and incomplete generations. |
| Tokens | input_tokens, output_tokens, cached_tokens_if_available | Estimate usage, capacity, and cost. |
| Retrieval | query_hash, index_version, result_count, top_score, retrieval_latency | Separate missing or weak context from generation errors. |
| Tools | tool_name, argument_schema_version, duration, success, error_class | Diagnose actions that fail outside the model. |
| Outcome | validation_status, evaluator_label, user_feedback_class, escalation | Connect system behavior to quality and business results. |
Use redaction, hashing, allowlists, and sampling deliberately. For example, store a prompt version and a hash of a customer identifier instead of the raw identifier. Keep a restricted debugging sample of content only when there is a documented operational need, access control, retention period, and deletion process. Avoid logging authorization headers, API keys, full retrieved documents, or raw tool arguments by default.
Do not treat provider-specific response fields as universal. Normalize common concepts such as token counts, finish status, and usage errors, but retain a provider-specific field for details that do not map cleanly. This makes migrations easier without discarding useful diagnostic information; the provider migration checklist covers related compatibility concerns.
Worked examples
Example 1: Estimating usage and cost
Assume a document assistant processes 10,000 traces in a reporting period. Each trace averages 2,400 input tokens and 600 output tokens. The application therefore uses:
- Input tokens: 10,000 × 2,400 = 24,000,000.
- Output tokens: 10,000 × 600 = 6,000,000.
- Total tokens: 30,000,000.
To estimate spend, insert the rates from the provider and model configuration used during that period: (24,000,000 × input-token rate) + (6,000,000 × output-token rate). Keep input and output rates separate because they may differ. Recalculate after changing models, prompt length, retrieval context, caching behavior, or output limits. This estimate excludes other expenses unless you add them separately, such as embedding generation, vector storage, tool execution, and observability storage.
Example 2: Finding the source of latency
Suppose a trace takes 5.2 seconds end to end. Retrieval takes 0.8 seconds, the model call takes 3.7 seconds, and application validation plus response delivery takes 0.7 seconds. The components sum to the observed duration, so the model is the largest contributor. If a release increases total latency to 7 seconds while retrieval rises to 2.5 seconds and model time remains stable, the likely investigation should begin with the index, query construction, or retrieval service rather than the prompt.
Example 3: Separating quality failures
For a failed answer, inspect the trace in order: Was the correct prompt version loaded? Did retrieval return relevant content? Did the model follow the requested output structure? Did schema validation pass? Did a tool return an error? This sequence prevents a team from rewriting a prompt when the real issue is an empty index result or a downstream timeout. For structured response failures, pair tracing with the practices in structured output prompts and validation.
When to recalculate
Review your LLM observability model whenever an input that affects behavior changes. Recalculate usage and cost after a model switch, prompt revision, retrieval change, context-window increase, traffic shift, caching change, or tool-call redesign. Recheck latency baselines after infrastructure changes or when a new streaming pattern is introduced.
Use a lightweight weekly review to inspect error rate, latency percentiles, token distribution, validation failures, and user feedback. Use a deeper review after incidents and releases. Compare the same workflow and traffic segment before drawing conclusions; mixing short classification requests with long agent tasks can hide meaningful regressions.
When an incident occurs, preserve the trace IDs, deployment version, prompt version, model identifier, and relevant provider request IDs. Classify the failure as application, retrieval, prompt, model/provider, tool, safety, or observability pipeline failure. Then assign one corrective action and one verification measure. For a fuller response process, use the LLM incident response runbook.
Finally, review dashboards and retention rules at least when instrumentation or pricing inputs change, and periodically confirm that the fields you collect still support real investigations. Good LLM tracing is not a larger log stream; it is a dependable chain of evidence that helps your team reduce latency, control usage, improve prompts, and restore service with less guesswork.