Careers Post-AI
AI infrastructure and systems: all chapters

AI infrastructure and systemsPart 5: Production operations

Chapter 17Observability for AI systems

30 min read, 1 lab, Intermediate

An LLM endpoint can return HTTP 200 on every request while users wait nine seconds for the first word, the GPU sits half idle, and the answers quietly get worse. Classic web monitoring would call that a healthy service; this chapter teaches you to see what is actually happening, from the token to the GPU to the agent run.

After this chapter you can

  • Explain which signals matter for LLM services and why request latency alone misleads
  • Instrument model and tool calls with OpenTelemetry using the GenAI semantic conventions
  • Trace a multi-step agent run end to end and find where its time and tokens go
  • Read GPU telemetry from DCGM and explain what "GPU utilization" does and does not measure
  • Build Prometheus queries and a Grafana dashboard for the golden signals of an LLM service
  • Design prompt logging that respects privacy and detects quality drift

Three signals, applied to tokens

Observability is the ability to answer new questions about a running system from the data it emits, without shipping new code. It rests on three kinds of telemetry. A metric is a number aggregated over time (requests per second, p95 latency). A log is a timestamped record of one event. A trace is the tree of timed operations, called spans, that one request causes as it moves through your services.

LLM systems change what each signal has to carry. A request is no longer one unit of work: it has a prompt phase and a generation phase, a variable number of tokens, and a price. The token is the new unit of work, and your telemetry must count tokens the way web telemetry counts requests.

SignalClassic web serviceLLM service adds
MetricsRequest rate, error rate, latencyTTFT, inter-token latency, tokens in and out, queue depth, KV cache use, cost
LogsRequest line, status, stack tracesPrompt and completion (redacted or sampled), model version, finish reason, refusal flag
TracesService-to-service callsModel calls, retrieval, tool calls, agent steps, retries and fallbacks as child spans

Metrics tell you that something is wrong, traces tell you where, and logs tell you why. You need all three, and they need shared identifiers (a trace ID on every log line) so you can jump between them.

The signals that matter for LLM services

Inference fundamentals taught you that generation has two phases: a compute-heavy prefill over the prompt and a memory-bound decode that emits one token at a time. Your metrics should measure each phase separately, because they fail for different reasons.

SignalDefinitionWhat a change usually means
Queue timeTime from arrival until the server starts workNot enough capacity; batch is full
TTFTTime to first token, as the client sees itQueueing or long prompts (prefill)
Inter-token latency (TPOT)Average gap between output tokensBatch too large, memory bandwidth saturated
Tokens per secondOutput tokens per second, per request and in aggregateThroughput and capacity headroom
Token countsInput, output and cached tokens per requestPrompt bloat, runaway generations, cost
Cache hit rateShare of input tokens served from prefix or prompt cacheCost and TTFT; a drop often follows a prompt change
Error rate5xx, timeouts, provider 429s, context-length errorsOutages, rate limits, oversize inputs
Refusal and empty rateResponses that decline, or finish with no contentSafety filter changes, prompt regressions
Cost per requestTokens times price, summed per requestUnit economics; covered in Cost engineering and GPU economics

Always record latency as a histogram, never as an average. LLM latency is heavy-tailed, so a mean of 2 seconds can hide a p99 of 30 seconds. Record the finish reason too: hitting max_tokens is a different event from a natural stop.

Self-hosted servers expose most of this already. vLLM serves Prometheus metrics at /metrics, including the histogram vllm:time_to_first_token_seconds, the gauge vllm:num_requests_waiting and the gauge vllm:kv_cache_usage_perc (older releases called it vllm:gpu_cache_usage_perc). Metric names shift between versions, so read your server's /metrics output rather than copying names from a blog post.

OpenTelemetry and the GenAI conventions

OpenTelemetry (OTel) is the vendor-neutral standard for producing telemetry: APIs and SDKs for your code, a wire protocol called OTLP, and the Collector, a pipeline process that receives, processes and exports telemetry to any backend. Instrument once with OTel and you can send the data to Prometheus, Tempo, Jaeger or a commercial vendor without touching application code.

The semantic conventions are OTel's agreed names for attributes, so that every library calls the same thing by the same name. The GenAI semantic conventions define names for model calls. As of December 2026 they are still marked Development, not Stable, and in mid-2026 they moved out of the main repository into a dedicated semantic-conventions-genai repository. Expect renames: gen_ai.system became gen_ai.provider.name, for example.

