Pidoku

Observability for LLM Services

Module 23 Lesson 23.h 1h Difficulty 3/5

Prerequisites 22.j, 23.a


Before you start: words you need#

WordPlain meaning
MetricsNumbers aggregated over time (rates, histograms, gauges). Cheap, good for alerts, but they lose per-request detail.
Trace / spanA trace follows one request through every service; each step in it is a span with a start, an end and attributes.
Wide eventOne structured log record per request with every field you may later want to slice by.
CardinalityHow many distinct values a label has. Per-tenant or per-request labels on metrics explode storage.
OpenTelemetry (OTel)The open standard and libraries for emitting traces, metrics and logs in a common format.
Semantic conventionsAgreed names for attributes, such as gen_ai.usage.input_tokens, so tools can read each other’s data.
Tail samplingDeciding whether to keep a trace after the request finished, so slow and failed ones can always be kept.
RunbookThe written steps an on-call engineer follows when a given alert fires.

1. What is it?#

Observability is being able to answer new questions about a running system from the data it emits, without shipping new code. For an LLM service the questions are unusual: which tenant’s prompts got longer? why was this request slow: queue, prefill, or a stall? did the new model start rambling?

This lesson is the service owner’s view: what to emit, what to alert on, and how on-call uses it. The separate Observability learning materials teach the tools and the theory in depth: OTel and tracing (3.c), engine metrics (5.c), LLM tracing (5.d), and quality and evals (Observability 5.g). 22.j covers the metric catalogue and dashboards for performance work.

Facts checked on 13 November 2026.


2. Why does it matter?#

A standard application-monitoring setup gives you request rate, errors, latency percentiles, CPU, memory and cross-service traces. It does not give you:

✗ KV cache use              ← the real capacity limit
✗ running batch size        ← the real efficiency
✗ queue wait vs prefill     ← the two halves of TTFT
✗ prefix-cache hit rate
✗ preemptions
✗ tokens generated for clients who already left
✗ per-request tokens and cost
✗ output quality signals
✗ GPU health (Xid, ECC, throttling, 23.e)

Every item matters and none is free. Instrumenting them is a deliberate project.


3. Simple analogy#

A car dashboard shows speed and fuel: metrics. A flight data recorder keeps everything about one journey: a trace. The garage’s logbook of every service visit is what lets you see that one model of car always fails at 80,000 km: wide events. A taxi firm needs all three, plus a fourth gauge no car maker fits: did the passenger arrive where they wanted to go (quality)?


4. Tiny example: why slow traces must be kept on purpose#

100,000 requests; 669 broke the 800 ms TTFT objective and 298 failed. Two ways to keep about 2,000 traces:

                         traces     slow   failed
all requests             100000      669      298
head sampling 2%           2019       11        9
tail sampling              1948      669      298

Head sampling (decide at the start) keeps a random 2%, so it keeps 2% of the slow ones too: 11 traces to debug 669 problems. Tail sampling (decide at the end: keep every slow or failed trace, plus 1% of the rest) costs the same and keeps all of them.


5. Technical explanation#

Three signals, three jobs#

METRICS   aggregate, cheap, alertable      "is it healthy right now?"        (22.j, 19.c)
TRACES    per request, sampled             "why was THIS request slow?"
LOGS      per request, structured          "what is the distribution of X?"
          (wide events)                    → capacity plans, cost attribution, benchmarks

For LLM services, per-request logs do the heaviest lifting. The questions are about distributions (prompt lengths, per-tenant patterns, cost) and metrics cannot carry that cardinality. Keep tenant and request IDs out of metric labels; put them in the logs.

The engine metrics you already have, by name#

Most of the gaps in section 2 are closed by metrics the engine already exports. In vLLM v0.32.0 they live at /metrics, prefixed vllm:, labelled only with model_name and engine (the engine index). 19.c explains where in the code each one is produced; 22.j covers dashboards. The service owner needs to know which question each one answers:

Gap from section 2vLLM v0.32.0 metricHow to read it
KV cache usevllm:kv_cache_usage_percGauge, 0 to 1: blocks held by live requests
Running batch sizevllm:num_requests_runningGauge; compare with max_num_seqs
Queue wait vs prefillvllm:request_queue_time_seconds, vllm:request_prefill_time_secondsHistograms; together with frontend time they make up vllm:time_to_first_token_seconds
Why requests waitvllm:num_requests_waiting, vllm:num_requests_waiting_by_reasonLabel reason: capacity or deferred
Prefix-cache hit ratevllm:prefix_cache_hits_total ÷ vllm:prefix_cache_queries_totalCounters, in tokens; divide the rates
Preemptionsvllm:num_preemptions_totalCounter; watch its rate
Requests refused at the doorvllm:admission_rejections_totalCounter (new in v0.32.0, 19.c)
Clients who leftvllm:request_success_total{finished_reason="abort"}Counter by finished_reason: stop, length, abort, error, repetition
Decode smoothnessvllm:inter_token_latency_secondsHistogram

