Production language model pipelines fail differently from deterministic microservices. An HTTP 200 response with a 420-millisecond time-to-first-token can still return an ungrounded hallucination, exhaust a tenant's monthly token budget in an unbounded tool-calling loop, or silently degrade after an upstream provider swaps a model checkpoint. Engineering reliable AI systems requires extending distributed tracing with semantic telemetry, real-time token cost ledgers, and statistical drift detectors.
Why Standard APM Falls Short for LLM Workloads
Conventional Application Performance Monitoring (APM) tools track request rate, error rate, and duration (RED metrics) alongside CPU and memory saturation. While necessary for host health, those signals miss the primary failure modes of generative pipelines. When a retrieval-augmented generation (RAG) endpoint returns a fabricated citation, the HTTP status code is 200 OK, memory consumption remains flat, and container CPU sits idle waiting on external GPU inference.
Latency profiles in autoregressive generation also violate standard APM assumptions. A typical REST microservice exhibits relatively tight latency variance determined by database index lookups and network hops. In contrast, language model inference has two distinct regimes: the prefill phase, which is compute-bound and scales with input prompt length, and the decode phase, which is memory-bandwidth-bound and scales linearly with the number of generated output tokens. Reporting a single end-to-end duration conflates a 100-token classification call with a 4,000-token document synthesis call. Production observability must separate Time to First Token (TTFT), Time Per Output Token (TPOT), and total generation wall time.
Multi-step agentic workflows compound this visibility gap. A single user request may trigger query rewriting, hybrid vector-plus-BM25 retrieval, cross-encoder reranking, three iterative tool invocations, and a final synthesis pass. Without hierarchical span context linking each LLM call to the parent business transaction, debugging a slow or erroneous response requires correlating unstructured logs across multiple worker processes. Furthermore, payload inspection is complicated by privacy constraints: logging raw prompts in cleartext exposes personally identifiable information (PII), requiring scrubbers at the telemetry collector layer.
OpenTelemetry Instrumentation: Spans, Attributes, and Sampling
OpenTelemetry (OTel) has standardized generative AI semantic conventions under the gen_ai.* namespace, enabling vendor-neutral instrumentation across gateways, orchestrators, and inference engines. Every model invocation should execute inside a dedicated child span nested under the parent workflow or HTTP request span. When an agent loops over external tools, each iteration creates an orchestration span containing child spans for the model completion and the tool execution.
Capturing high-cardinality diagnostic data without exploding storage costs requires disciplined attribute design. Core numeric and categorical attributes—such as model identifier, provider name, token counts, temperature, and finish reason—belong on every span so they can be indexed for fast aggregation. Full prompt and completion payloads, which can exceed 100 kilobytes per call, should be emitted as structured span events or offloaded to object storage via content-addressed hashes, controlled by tail-based sampling rules.
from opentelemetry import trace
from opentelemetry.trace import SpanKind, Status, StatusCode
import time
tracer = trace.get_tracer("llm.observability.gateway", "1.2.0")
PRICING_PER_1K = {
"gpt-4o-2024-08-06": (0.0025, 0.0100),
"claude-3-5-sonnet-20241022": (0.0030, 0.0150),
}
def invoke_instrumented_llm(client, model: str, messages: list, tenant_id: str, feature: str):
with tracer.start_as_current_span(
name=f"chat {model}",
kind=SpanKind.CLIENT,
attributes={
"gen_ai.system": "openai_compatible",
"gen_ai.request.model": model,
"gen_ai.request.temperature": 0.2,
"tenant.id": tenant_id,
"product.feature": feature,
},
) as span:
t0 = time.perf_counter()
try:
response = client.chat.completions.create(
model=model,
messages=messages,
temperature=0.2,
stream=True,
stream_options={"include_usage": True},
)
ttft_ms = None
chunks = []
usage = None
for chunk in response:
if ttft_ms is None and chunk.choices and chunk.choices[0].delta.content:
ttft_ms = (time.perf_counter() - t0) * 1000.0
if chunk.choices and chunk.choices[0].delta.content:
chunks.append(chunk.choices[0].delta.content)
if getattr(chunk, "usage", None) is not None:
usage = chunk.usage
total_ms = (time.perf_counter() - t0) * 1000.0
prompt_tok = usage.prompt_tokens if usage else 0
comp_tok = usage.completion_tokens if usage else 0
cached_tok = getattr(usage.prompt_tokens_details, "cached_tokens", 0) if usage else 0
in_rate, out_rate = PRICING_PER_1K.get(model, (0.003, 0.012))
billable_in = max(0, prompt_tok - cached_tok) + (cached_tok * 0.5)
cost_usd = (billable_in / 1000.0) * in_rate + (comp_tok / 1000.0) * out_rate
span.set_attribute("gen_ai.usage.input_tokens", prompt_tok)
span.set_attribute("gen_ai.usage.output_tokens", comp_tok)
span.set_attribute("gen_ai.usage.cached_tokens", cached_tok)
span.set_attribute("llm.latency.ttft_ms", round(ttft_ms or total_ms, 2))
span.set_attribute("llm.latency.tpot_ms", round((total_ms - (ttft_ms or 0)) / max(1, comp_tok), 2))
span.set_attribute("llm.cost_usd", round(cost_usd, 6))
span.set_status(Status(StatusCode.OK))
return "".join(chunks)
except Exception as exc:
span.record_exception(exc)
span.set_status(Status(StatusCode.ERROR, str(exc)))
raise
Tail-based sampling in the OpenTelemetry Collector ensures that 100% of traces containing errors, elevated latency (such as TTFT above 2,500 milliseconds), negative user feedback, or guardrail triggers are retained with full prompt/response bodies, while normal traffic is sampled at 5% for payload storage and 100% for aggregated metric counters. This hybrid approach keeps observability storage below 2% of total inference spend.
Token Cost Attribution: Per-Feature and Per-Team Budgeting
Unlike provisioned database instances with fixed monthly capacity, language model APIs and elastic GPU clusters bill per token. A single unoptimized prompt template that injects an entire conversation history or an unfiltered 30-page retrieval chunk can multiply daily spend tenfold overnight. Financial governance requires attributing every input, cached, and output token to an organizational owner (`team`), a product surface (`feature`), an environment (`staging` vs. `prod`), and a customer tier.
Accurate cost calculation must account for modern pricing mechanics: prompt caching discounts (typically 50% to 90% off cached prefix tokens), batch API discounts (50% off asynchronous workloads), and reasoning token multipliers on frontier thinking models where internal chain-of-thought tokens are billed as output tokens despite never appearing in the visible response. By propagating W3C Trace Context Baggage (`baggage: team=search,feature=semantic_rerank,tenant=enterprise_42`) from the ingress gateway down to every model wrapper, the telemetry pipeline computes exact micro-dollar cost at the span level.
| Telemetry Dimension | OTel Attribute Key | Baseline Target | Alert / Circuit-Breaker Trigger |
|---|---|---|---|
| Prefill Responsiveness | llm.latency.ttft_ms |
P95 < 650 ms | P99 > 1,850 ms over 5m window |
| Decode Throughput | llm.latency.tpot_ms |
P95 < 22 ms/tok | P99 > 55 ms/tok (GPU KV thrash) |
| Prefix Cache Efficiency | gen_ai.usage.cached_ratio |
> 0.68 on chat | Drops below 0.40 after deploy |
| Feature Spend Velocity | llm.cost_usd |
$1.80 / hr / feature | Hourly burn > 250% of 7d moving avg |
| Semantic Query Drift | eval.centroid_cosine_sim |
≥ 0.88 vs baseline | < 0.82 over 1,000-query rolling window |
| Grounded Faithfulness | eval.faithfulness_score |
≥ 0.94 on sampled RAG | < 0.89 or +3% hallucination delta |
Semantic Drift and Hallucination Rate Monitoring
Even when infrastructure latency and token budgets remain stable, output quality can erode due to two forces: covariate shift in user queries (users begin asking about new product lines or seasonal events absent from the knowledge base) and concept drift in model behavior (provider checkpoint updates or prompt edits that subtly alter formatting and refusal rates). Detecting these shifts without human labeling on every request requires automated statistical and model-based evaluation pipelines running asynchronously off the critical path.
To measure query and response distribution shift, the telemetry worker embeds a 10% sample of incoming user queries and generated responses using a lightweight embedding model (such as a 384-dimension distilled encoder) and computes the rolling centroid vector over 1,000-request windows. When the cosine similarity between the current window's centroid and the golden reference centroid drops below 0.82, or when the Maximum Mean Discrepancy (MMD) across embedding clusters spikes, an alert flags the topic cluster that diverged. In RAG systems, pairing this with retrieval score monitoring—tracking the top-k dense similarity scores and cross-encoder logits—immediately distinguishes whether bad answers stem from missing knowledge base documents or from generation failures.
For hallucination detection, an asynchronous evaluator consumes sampled spans from Kafka or the OTel collector and runs a decomposed NLI (Natural Language Inference) or small judge model check. The evaluator splits the generated response into atomic factual claims and verifies whether each claim is entailed by the retrieved context chunks recorded on the span. Tracking the fraction of unsupported claims yields a continuous hallucination rate metric (`1 - faithfulness_score`). Correlating this metric against prompt version tags (`prompt.git_sha`) catches regressions within minutes of a Canary rollout.
Alerting, Dashboards, and Cost Governance at Scale
Actionable LLM dashboards separate real-time operational health from asynchronous quality evaluation. The primary SRE panel plots P50, P95, and P99 TTFT and TPOT broken down by model and region, overlaid with prefix cache hit rates and token-per-second throughput. Implementing semantic caching and prefix-aware routing routinely compresses P99 end-to-end latency from 1,850 milliseconds down to 620 milliseconds while cutting input token expenditure by 45%. Visualizing cache hit rate directly alongside latency makes cache invalidation bugs—such as injecting a dynamic timestamp at the very top of a system prompt, which busts prefix caching on every call—immediately obvious.
Cost governance moves beyond passive dashboards by enforcing automated rate limits and circuit breakers at the AI gateway layer. Each feature and tenant is assigned a token-bucket quota expressed in USD per hour rather than raw request counts, preventing a flood of 100K-context requests from bypassing simple RPM (requests per minute) limiters. When a non-critical background job exceeds 200% of its hourly cost budget, the gateway automatically downgrades its routing tier from a frontier model to a distilled flash or mini variant, preserving availability while halting runaway spend. Combining OpenTelemetry tracing, granular token accounting, and continuous faithfulness scoring transforms language model deployments from opaque black boxes into predictable, auditable production systems.