Attribute or metricMeaning
gen_ai.operation.namechat, embeddings, execute_tool, invoke_agent and others
gen_ai.provider.nameWho served it: openai, aws.bedrock and so on
gen_ai.request.model and gen_ai.response.modelModel asked for, and model that actually answered
gen_ai.usage.input_tokens and gen_ai.usage.output_tokensToken counts for the call
gen_ai.response.finish_reasonsWhy generation stopped
gen_ai.client.token.usageHistogram metric of tokens per call
gen_ai.client.operation.durationHistogram metric of call duration
gen_ai.server.time_to_first_tokenServer-side TTFT histogram

Span names follow the pattern operation then target, such as chat gpt-4o-mini or execute_tool search_docs. Prompt and completion content is opt-in by design and is not captured unless you enable it, which is the right default for privacy.

Tracing an agent run

An agent run is where traces earn their keep. One user request becomes a loop of model calls, tool calls, retrievals and retries, and only a trace shows the sequence, the timing and the token cost of each step. The conventions model this as a root invoke_agent span with chat and execute_tool children.

Reading that trace answers questions that metrics cannot. Half the latency is one slow ticketing API, not the model. Token use grows with every step because each chat call resends the growing conversation, which is why the last call is the most expensive. Put these attributes on every agent span so the questions stay answerable:

  • Step number and total steps, so you can alert on runs that exceed a step budget (a runaway loop).
  • Tool name, arguments hash and result size, never raw arguments containing user data.
  • Cumulative tokens and estimated cost for the run, set on the root span when it ends.
  • The user or tenant ID as a pseudonymous key, so you can slice cost and errors per customer.

Context propagation makes this work across services. The OTel SDK injects a traceparent header (the W3C Trace Context standard) into outgoing HTTP calls, so a tool running in another service attaches its spans to the same trace. Agent frameworks that run tools in background workers must pass that context explicitly, or the trace breaks into orphans.

GPU telemetry and what utilization really measures

If you run your own models, the GPU is the most expensive component you monitor. NVIDIA's DCGM (Data Center GPU Manager) reads hardware counters, and dcgm-exporter publishes them as Prometheus metrics, usually as a Kubernetes DaemonSet on every GPU node.

MetricWhat it measuresTrap
DCGM_FI_DEV_GPU_UTILShare of time at least one kernel was running100% can mean one tiny kernel kept the GPU busy
DCGM_FI_PROF_SM_ACTIVEShare of cycles streaming multiprocessors had work assignedA warp stalled on memory still counts as active
DCGM_FI_PROF_PIPE_TENSOR_ACTIVEShare of cycles the tensor cores were busyThe closest counter to "doing matrix math"
DCGM_FI_DEV_FB_USEDGPU memory in usevLLM preallocates memory, so it reads near full when idle
DCGM_FI_DEV_POWER_USAGEPower draw in wattsA good cheap proxy for real work
DCGM_FI_DEV_XID_ERRORSLast XID error code reported by the driverNonzero values need investigation; see the next chapter

The headline number that nvidia-smi calls utilization is a time-occupancy figure, not work done. It answers "was anything running?", not "how much of the chip was used?". A memory-bound decode loop can show 100% utilization while tensor-core activity sits at a few percent.

Reading a GPU that looks busy
GPU_UTIL            100 %   <- something was running all the time
SM_ACTIVE            42 %   <- less than half the SMs had work
PIPE_TENSOR_ACTIVE    9 %   <- tensor cores mostly idle
POWER_USAGE         310 W   of 700 W limit
FB_USED              74 GB  of 80 GB (preallocated KV cache)

That GPU is busy but inefficient. For an inference server the usual cause is small batches, so the fix is more concurrency per replica, not more replicas. Correlate GPU counters with serving metrics: if vllm:num_requests_waiting is zero and tensor activity is low, you are overprovisioned. If the queue is growing while KV cache use sits at 100%, you are memory-bound and need more cache capacity or shorter contexts.

Prometheus queries and dashboards

Prometheus scrapes or receives metrics and stores them as time series identified by a name and labels. You query it with PromQL. Histograms are stored as cumulative buckets with an le ("less than or equal") label, and histogram_quantile estimates percentiles from them.

Golden signals for an LLM service
# p95 time to first token over 5 minutes
histogram_quantile(0.95, sum by (le) (rate(vllm:time_to_first_token_seconds_bucket[5m])))
 
# Aggregate output tokens per second
sum(rate(vllm:generation_tokens_total[1m]))
 
# Error ratio
sum(rate(llm_requests_total{status="error"}[5m]))
  / sum(rate(llm_requests_total[5m]))
 