Three gaps have no engine metric: tokens generated after the client left, per-request tokens and cost by tenant, and output quality. Those come from your gateway’s per-request record (below) and the quality layer. GPU health comes from DCGM, not the engine (23.e).

Counters appear in a scrape, and must be written in PromQL, with the _total suffix that the Prometheus client appends, as the table shows. The PromQL for each of these (p95 queue wait, hit rate, abort share) and the alert rules built on them live in 22.j; do not rebuild them per service. Note also that vLLM’s latency histograms carry no prompt-length label, so an objective such as “p95 TTFT for prompts up to 2k tokens” has to be computed from the gateway’s per-request record (below), not from engine metrics.

Older guides use names that no longer exist, such as vllm:gpu_cache_usage_perc (now vllm:kv_cache_usage_perc). Check the names against the /metrics page of the version you run after every engine upgrade (23.g): a renamed metric makes an alert silently stop firing.

The per-request record#

JSON
{
  "ts": "2026-11-12T10:23:45.123Z",
  "event": "inference_complete",
  "request_id": "req_abc123",
  "trace_id": "4bf92f3577b34da6a3ce929d0e0e4736",
  "tenant": "team-search",
  "api_key_id": "key_xyz",
  "model": "chat-70b",
  "model_version": "v15-fp8-tp8-vllm0.32.0",
  "replica": "chat-70b-7f9d4-x2k1p",
  "region": "ap-south-1",

  "prompt_tokens": 1843,
  "cached_prompt_tokens": 1536,
  "output_tokens": 200,
  "reasoning_tokens": 0,
  "max_tokens_requested": 2048,

  "queue_wait_ms": 12.4,
  "prefill_ms": 187.3,
  "ttft_ms": 234.1,
  "itl_p95_ms": 38.2,
  "itl_max_ms": 112.0,
  "e2e_ms": 4512.0,
  "ttft_ok": true,
  "itl_ok": true,

  "batch_size_at_admission": 47,
  "kv_blocks_peak": 128,
  "kv_block_seconds": 578.0,
  "preemptions": 0,

  "finish_reason": "stop",
  "temperature": 0.7,
  "structured_output": null,
  "status": 200,
  "client_disconnected": false,
  "tokens_after_disconnect": 0
}

The fields most often missing, and what each enables:

  • cached_prompt_tokens: the real benefit of prefix caching, per tenant.
  • kv_block_seconds: the missing term in cost attribution (23.c) and quotas (23.j).
  • ttft_ok, itl_ok: goodput, computed per request (23.a).
  • tokens_after_disconnect: pure waste, per request.
  • model_version, replica: correlation with deployments (23.g) and per-replica imbalance.
  • reasoning_tokens: for reasoning models, where most of the cost hides.

Log token counts by default, not prompt or completion text. Content in logs is a privacy and breach-scope decision (23.i).

Tracing an LLM request#

One span per stage, with the system state the request met:

inference.request                      gen_ai.operation.name=chat, gen_ai.request.model,
│                                      gen_ai.provider.name, model_version, tenant
├── auth
├── rate_limit                         decision, which limit
├── tokenize                           gen_ai.usage.input_tokens
├── route                              replica, prefix-cache hit expected?
├── queue        ← the useful span     running batch size, KV cache use at admission
├── prefill                            cached tokens, new tokens
└── decode                             gen_ai.usage.output_tokens,
                                       gen_ai.response.finish_reasons, preemptions

The queue span carrying batch size and KV use turns a trace from decoration into diagnosis: open a slow request and you see the state of the system it met.

Engines emit some of this themselves. vLLM exports request spans over OTLP with --otlp-traces-endpoint (and --collect-detailed-traces for model-level timing), including time in queue, time to first token, and prefill and decode time. Your gateway adds the outer spans.

The GenAI semantic conventions: useful, not yet stable#

