Introduction
Large language model deployments introduce observability challenges that traditional application monitoring does not address. A standard APM dashboard can tell you that an API endpoint is slow, but it cannot tell you why a model produced a hallucinated citation, whether token costs are spiking due to a specific prompt template, or which retrieval step failed in a RAG pipeline. LLM applications need observability that spans the full inference lifecycle: input classification, model invocation, tool use, retrieval, and output validation.
This guide describes how to build an observability stack for production LLM applications. It covers distributed tracing across multi-step workflows, token and cost tracking per request, latency measurement by model tier, quality and safety signals, and alerting strategies that distinguish between infrastructure problems and model behavior problems. The examples are hypothetical and designed to be adapted to your own stack.
Why Standard Monitoring Falls Short
Conventional application monitoring focuses on request latency, error rates, and throughput. Those metrics remain necessary but are insufficient for LLM systems. A model can return a 200 OK response in 500 milliseconds while emitting a factually incorrect answer, leaking sensitive data, or consuming ten times the expected token budget. Standard metrics capture none of these failure modes.
LLM observability must answer questions that standard monitoring cannot:
- Which prompts or model versions are driving cost increases?
- Are retrieval-augmented responses grounded in the supplied source documents?
- Do specific input patterns trigger unsafe or off-topic outputs?
- How does latency vary across model tiers in a cascading architecture?
- Which tool calls fail most often in agent workflows?
Without answers to these questions, teams operate blindly. They discover problems through user complaints rather than through their own telemetry.
Distributed Tracing for Multi-Step Workflows
LLM applications rarely make a single model call. A RAG pipeline may embed a query, retrieve documents, rerank results, construct a prompt, call a model, validate the output, and optionally retry with a different model. Each step can fail independently, and a failure in an early step cascades to later ones.
Distributed tracing assigns a trace ID to each user request and a span ID to each step within that request. A trace might contain spans for:
- Query classification - determining the request type and routing
- Embedding generation - converting the query to a vector
- Vector search - retrieving candidate documents
- Reranking - scoring and ordering retrieved results
- Prompt construction - assembling context and instructions
- Model invocation - calling the LLM API
- Output validation - checking the response against constraints
- Post-processing - formatting the final answer
Each span should record its start time, end time, input size, output size, token counts, cost, and status. When a span fails, the trace preserves the full context so engineers can see whether the problem originated in retrieval, generation, or validation.
Trace context must propagate across service boundaries. If your application calls an external LLM API, the trace ID should be included in request headers where the provider supports it. If you use an agent framework, ensure the framework instruments each tool invocation with the current trace context.
Token Usage and Cost Tracking
Token cost is often the most visible operational metric for LLM applications, yet it is also the most easily misunderstood. A single request can consume tokens across multiple stages: the system prompt, few-shot examples, retrieved context, the user query, and the model's response. Tracking must capture all of these components, not just the response tokens.
Cost tracking should be attributed at multiple levels:
- Per request: Total tokens and cost for a single user interaction
- Per prompt template: Which templates consume the most tokens on average
- Per model: Which models are driving the largest share of spend
- Per user or tenant: Which customers or internal teams are responsible for costs
- Per feature: Which application features (search, summarization, code generation) are most expensive
Attribution requires consistent tagging. Every trace span should carry tags for model name, model version, provider, prompt template ID, and feature area. This enables cost breakdown by any dimension.
A common mistake is to attribute cost only to successful requests. Failed requests still consume tokens—especially when a model generates a long response before a validation failure is detected. Track cost for all requests, successful or not.
Latency and Performance Metrics
Latency in LLM applications has several distinct components that should be measured separately:
- Time to first token (TTFT): How long until the first token of the response arrives. This drives perceived responsiveness for streaming interfaces.
- Time per output token (TPOT): The rate at which tokens are generated after the first one. This affects total response time for long outputs.
- Total time to response: The complete elapsed time from request to final output.
- Retrieval latency: Time spent in vector search, reranking, and context assembly before the model call begins.
- Validation latency: Time spent checking the model's output against constraints.
These metrics should be tracked per model tier and per request type. A cascading system that routes simple queries to a fast model and complex queries to a slow model will show bimodal latency distributions. Aggregating all requests into a single average hides this structure.
P50, p95, and p99 latency should be reported for each tier. If the p99 latency for your frontier model is 30 seconds while the p50 is 3 seconds, you need to understand whether long-running requests are retries, complex reasoning tasks, or infrastructure problems.
Quality and Safety Signals
Quality signals measure whether the model's output meets your application's requirements. Unlike infrastructure metrics, quality signals often require application-specific logic:
- Schema compliance: Does the response match the expected JSON structure?
- Citation accuracy: Are claimed sources actually present in the retrieved documents?
- Hallucination rate: How often does the model state facts not supported by the context?
- Refusal rate: How often does the model decline to answer, and on what topics?
- Toxicity score: Does the output contain harmful or policy-violating content?
- User feedback: Thumbs up/down, edit distance, or explicit ratings from users
Quality signals should be computed deterministically where possible. Schema compliance can be checked with JSON Schema. Citation accuracy can be verified by matching claimed source IDs against the retrieval results. Hallucination detection is harder and may require a secondary model or human review, but even lightweight checks (such as verifying that all entities in the response appear in the context) add value.
Safety signals track whether outputs violate usage policies. These include refusal rates by category, detection of prompt injection attempts, and identification of sensitive data (PII, credentials) in model outputs. Safety violations should trigger immediate alerts and, where appropriate, automatic response blocking.
Alerting Strategies
Alerting for LLM applications must distinguish between infrastructure problems and model behavior problems. A spike in 500 errors from the model provider is an infrastructure issue. A gradual increase in hallucination rate is a model behavior issue. They require different responses and different owners.
Suggested alert categories:
Critical (page immediately):
- Model API completely unavailable
- Authentication failures to model providers
- Safety policy violations in outputs
- Data leakage (PII or credentials in model responses)
Warning (ticket within business hours):
- Token cost exceeding daily budget by 20%
- Hallucination rate above threshold
- Schema compliance rate dropping below 95%
- p99 latency exceeding SLA
Info (dashboard only):
- Cost per request trending upward
- New prompt template deployed
- Model version rollout in progress
Alert thresholds should be based on baselines established during normal operation. Do not set static thresholds without data. A hallucination rate of 5% might be acceptable for creative writing but unacceptable for medical triage.
Worked Example: RAG Pipeline Observability
Consider a hypothetical customer support RAG application. When a user submits a question, the system:
- Embeds the question (span: embedding)
- Searches a vector database for relevant support articles (span: retrieval)
- Reranks the top 20 results to 5 (span: reranking)
- Constructs a prompt with the 5 articles and the user question (span: prompt_construction)
- Calls a mid-tier model to generate an answer (span: model_invocation)
- Validates that the answer cites only the retrieved articles (span: validation)
- Returns the answer to the user (span: response)
If step 6 fails, the trace shows exactly where the problem occurred. If retrieval returned irrelevant articles, the validation failure is explained. If the model ignored the retrieved articles and hallucinated a policy, the model_invocation span shows the discrepancy.
Each span records token counts. The engineering team discovers that prompt construction consumes 40% of all tokens because the retrieved articles are long. They implement context pruning and reduce costs by 30% without affecting answer quality.
Limitations and Considerations
Observability adds overhead. Every trace span, every token count, and every quality check consumes compute and storage. Sample traces at 100% for critical paths and at a lower rate (1-10%) for high-volume, low-risk paths.
Model providers vary in what they expose. Some return detailed token usage in API responses; others provide only aggregate usage reports. Build your tracking around what your providers actually expose, and document the gaps.
Quality signals are probabilistic. A schema check is deterministic, but a hallucination score is an estimate. Label quality signals as such in dashboards so that engineers do not treat probabilistic scores as ground truth.
Conclusion
LLM observability is not optional for production AI systems. Standard application monitoring cannot answer the questions that matter for model-driven applications: cost attribution, quality signals, safety violations, and multi-step workflow tracing. Implement distributed tracing across your inference pipeline, track tokens and cost at every stage, measure latency by model tier, and define quality and safety alerts that reflect your application's risk tolerance. Start with the most critical user journeys, measure rigorously, and expand observability coverage as your system grows.
For related guidance on cost-effective model routing, see Model Cascading in Production: Cost-Effective AI Workflow Orchestration, which covers tiering queries across model capabilities.
Sources
- OpenAI Platform: Token Counting - Official guidance on counting tokens in chat completions.
- Anthropic: Token Counting - How Anthropic counts tokens and manages context windows.
- OpenTelemetry: Semantic Conventions for GenAI - OpenTelemetry semantic conventions for LLM observability.
- Arize Phoenix: LLM Tracing - Open-source LLM observability and tracing framework.
- LangSmith: Evaluation and Tracing - Tracing and evaluation platform for LLM applications.