# Queue depth per replica
max by (pod) (vllm:num_requests_waiting)
 
# Tensor-core activity per GPU
avg by (gpu, Hostname) (DCGM_FI_PROF_PIPE_TENSOR_ACTIVE)

A good LLM dashboard reads top to bottom like a diagnosis: symptoms first, hardware last.

  1. Row 1: user experience

    p50, p95 and p99 TTFT, inter-token latency, error ratio, and refusal rate. These are the panels you alert on.

  2. Row 2: load and capacity

    Requests per second, output tokens per second, queue depth, KV cache use and running requests per replica.

  3. Row 3: tokens and cost

    Input, output and cached tokens per second, cache hit rate, and cost per hour broken down by model and by team.

  4. Row 4: hardware

    Tensor activity, SM activity, memory, power and XID errors per GPU. You look here only after rows 1 to 3 point at capacity.

Watch label cardinality. Every distinct combination of label values is a separate time series, so putting a user ID, prompt hash or full model path on a metric can create millions of series and take Prometheus down. User-level detail belongs on traces and logs; metrics get bounded labels like model, route, status and team.

Logging prompts without leaking them

Prompts and completions are the most useful debugging data you have and the most dangerous to store. They contain whatever users typed: names, health details, credentials pasted by accident, other people's data. A prompt log is a copy of user data, subject to the same retention, access and deletion duties as your primary database.

Log by default (risky)

  • Full prompt and completion on every request
  • Kept forever in a shared logging tool
  • Every engineer can search it
  • Deletion requests cannot be honoured

Log with intent (sound)

  • Metadata always: tokens, model, latency, finish reason
  • Content sampled, redacted, and stored separately
  • Short retention and role-based access
  • Keyed by pseudonymous ID so deletion works

Redact before the data leaves the process, not in the backend. The OTel Collector can drop or hash attributes with its attributes and transform processors, and a PII detector can mask emails, phone numbers and card numbers in the application. Keep content capture behind a flag you can enable per tenant or per incident.

Watching quality drift

A model can degrade without any error: a provider updates weights behind the same model name, a prompt template change shifts behaviour, or user traffic moves to topics your evals never covered. Quality drift is a sustained change in output quality or input distribution over time, and catching it needs signals beyond latency and errors.

  • Cheap proxies on every request: output length distribution, refusal rate, empty-response rate, JSON parse failure rate for structured outputs, and tool-call error rate.
  • User signals: thumbs down, regenerate clicks, conversation abandonment, escalations to a human.
  • Sampled judging: run an LLM judge or rubric from Evaluation infrastructure on 1 to 5% of production traffic and chart its score daily.
  • Input drift: track embedding-cluster or topic distribution of prompts and alert when a new cluster grows.

Alert on change, not on absolute values. A refusal rate of 3% may be normal for your product; a jump from 3% to 9% the day after a deploy is an incident.

Key terms

Span
One timed operation inside a trace, with a name, start and end time, attributes and a parent.
OTLP
The OpenTelemetry Protocol, the wire format for sending traces, metrics and logs to a Collector or backend.
Semantic conventions
OpenTelemetry's agreed attribute and metric names, so different libraries describe the same thing the same way.
TTFT
Time to first token: the delay from sending a request until the first output token arrives.
Inter-token latency
The average time between consecutive output tokens during decode, also called time per output token.
DCGM
NVIDIA Data Center GPU Manager, which reads GPU hardware counters; dcgm-exporter publishes them to Prometheus.
Cardinality
The number of distinct time series a metric produces, equal to the number of label value combinations.
Quality drift
A gradual change in output quality or input distribution that produces no errors on its own.
Lab

Instrument an LLM service with OpenTelemetry and build a golden-signals dashboard

Intermediate, 75 min

Goal: run a small streaming LLM API on your laptop, instrument it with OpenTelemetry traces and metrics, and build a Grafana dashboard showing TTFT, tokens per second, errors and cost.

You need: Docker Desktop or Docker Engine with Compose v2, about 4 GB of free RAM, and curl. Everything runs on CPU. The backend is grafana/otel-lgtm, a single development image bundling an OTel Collector, Prometheus, Tempo, Loki and Grafana.

  1. Create a project folder with three files. First the service, which streams from Ollama and records GenAI-style spans and metrics:
app.py
import json, os, time
import httpx
from fastapi import FastAPI, HTTPException
from fastapi.responses import StreamingResponse
from pydantic import BaseModel
from opentelemetry import trace, metrics
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk.metrics import MeterProvider
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
from opentelemetry.sdk.metrics.view import View, ExplicitBucketHistogramAggregation
from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter
 
