Introduction
Large language models have moved from experimental prototypes to production services that power customer-facing chatbots, code assistants, summarization tools, and decision-support systems. Unlike traditional software, where a feature either works according to specification or it does not, LLM outputs are probabilistic, context-dependent, and expensive to generate. A model can return a plausible but factually wrong answer, emit a response that leaks internal data, or consume thousands of tokens on a single request without any obvious failure signal.
This guide provides a practical framework for building LLM observability pipelines. Observability is the practice of understanding what your system is doing from the outside in, using telemetry such as metrics, traces, and logs. For LLM applications, observability answers critical questions: How much does each request cost? How long does the model take to respond? Which prompts trigger errors or refusals? Are responses regressing in quality over time?
By the end of this article, you will understand how to instrument an LLM application, which metrics matter most, how to trace multi-step agentic workflows, and how to set up alerting that catches regressions before users notice them.
Core Pillars of LLM Observability
LLM observability rests on three telemetry pillars: metrics, tracing, and logging. Each pillar answers a different class of question, and together they give you a complete picture of system health.
Metrics
Metrics are numerical measurements aggregated over time. They are ideal for dashboards, service-level objectives, and alerts. Key LLM metrics include:
- Request volume: Number of LLM calls per minute, broken down by model, endpoint, and user.
- Token usage: Input and output tokens per request. Token volume is the primary cost driver, so tracking it granularly prevents budget surprises.
- Latency: Time to first token (TTFT), tokens per second (TPS), and end-to-end request latency. Latency distributions should be tracked at p50, p95, and p99, not just as averages.
- Error rate: Rate of provider errors (429 rate limits, 503s), validation errors (context window exceeded), and structural failures (invalid JSON).
- Refusal rate: How often the model declines to answer due to safety filters. A rising refusal rate can indicate overly restrictive system prompts.
Tracing
A single user request often triggers multiple LLM calls, tool invocations, retrieval steps, and post-processing operations. Tracing connects these steps into a single timeline, showing where time and tokens are spent. Each span in a trace should record the model name, prompt, input token count, output token count, latency, and result status. Traces are essential for debugging agentic workflows where a failure in one step cascades into downstream errors.
Logging
Logs capture discrete events, such as a single model call with its full prompt and response, or a safety filter interception. Structured logs (JSON) make it possible to search for specific failure modes, such as all responses containing a particular error phrase, or all requests exceeding a token threshold.
Key Metrics to Track in Production
Not all metrics are equally actionable. Focus on these five categories.
Cost and Token Efficiency
Token usage is directly tied to spend. Track input and output tokens separately, because providers price them differently. Aggregate by model, endpoint, user ID, and feature. For example, a summarization feature may consume ten times more tokens than a classification feature. Set budget alerts at daily and monthly thresholds, and alert on sudden per-request spikes that could indicate prompt injection, infinite loops, or unexpected model verbosity.
Latency and User Experience
Time to first token determines whether an interface feels responsive. For streaming applications, TTFT under one second is a common target. Total request latency determines throughput. Track p99 latency because LLM latency has a long tail: provider congestion and long outputs create outliers that averages hide. If p99 exceeds your threshold, consider falling back to a smaller model or returning a cached response.
Error Classification
Classify errors into actionable buckets rather than treating them as a single number:
- Validation errors: Prompt exceeds context window or fails a safety filter. Usually client-side.
- Provider errors: Timeouts, 429 rate limits, or 503 service unavailable. Require exponential backoff and retry.
- Output failures: The model returned a response, but it failed a structural check, such as invalid JSON. Indicates a need for better prompting or few-shot examples.
- Safety interventions: The model refused due to a policy violation. Track refusal rate to tune system prompts without compromising safety.
Distributed Tracing for LLM Chains
In agentic applications, one user request can fan out into many LLM calls. A research agent might retrieve documents, summarize each one, synthesize an answer, and then verify citations. Without tracing, a slow or expensive request is impossible to debug.
Each trace should have a root span representing the user request, and child spans for each LLM call, tool call, and retrieval step. Record the following attributes on every span:
llm.model: The model identifier, such asclaude-3-5-sonnet-20241022.llm.prompt: The full prompt text, redacted for secrets.llm.input_tokensandllm.output_tokens: Token counts.llm.latency_ms: Duration of the call.llm.finish_reason: Why the model stopped, such asstop,max_tokens, orcontent_filter.
Trace context should propagate across service boundaries so that a request originating in your web frontend remains connected to model calls in backend workers.
Alerting and Service-Level Objectives
Define service-level objectives (SLOs) that translate observability data into business commitments. Example SLOs for an LLM application:
- 99% of requests complete within five seconds.
- 99.9% of requests receive a structurally valid response.
- Monthly token spend stays within budget.
- Refusal rate remains below 2%.
Alerts should fire on SLO violations and on anomalous changes. A sudden 50% increase in average output tokens could indicate a prompt change that made the model more verbose. A spike in 429 errors means you are being rate limited and may need to add retry logic or request a higher quota.
Practical Implementation Example
The following Python sketch shows how to wrap an LLM call with telemetry:
import time
import json
from opentelemetry import trace
from opentelemetry.trace import Status, StatusCode
tracer = trace.get_tracer(__name__)
def track_llm_call(model, messages, generate_fn):
with tracer.start_as_current_span("llm.call") as span:
span.set_attribute("llm.model", model)
prompt_text = json.dumps(messages)
span.set_attribute("llm.prompt", prompt_text[:4000])
start = time.time()
try:
response = generate_fn(model, messages)
latency_ms = (time.time() - start) * 1000
span.set_attribute("llm.latency_ms", latency_ms)
span.set_attribute("llm.input_tokens", response.input_tokens)
span.set_attribute("llm.output_tokens", response.output_tokens)
span.set_attribute("llm.finish_reason", response.finish_reason)
span.set_status(Status(StatusCode.OK))
return response
except Exception as exc:
span.record_exception(exc)
span.set_status(Status(StatusCode.ERROR, str(exc)))
raise
This wrapper records every call as a trace span, captures token counts and latency, and flags exceptions. Integrate it with your observability backend so spans appear alongside HTTP and database traces.
Limitations and Pitfalls
Observability is not a substitute for evaluation. Metrics tell you that something changed, but not whether the change is good or bad. Pair observability with offline evaluation datasets and LLM-as-a-judge scoring to assess quality. For more on patterns for complex autonomous workflows, see our guide on Agentic LLM Workflows: Planning, Reflection, and Self-Correction Patterns.
Token counting varies by provider and tokenizer. A token count from one provider is not directly comparable to another, so avoid cross-provider cost comparisons unless you normalize by model.
Prompt and response logging can capture sensitive user data. Redact personally identifiable information and API keys before writing logs, and retain logs only as long as your compliance policy allows.
Finally, alert fatigue is real. Start with a small set of high-signal alerts—error rate, p99 latency, and daily spend—and expand only after you have tuned thresholds against real traffic.
Conclusion
LLM observability turns a black-box model into an instrumented system you can operate with confidence. By tracking token usage, latency, errors, and refusals; tracing multi-step chains; and alerting on SLO violations, you can catch regressions early, control costs, and maintain user trust as your application scales. Start with the metrics that matter most to your use case, instrument your critical paths, and expand your telemetry as your LLM footprint grows.