OpenTelemetry’s GenAI conventions name the attributes and metrics: gen_ai.provider.name (which replaced the older gen_ai.system), gen_ai.request.model, gen_ai.usage.input_tokens, gen_ai.usage.output_tokens, gen_ai.usage.cache_read.input_tokens, gen_ai.response.finish_reasons, and server metrics such as gen_ai.server.time_to_first_token and gen_ai.server.time_per_output_token.

Status on 13 November 2026: in June 2026 (semantic conventions v1.42.0) they moved to their own repository, open-telemetry/semantic-conventions-genai, and every one of its attributes, spans and metrics is still at “development” stability; none is stable. Engines lag behind too: vLLM’s spans still use older names such as gen_ai.usage.prompt_tokens and its own gen_ai.latency.* attributes. So:

  • use the conventions, so tools can read your data;
  • pin the version you follow, and expect renames;
  • map names in one place (the OTel Collector’s transform processor), not in every service.

Sampling#

Keep 100% of errors and of requests that broke the SLO, and a small share (0.1–1%) of the rest. That needs tail sampling (the OTel Collector’s tail-sampling processor, or your backend’s equivalent), because only the end of a request knows whether it was slow. Head sampling, as section 4 shows, keeps almost none of the traces you need.

Quality observability#

Generic tooling has no idea of quality. Build it in layers:

CHEAP, EVERY REQUEST        output length, finish-reason mix, structured-output validity,
                            refusal patterns (on a sample), n-gram repetition rate,
                            response language vs request language
SAMPLED (≈1%)               LLM-as-judge score on a rubric, safety classifier score
USER SIGNALS                regeneration rate (a strong negative signal), thumbs,
                            conversation abandonment, turns to resolution
DAILY                       the evaluation suite on sampled production prompts;
                            input drift (has the prompt mix changed?)

Regeneration rate is the best single user-side signal in most chat products: it needs no explicit feedback and moves quickly. The Observability materials’ quality lesson (Observability 5.g) goes deeper.

What to alert on#

PAGE (wake someone)     SLO burn rate high (23.a); error rate > 5%; a model or region down;
                        a security event
TICKET (working hours)  slow budget burn; cost per token drifting > 20%;
                        preemptions rising (rate of vllm:num_preemptions_total, 22.j);
                        quality signals out of range; ECC errors accumulating
DASHBOARD ONLY          normal variation, informational metrics
NEVER                   GPU utilization (22.d); raw queue length (use wait time);
                        single-request latency; anything that fires weekly with no action

The last line keeps alerting useful: an alert acknowledged every week without action should be deleted or turned into a ticket. This is the service owner’s policy; the rules themselves (PromQL and thresholds on the engine metrics) are written out in 22.j. Alerting on SLOs with burn rates is covered in 4.c of the Observability materials.

The runbook#

Each alert gets an entry with specific checks, not “investigate”:

ALERT: TTFTSLOBurn

MEANS   p95 TTFT for prompts ≤ 2k tokens (from gateway records) is burning the
        error budget at > 10×.

FIRST CHECKS, IN ORDER
  1. Service dashboard → is p95 queue wait up?
       yes → CAPACITY      no → PREFILL
  2. One replica or all? (per-replica heatmap)
       one → check its health; take it out of the pool
  3. Anything deployed in the last hour? (deploy annotations)
       yes → roll back first (23.g)

CAPACITY
  vllm:num_requests_running vs max_num_seqs; vllm:kv_cache_usage_perc;
  rate(vllm:num_preemptions_total[5m]); arrival rate vs yesterday
  arrival up      → scale; check autoscaler events and pending pods (23.d)
  arrival normal, batch low → routing problem

PREFILL
  prompt-length distribution shifted (vllm:request_prompt_tokens histogram)?
  prefix-cache hit rate dropped (routing change, template change)?
  GPU clocks throttled (DCGM)?

ESCALATE  unresolved after 20 minutes → page <team>
LINKS     dashboards, past incidents, the capacity plan

A runbook that names the dashboard and the next query is worth ten that say “investigate the cause”. Update it after every incident.


6. Under the hood#

The simulation behind section 4.

Go
// sampling.go — head-based vs tail-based trace sampling for slow and failed requests.
package main

import (
	"fmt"
	"math/rand"
)

type trace struct {
	ttftMs float64
	failed bool
}

const ttftSLO = 800.0

// keepTail decides AFTER the request finished, when its outcome is known.
func keepTail(t trace, r *rand.Rand) bool {
	return t.failed || t.ttftMs > ttftSLO || r.Float64() < 0.01
}