resource = Resource.create({"service.name": os.getenv("OTEL_SERVICE_NAME", "llm-api")})
tp = TracerProvider(resource=resource)
tp.add_span_processor(BatchSpanProcessor(OTLPSpanExporter()))
trace.set_tracer_provider(tp)
buckets = ExplicitBucketHistogramAggregation([0.1, 0.25, 0.5, 1, 2, 4, 8, 16, 32])
mp = MeterProvider(
    resource=resource,
    metric_readers=[PeriodicExportingMetricReader(OTLPMetricExporter())],
    views=[View(instrument_name="llm.ttft", aggregation=buckets),
           View(instrument_name="llm.duration", aggregation=buckets)],
)
metrics.set_meter_provider(mp)
 
tracer = trace.get_tracer("llm-api")
meter = metrics.get_meter("llm-api")
ttft_h = meter.create_histogram("llm.ttft", unit="s")
dur_h = meter.create_histogram("llm.duration", unit="s")
tokens_c = meter.create_counter("llm.tokens")
requests_c = meter.create_counter("llm.requests")
cost_c = meter.create_counter("llm.cost_usd")
inflight = meter.create_up_down_counter("llm.inflight")
 
OLLAMA = os.getenv("OLLAMA_URL", "http://localhost:11434")
MODEL = os.getenv("MODEL", "qwen2.5:0.5b")
PRICE_IN, PRICE_OUT = 0.10e-6, 0.40e-6  # pretend USD per token, for the cost panel
app = FastAPI()
 
class ChatIn(BaseModel):
    prompt: str
    max_tokens: int = 64
 
@app.post("/chat")
async def chat(body: ChatIn):
    if len(body.prompt) > 4000:
        requests_c.add(1, {"status": "error", "reason": "too_long"})
        raise HTTPException(413, "prompt too long")
 
    async def stream():
        attrs = {"gen_ai.request.model": MODEL}
        start, first = time.perf_counter(), None
        inflight.add(1)
        with tracer.start_as_current_span(f"chat {MODEL}") as span:
            span.set_attribute("gen_ai.operation.name", "chat")
            span.set_attribute("gen_ai.provider.name", "ollama")
            span.set_attribute("gen_ai.request.model", MODEL)
            try:
                payload = {"model": MODEL, "stream": True,
                           "messages": [{"role": "user", "content": body.prompt}],
                           "options": {"num_predict": body.max_tokens}}
                async with httpx.AsyncClient(timeout=60) as client:
                    async with client.stream("POST", f"{OLLAMA}/api/chat", json=payload) as r:
                        r.raise_for_status()
                        async for line in r.aiter_lines():
                            if not line:
                                continue
                            chunk = json.loads(line)
                            text = chunk.get("message", {}).get("content", "")
                            if text and first is None:
                                first = time.perf_counter()
                                ttft_h.record(first - start, attrs)
                                span.add_event("first_token")
                            if text:
                                yield text
                            if chunk.get("done"):
                                tin = chunk.get("prompt_eval_count", 0)
                                tout = chunk.get("eval_count", 0)
                                span.set_attribute("gen_ai.usage.input_tokens", tin)
                                span.set_attribute("gen_ai.usage.output_tokens", tout)
                                span.set_attribute("gen_ai.response.finish_reasons",
                                                   [chunk.get("done_reason", "stop")])
                                tokens_c.add(tin, {**attrs, "type": "input"})
                                tokens_c.add(tout, {**attrs, "type": "output"})
                                cost_c.add(tin * PRICE_IN + tout * PRICE_OUT, attrs)
                requests_c.add(1, {**attrs, "status": "ok"})
            except Exception as e:
                span.record_exception(e)
                span.set_status(trace.Status(trace.StatusCode.ERROR))
                requests_c.add(1, {**attrs, "status": "error"})
                yield "\n[error]"
            finally:
                dur_h.record(time.perf_counter() - start, attrs)
                inflight.add(-1)
 
    return StreamingResponse(stream(), media_type="text/plain")
  1. Add the container definition and the Compose file:
Dockerfile
FROM python:3.12-slim
RUN pip install --no-cache-dir fastapi uvicorn httpx \
    opentelemetry-sdk opentelemetry-exporter-otlp-proto-http
COPY app.py /app/app.py
WORKDIR /app
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8000"]
compose.yaml
services:
  lgtm:
    image: grafana/otel-lgtm:latest
    ports: ["3000:3000", "4317:4317", "4318:4318"]
  ollama:
    image: ollama/ollama:latest
    volumes: ["ollama:/root/.ollama"]
  app:
    build: .
    ports: ["8000:8000"]
    environment:
      OLLAMA_URL: http://ollama:11434
      OTEL_SERVICE_NAME: llm-api
      OTEL_EXPORTER_OTLP_ENDPOINT: http://lgtm:4318
      OTEL_METRIC_EXPORT_INTERVAL: "5000"
    depends_on: [lgtm, ollama]
volumes:
  ollama: {}
  1. Start everything, pull a 0.5B model (about 400 MB) and send one request:
docker compose up -d --build
docker compose exec ollama ollama pull qwen2.5:0.5b
curl -N -X POST localhost:8000/chat -H 'content-type: application/json' \
  -d '{"prompt":"Explain a KV cache in one sentence."}'

You should see the answer stream in word by word. On a recent laptop CPU the first token arrives in well under a second.

  1. Generate steady load, including a few deliberate errors (oversize prompts):
seq 300 | xargs -P 4 -I{} curl -s -o /dev/null -X POST localhost:8000/chat \
  -H 'content-type: application/json' -d '{"prompt":"Give me fact number {} about GPUs."}'
python3 -c "print('{\"prompt\":\"' + 'x'*5000 + '\"}')" > big.json
for i in $(seq 10); do curl -s -o /dev/null -X POST localhost:8000/chat \
  -H 'content-type: application/json' -d @big.json; done
  1. Open Grafana at http://localhost:3000 (default login admin / admin). In Explore, pick the Prometheus data source and type llm_ to see how OTel names were translated: dots become underscores, the s unit adds _seconds, and counters gain _total. You should find llm_ttft_seconds_bucket, llm_tokens_total, llm_requests_total, llm_cost_usd_total and llm_inflight.

  2. Create a new dashboard with these panels (time series unless noted):

Dashboard panels
# p50 and p95 TTFT
histogram_quantile(0.50, sum by (le) (rate(llm_ttft_seconds_bucket[2m])))
histogram_quantile(0.95, sum by (le) (rate(llm_ttft_seconds_bucket[2m])))
 
# Output tokens per second
sum(rate(llm_tokens_total{type="output"}[1m]))
 
# Error ratio (stat panel, percent)
sum(rate(llm_requests_total{status="error"}[5m])) / sum(rate(llm_requests_total[5m]))
 
# Requests in flight
sum(llm_inflight)
 
# Cost per hour in pretend dollars
sum(rate(llm_cost_usd_total[5m])) * 3600
  1. In Explore, switch to the Tempo data source, search for service llm-api, and open a trace. Check the chat qwen2.5:0.5b span carries the token attributes and a first_token event.

Check your work: your dashboard shows a p95 TTFT line, a nonzero tokens-per-second line during the load run, an error ratio that rose when you sent the oversize prompts, and a Tempo trace whose span attributes match the token counts in the Ollama response. Rerun step 4 with -P 16 and watch TTFT climb while tokens per second flattens: you just found your laptop's saturation point.

Stretch: add a /agent endpoint that makes two model calls with a fake execute_tool span between them, nest all three under an invoke_agent span, and add a panel for average steps per agent run. Then add an OTel Collector attributes processor that hashes a user.id attribute before export.

Check yourself

A streaming chat endpoint shows average request duration rising from 4 s to 7 s after a prompt change, while TTFT and inter-token latency are unchanged. What is the most likely explanation?

A dashboard shows GPU utilization at 100% on every inference node, tensor-core activity at 8% and zero queued requests. What should you conclude?

An engineer adds the end-user ID as a label on the request-count metric to debug one customer. Why is this a problem?

Your team instruments agents with the OpenTelemetry GenAI conventions. Six months later several dashboard panels go empty after a library upgrade, with no errors. What is the most likely cause?

Recap

  • Treat the token as the unit of work: measure queue time, TTFT, inter-token latency, token counts, cache hits, errors, refusals and cost.
  • Record latency as histograms and alert on TTFT and inter-token latency, not total duration, for streaming endpoints.
  • OpenTelemetry's GenAI conventions give standard names for model, tool and agent spans, but they are still in Development, so pin the version.
  • GPU utilization measures time occupied, not work done; read tensor and SM activity, power and queue depth together.
  • Keep metric labels bounded, put per-user detail on traces, and log prompt content deliberately, redacted and with short retention.
  • Quality drift produces no errors, so watch proxies, user signals and sampled judge scores for changes after each deploy.

Go deeper