func main() {
	r := rand.New(rand.NewSource(7))
	var traces []trace
	for i := 0; i < 100000; i++ {
		t := trace{ttftMs: 200 + r.ExpFloat64()*120}
		if r.Float64() < 0.003 {
			t.failed = true
		}
		traces = append(traces, t)
	}

	type count struct{ kept, slow, failed int }
	var all, head, tail count
	for _, t := range traces {
		slow := t.ttftMs > ttftSLO
		add := func(c *count) {
			c.kept++
			if slow {
				c.slow++
			}
			if t.failed {
				c.failed++
			}
		}
		add(&all)
		if r.Float64() < 0.02 { // head: decided at the start, before anything is known
			add(&head)
		}
		if keepTail(t, r) {
			add(&tail)
		}
	}
	fmt.Printf("%-22s %8s %8s %8s\n", "", "traces", "slow", "failed")
	fmt.Printf("%-22s %8d %8d %8d\n", "all requests", all.kept, all.slow, all.failed)
	fmt.Printf("%-22s %8d %8d %8d\n", "head sampling 2%", head.kept, head.slow, head.failed)
	fmt.Printf("%-22s %8d %8d %8d\n", "tail sampling", tail.kept, tail.slow, tail.failed)
}

Output:

                         traces     slow   failed
all requests             100000      669      298
head sampling 2%           2019       11        9
tail sampling              1948      669      298

The cost of tail sampling is elsewhere: the collector must hold every span of a trace in memory until the trace ends, and an LLM request can stream for minutes. Size the decision wait to your longest normal request, and drop the rare runaway.


7. Performance implications#

  • Telemetry costs CPU, not GPU. Per-request logging and span export run on the host; on a busy engine with a Python frontend, keep it off the hot path (batch and export asynchronously).
  • Per-token events are too many. Record ITL as a per-request summary (p50, p95, max), not one event per token.
  • Metric cardinality is the usual bill. Per-tenant labels multiply series; per-request labels break the metrics store. Use logs for those.

8. Production implications#

  • Budget real engineering time. No product gives you the LLM-specific signals.
  • Structured per-request logs are the foundation. Keep 30+ days; they feed capacity (23.b), cost (23.c) and quotas (23.j).
  • Follow the GenAI conventions, pinned, and map names in the collector.
  • Instrument quality, not only performance.
  • Tail-sample traces.
  • Write runbooks with specific next steps, and update them after incidents.
  • Prune alerts every quarter.
  • Emit model_version and replica everywhere.

9. Common mistakes#

  1. Relying on generic monitoring. It misses everything LLM-specific.
  2. No quality signals. Regressions are found through support tickets.
  3. Head-based trace sampling. Keeps almost none of the slow requests.
  4. Metrics without per-request logs. No distributions, no capacity planning, no cost attribution.
  5. Per-tenant or per-request labels on metrics. The metrics store falls over.
  6. Alerting on GPU utilization.
  7. Runbooks that say “investigate”.
  8. No model_version. Regressions cannot be tied to deployments.
  9. Logging prompt text by default. A compliance problem waiting to happen.

10. Hands-on exercise#

  1. Run sampling.go. Lower the head-sampling rate to 0.5% and the tail rate for normal requests to 0.1%. How many slow traces does each keep now?
  2. Emit the per-request record of section 5 from a gateway or engine wrapper, including the “often missing” fields. Check each is populated correctly.
  3. Turn on vLLM’s OTLP tracing into a local collector. Map its attribute names to the current GenAI conventions with a transform processor.
  4. Record a week of cheap quality signals as baselines. Deploy a degraded model to a canary and see which moves first.
  5. List every alert on a service you know and when it last fired. Delete or downgrade those that fired without anyone acting.

11. Interview questions#

  1. What does generic monitoring miss for an LLM service?
  2. Which per-request fields would you log, and what does each enable?
  3. Which vLLM metrics tell you whether a TTFT problem is capacity or prefill, and which gaps have no engine metric at all?
  4. Why do logs matter more than metrics for capacity planning and cost?
  5. Why is tail sampling important here, and what does it cost?
  6. How would you observe output quality continuously?
  7. What is the state of the OpenTelemetry GenAI conventions, and how do you use them safely?
  8. What makes a good runbook entry? What would you never alert on?

12. Further reading#

Checked on 13 November 2026.

↑↓ navigate↵ openesc close

100% drag to pan · scroll or pinch to zoom · double-click to zoom in