11A.2 Metrics, Dashboards, SLOs and Alerting
11A.1 showed you how to see individual LLM requests — traces, spans, attributes, cost records. This lesson is about seeing the system: the aggregated numbers that tell you whether llm_service is healthy right now, whether it is getting worse, and whether it is about to spend its error budget. It covers the full metrics pipeline for an LLM service — which metrics actually matter (and which ones are traps), how to emit them from Python with Prometheus or OpenTelemetry, how to turn them into SLIs, SLOs and error budgets, how to build dashboards as code, and how to design alerts that page a human only when a human is needed. It builds llm_service/metrics.py, the metrics layer of the module's running project, on top of the hook points 03.11 already gives you.
What you'll learn
- The complete metrics catalogue for an LLM service: request rate, error rate by class, latency percentiles (TTFT, time-to-last-token, inter-token latency, end-to-end), token throughput, queue depth and concurrency, rate-limit hits and retries, token usage and cost per request/feature/tenant, cache hit rates, fallback rates, refusal and abstention rates, guardrail triggers, online quality scores, feedback rates and drift indicators
- How RED, USE and the Google golden signals adapt to LLM workloads — and why "error rate" alone misses the failures that cost the most money
- The Prometheus data model done right: counters, gauges and histograms; labels and the cardinality trap; bucket selection for latencies measured in seconds to minutes; exemplars that link a spike to the exact trace
llm_service/metrics.pyin full: a backend-agnostic metrics module wired into theprovider_agnostichooks, plus a/metricsendpoint for the FastAPI service — and the OpenTelemetry metrics path as the vendor-neutral alternative- SLIs, SLOs and error budgets for LLM features: what to measure, targets by tier, the error-budget policy, why quality SLOs need online evals, and multi-window multi-burn-rate alerting explained from first principles
- Dashboards as code: the template set every LLM service needs (health, cost, quality, RAG/agent internals, per-tenant), Grafana provisioning, and annotating deploys and model changes on charts
- Alert design: actionable symptom-based rules, silent-failure alerts ("zero retrieval hits", "everything abstained"), anomaly detection on cost with a working z-score detector, synthetic probes, routing, runbooks and alert fatigue
- Provider health monitoring: the official status pages and machine-readable APIs for all four providers, your own leading indicators (error rate, latency, rate-limit headroom, quota), and correlating incidents across providers
- Capacity and load: what load testing an LLM service actually measures (streaming connections, concurrency vs request rate, token throughput), a Locust reference script, capacity-planning arithmetic, tail latency and back-pressure
- Cost monitoring: budgets, threshold alerts, per-tenant caps, forecasting, and detecting cost-per-request anomalies before the invoice arrives
What you don't need
- API keys or a running Prometheus/Grafana stack. The metrics code runs against an in-memory backend and produces real output; the Prometheus exposition, alert rules, dashboards and load tests are reference material you can run later against your own stack.
- Deep Prometheus or SRE knowledge. Concepts are explained from first principles; links go deeper where useful.
- Tracing internals. 11A.1 owns traces, spans and the GenAI semantic conventions; this lesson consumes them (exemplars, trace IDs) and links back rather than re-teaching them.
- Evaluation methodology. Module 10A owns evals and judges; this lesson shows how their online scores become SLOs and dashboard panels.
Setup
The module's running project is llm_service, a FastAPI app built across Modules 11A to 11C. If you haven't created it yet:
uv init llm-service --bare --python 3.13 && cd llm-serviceAdd the packages this lesson uses (package names only, so you get the newest release):
# Metrics: the official Prometheus Python client
uv add prometheus-client
# Vendor-neutral metrics (optional path, Part 3.4 — same packages as 11A.1)
uv add opentelemetry-sdk opentelemetry-exporter-otlp-proto-http
# The service itself (the same fastapi[standard] form as 01B.7; the
# [standard] extra brings uvicorn and the fastapi CLI with it)
uv add "fastapi[standard]" pydantic
# Load testing (Part 8, optional — run in a separate env if you prefer)
uv add locustThe samples were written and checked against prometheus-client 0.26.0, opentelemetry-sdk and opentelemetry-exporter-otlp-proto-http 1.45.2, fastapi 0.162.0, pydantic 2.14.3 and locust 2.47.0, all as of November 2026. A plain install gives you the newest release of each, so a newer FastAPI or prometheus-client may print slightly different output or deprecation warnings; check the project's release notes if a sample fails to import.
This lesson's code samples import provider_agnostic (the package from 03.11) for the hook interface — copy that package into the project, or read the samples as the specification of what the hooks receive. Samples marked "run for real" use only the standard library and produce real output; samples that need prometheus_client, FastAPI or a provider are labelled illustrative.
What you must be able to do after this lesson#
- Choose the core metrics for an LLM service: request rate, error rate by class, TTFT and total latency percentiles, tokens and cost
- Pick the right Prometheus instrument (counter, gauge, histogram) and avoid user_id as a label
- Instrument a service with the metrics module and read the output from the in-memory backend
- Define an SLI, an SLO and an error budget for an LLM feature
- Explain burn rate and write a multi-window multi-burn-rate alert rule
- Decide whether an alert should page or only create a ticket, and add a silent-failure alert
- Use Little's Law to estimate the concurrency capacity of a service
Why this matters for an AI engineer#
Every row below is a production failure that metrics, SLOs or alerts exist to catch — and each one is invisible to the tools you used before LLMs:
| You'll hear... | You'll understand it after... |
|---|---|
| "Error rate is fine but the bill doubled." | 1.2 LLM-specific metrics |
| "The answers got worse but nothing is erroring." | 4.4 Quality SLOs, 6.3 Silent-failure alerts |
| "What does '99.9% available' even mean when the model can refuse?" | 4.1 SLIs and SLOs |
| "Page me only when I'm needed." | 4.6 Page vs ticket, 6.1 Alert design |
| "Our /metrics endpoint is melting Prometheus." | 1.5 Cardinality |
| "The p50 looks great — why do users complain?" | 2.3 Histograms and percentiles |
| "The provider is down — how do we know before users do?" | Part 7: provider health |
| "Can we handle 10× tomorrow's traffic?" | Part 8: capacity and load |
| "Alert fired, nobody knew what to do." | 6.6 Routing, runbooks and alert fatigue |
| "Why did the dashboard show green during the outage?" | 5.1 The dashboard set |
Part 1: The metrics that matter#
1.1 Why the classic list is not enough#
Classic web-service monitoring tracks the golden signals: latency, traffic, errors and saturation. Those are necessary for an LLM service but not sufficient, because an LLM service has three properties that break the usual assumptions:
- Errors are not the expensive failures. A request can return HTTP 200, finish cleanly, and still be a failure: a refusal the user didn't want, a truncated answer the user can't use, a wrong answer that poisons a downstream workflow, or a correct answer that cost 40× what it should have. 03.8, Part 10 catalogued 200s that aren't successes; metrics must classify outcomes, not just count status codes.
- Cost is a first-class signal. Every call has a metered price in tokens (03.7). A cost spike is often the first symptom of a regression — a prompt edit that broke prefix caching, a router change that sends easy traffic to the expensive model, a fallback storm that retries paid calls. Cost metrics belong on the same dashboard as latency.
- Quality is measurable but not binary. "Was the answer good?" is an evaluation question (Module 10A), but online proxies — judge scores on a sample, user feedback rates, abstention rates, citation coverage — are metrics you can alert on. A service can be 100% "up" and 0% useful.
1.2 The LLM-specific metrics#
The catalogue below is organised by question. Each row names the metric, what it is for, and where the number comes from. "Hook" means the provider_agnostic hook events from 03.11, Part 9 (attempt, after, error, abandoned); "service" means the FastAPI layer around it.
| Question | Metric(s) | Type | Source |
|---|---|---|---|
| Is anyone using it? | llm_requests_total{feature, outcome} — request rate per feature |
Counter | service |
| Is it failing? | llm_errors_total{model_key, error_class} — by the 03.8 taxonomy (transport, HTTP, 200-that-isn't-success, validation) |
Counter | hook error/after |
| Is it slow? | llm_call_duration_seconds{model_key, provider} histogram (per attempt); llm_ttft_seconds{model_key} histogram (streaming only); llm_request_duration_seconds{feature} at request level. Inter-token latency deserves its own histogram on high-throughput deployments (2.3) |
Histogram | hook + service stream layer |
| Is it expensive? | llm_tokens_total{model_key, kind} (uncached input / cached read / cache write / output — output INCLUDES reasoning; reasoning also has its own counter llm_reasoning_tokens_total so the kinds never double-count); llm_cost_usd_total{feature, model_key} |
Counter | hook after/error (usage + cost already computed by 03.11) |
| Is the provider throttling us? | llm_rate_limit_hits_total{model_key, provider}; llm_retries_total{model_key}; gauge llm_rate_limit_remaining{model_key, window} from response headers (aspirational — needs resp.raw headers; see 3.4) |
Counter + Gauge | hook attempt |
| Are fallbacks firing? | llm_fallbacks_total{from_model, to_model, reason} |
Counter | hook attempt (model change within a call) |
| Did the provider silently swap the model? | llm_served_model_total{model_key, served_model} — calls by resolved snapshot; a new label value is a silent provider update |
Counter | hook after (resolved_model) |
| Is the cache working? | llm_cache_lookups_total{cache, result} (hit/miss/error); hit-rate = hits/lookups |
Counter | 11B.3 cache layer |
| Is the model refusing? | llm_outcomes_total{model_key, outcome} — ok / refused / blocked / truncated / invalid / failed / abandoned (+ other catch-all) |
Counter | hook after (finish reason + 03.8's check_response) |
| Are guardrails firing? | llm_guardrail_events_total{guardrail, decision} |
Counter | service guardrail layer (Module 12 owns the guardrails; you own the counter) |
| Is quality drifting? | eval_score{feature, eval_name} gauge (sampled judge/metric scores); llm_feedback_total{feature, sentiment} |
Gauge + Counter | 10A.9 online eval pipeline |
| Is the queue backing up? | llm_queue_depth{queue} gauge; llm_inflight_requests{feature} gauge |
Gauge | service |
| Are we near provider limits? | Rate-limit headroom gauges from x-ratelimit-* headers (03.8, 9.3) |
Gauge | hook after |
Two rows deserve emphasis:
- Token and cost counters must be split by token kind. A single
tokens_totalhides the difference between a cached read (cheap) and an uncached input token (expensive). 03.7, 5.1 defined the canonical usage fields — mirror them exactly:uncached_input_tokens,cached_input_tokens,cache_write_tokens,output_tokens,reasoning_tokens. One subtlety:output_tokensincludes reasoning tokens, so reasoning gets its own counter (llm_reasoning_tokens_total) and is never akindofllm_tokens_total— otherwisesum by (kind)double-counts. - Outcome is not the same as error. "Failed" (exception, 5xx) and "invalid" (billed reply that failed validation, 03.11) and "abandoned" (consumer stopped reading a stream) and "refused" (a finish reason, not an exception) are four different operational stories with four different fixes. Your counters must keep them separate — Part 3's
metrics.pydoes.
1.3 RED, USE and the golden signals, adapted#
Three classic frameworks compress the catalogue into a checklist. Learn them once, then extend:
- RED (Rate, Errors, Duration) — for request-driven services: request rate, error rate, latency distribution. Every LLM endpoint gets these three, with "errors" replaced by the outcome taxonomy above.
- USE (Utilization, Saturation, Errors) — for resources: your worker pool, connection pool, queue, GPU (if self-hosting, 11C.6). For
llm_service: in-flight requests vs worker capacity, queue depth, upstream connection-pool saturation. - Golden signals (Google SRE) — latency, traffic, errors, saturation — the dashboard's four quadrants. For LLM services the honest version adds a fifth: cost (and a sixth you can't dashboard directly: quality — see 4.4).
The adaptation that matters: duration is a distribution, not a number. "Average latency 2s" hides a bimodal reality — 0.8s for easy queries and 45s for reasoning-heavy ones. You need percentiles (Part 2.3), and for streaming services you need two duration signals: time to first token (how fast the user sees something) and total duration (how long the whole answer takes). A service can have great TTFT and terrible total latency (fast start, endless reasoning), or the reverse.
1.4 Where each metric comes from#
The critical engineering decision is where in the code each number is born. Three sources, in order of preference:
- The provider-agnostic client's hooks (
attempt,after,error,abandoned) see every model call with usage, cost, latency, finish reason and error class already normalised across providers (03.11, Part 9). This is where call-level metrics come from — one hook implementation covers OpenAI, Anthropic, Gemini and OpenRouter. - The FastAPI service layer sees HTTP-level facts the client never does: which feature or endpoint was called, queue wait time, concurrent streams, auth/tenant identity (hashed), SSE connection lifecycle. Request-level metrics and gauges come from here.
- The retrieval/agent/tool layers emit domain metrics: retrieval hit counts, rerank scores, tool-call counts, guardrail triggers, citation coverage. These come from your pipeline code (the
docs_qa-style components of 07.11 and 08A.14), not the LLM client.
1.5 Labels and the cardinality trap#
A label is a key-value tag on a metric (feature="invoice_extract"). Every distinct combination of label values creates a separate time series — and each series costs memory in Prometheus, query time in Grafana, and cardinality in your alert rules. The trap for LLM services is unique: the natural things you want to slice by — user_id, request_id, session_id, prompt_hash, raw tenant_id — are unbounded. A million users means a million series per metric; a busy service melts its own monitoring within hours.
The discipline:
| Label | Cardinality | Verdict |
|---|---|---|
feature / endpoint |
~5–50 | ✅ safe — bounded by your code |
model_key, provider, api |
~10–100 | ✅ safe — bounded by your registry (03.11, Part 7) |
outcome, error_class, finish_reason |
~10–50 | ✅ safe — bounded enums |
tenant_tier (free/pro/enterprise) |
~3–10 | ✅ safe if bucketed |
tenant_id raw |
unbounded | ❌ never — use tenant_tier, or hash+sample |
user_id, request_id, session_id |
unbounded | ❌ never on metrics — they belong in traces/logs (11A.1), where cardinality doesn't apply |
prompt_version |
grows forever | ⚠️ keep as a bounded label (current + previous) or move to dashboard annotations (Part 5) |
A useful heuristic: if a label value is generated per-request by user behaviour, it doesn't belong on a metric. Metrics answer "how is the system doing"; traces and logs answer "what did this one request do". When you need per-user or per-request drill-down, that's what the trace_id exemplar (2.4) and the trace store are for.
Part 2: Metrics fundamentals#
2.1 The four instrument types#
Prometheus (and OTel metrics, which map onto it) gives you four instrument types. Choosing the right one is the difference between a metric you can alert on and a number that lies to you.
| Type | What it does | LLM example | Alertable? |
|---|---|---|---|
| Counter | Monotonically increasing total; rate() gives per-second rate | llm_requests_total, llm_tokens_total, llm_cost_usd_total |
✅ via rate()/increase() |
| Gauge | A value that goes up and down; current state | llm_inflight_requests, llm_queue_depth, eval_score, llm_rate_limit_remaining |
✅ directly |
| Histogram | Counts observations into buckets + sum + count | llm_call_duration_seconds, llm_ttft_seconds, llm_cost_per_request_usd |
✅ via histogram_quantile() |
| Summary | Client-side quantiles + sum + count | (rarely used — see below) | ⚠️ quantiles can't be aggregated across instances |
Two rules that prevent the most common metric bugs:
- Counters only go up. Never
.set()a counter; if a value can decrease (in-flight requests, queue depth, current error-budget remaining), it's a gauge. The classic bug: makingllm_requests_totala gauge "because restarts reset it" — restarts are handled by Prometheus'srate()semantics andincrease()extrapolation, not by breaking the type. - Prefer histograms over summaries. A summary computes quantiles inside your process; two replicas each compute their own p95 and you cannot combine them into a fleet p95. A histogram stores bucket counts, so Prometheus can aggregate buckets across all replicas before computing quantiles — the only correct way to get a service-wide p99. Summaries exist for niche cases; for service metrics, histogram is the default.
2.2 Labels, series and the exposition format#
A metric with labels is a family of time series. llm_requests_total{feature="ask", outcome="ok"} and llm_requests_total{feature="extract", outcome="ok"} are two independent counters. In the /metrics exposition format they look like:
# HELP llm_requests_total LLM requests completed, by feature and outcome.
# TYPE llm_requests_total counter
llm_requests_total{feature="ask",outcome="ok"} 10234
llm_requests_total{feature="extract",outcome="invalid"} 87
llm_requests_total{feature="summarize",outcome="failed"} 12Notes that matter in production:
- Names carry units and types. Prometheus convention: base units in the name (
_seconds,_bytes, there is no Prometheus base unit for money, so this module uses_usdand documents it; whichever you pick, be consistent), counters end in_total, histograms in_seconds/_usdetc. without a suffix beyond the unit. A metric namedllm_latencyis a trap: is it ms or s? Always suffix with the unit. _totalis normalised for you.prometheus_clientstrips a trailing_totalat registration and re-adds it at exposition, soCounter('llm_requests')andCounter('llm_requests_total')both exposellm_requests_total— there is no_total_totaloutcome. Keep the_totalsuffix in Python names anyway: it documents the instrument type at the call site.- Label values are strings. Numbers become strings (
"0.5"), booleans become"true"/"false". Keep enums lowercase snake_case.
2.3 Histograms and percentiles#
A histogram observes values and increments one bucket per observation, where each bucket counts observations ≤ le ("less than or equal"). It also keeps _sum and _count. From buckets, Prometheus computes quantiles with histogram_quantile(0.99, ...) — an estimate, accurate to within a bucket boundary.
Why this matters for LLM latency: the default Prometheus buckets (.005, .01, .025, .05, .075, .1, .25, .5, .75, 1.0, 2.5, 5.0, 7.5, 10.0) top out at 10 seconds — useless when a reasoning-model call legitimately takes 90s and a provider outage takes 300s. You must choose buckets that cover your real distribution. The shape to aim for: roughly log-spaced buckets spanning your fastest plausible call to your timeout ceiling.
Worked example — buckets for llm_call_duration_seconds on llm_service (illustrative tuning, verify against your own p50–p99 after a week of traffic):
# Seconds. Fast path: a small model, short answer ≈ 0.5–3s.
# Typical: frontier model, medium context ≈ 3–30s.
# Slow: reasoning models, long documents, retries ≈ 30–300s.
LLM_LATENCY_BUCKETS = [0.5, 1, 2.5, 5, 10, 20, 30, 45, 60, 90, 120, 180, 300]Two subtleties worth knowing:
- The last bucket is always
+Inf.prometheus_clientappends it automatically; every observation lands somewhere, so_countis always exact even when_sum-based averages aren't meaningful for percentiles. - Quantile estimates are only as good as your bucket edges. If all your traffic lands between 20s and 30s and you have no buckets there,
histogram_quantile(0.95)interpolates crudely. After a week of real traffic, checkhistogram_quantileoutput against raw_bucketcounts and adjust — this is a tuning loop, not a one-time decision.
For streaming calls you want two histograms, not one: llm_ttft_seconds (request sent → first content token) and llm_stream_total_seconds (request sent → last token). TTFT is what users feel as "is it alive"; total is what they feel as "how long until done". Inter-token latency (the gap between tokens during decode) is a third signal worth a histogram on high-throughput deployments — it reveals provider-side degradation that TTFT and total both miss (a stream that starts fast then crawls).
2.4 Exemplars: from a spike to a trace#
A histogram tells you that p99 spiked at 14:05. An exemplar — a trace ID attached to one specific observation — tells you which request caused it. prometheus_client supports exemplars on counters and histogram observations (since 0.12.0, October 2021), rendered only in the OpenMetrics exposition format:
histogram.observe(4.7, exemplar={"trace_id": "4bf92f35c8d9"})
counter.inc(exemplar={"trace_id": "4bf92f35c8d9"})For exemplars to be visible you need two things: (1) the /metrics endpoint must serve OpenMetrics (Prometheus does this by content negotiation automatically), and (2) Prometheus must run with --enable-feature=exemplar-storage (as of November 2026 — check your Prometheus version's flag name). Grafana then renders a dot on the bucket; clicking it jumps to the trace in your tracing backend (11A.1's platform, or Jaeger/Tempo). This is the single highest-leverage observability feature for LLM debugging: the bridge between "the metric says slow" and "here is the exact request that was slow, with its prompt version and token counts".
2.5 Naming conventions that survive contact with reality#
Borrow the Prometheus best-practice naming and add LLM-specific discipline:
- Prefix everything with the service:
llm_forllm_servicecall metrics,http_for HTTP-level,eval_for quality scores,rag_/agent_for pipeline internals. - Unit suffixes:
_seconds,_usd,_tokens,_bytes. Never_msor_dollars— pick one convention and hold it. - Counter suffix
_totalcomes free; don't double it. - Histogram names describe the thing measured, not the aggregation:
llm_call_duration_seconds, notllm_latency_histogram. - One metric, many label values — not many metrics for what is one concept.
llm_tokens_total{kind="output"}beatsllm_output_tokens_total+llm_input_tokens_totalwhen you also wantkind="reasoning"next month.
Part 3: Instrumenting in Python#
Deep-dive
3.1 prometheus_client: the core API#
The official Python client (prometheus-client, Apache-2.0/BSD-2-Clause licensed, version 0.26.0 as of November 2026) exposes four classes that map to the four types:
from prometheus_client import Counter, Gauge, Histogram
requests = Counter(
"llm_requests_total", "LLM requests by feature and outcome",
["feature", "outcome"],
)
inflight = Gauge(
"llm_inflight_requests", "Requests currently being processed",
["feature"],
)
duration = Histogram(
"llm_call_duration_seconds", "End-to-end LLM call latency",
["model_key", "provider"],
buckets=[0.5, 1, 2.5, 5, 10, 20, 30, 45, 60, 90, 120, 180, 300],
)Usage is deliberately simple:
requests.labels(feature="ask", outcome="ok").inc()
inflight.labels(feature="ask").inc() # on entry
inflight.labels(feature="ask").dec() # on exit (or .set(n))
duration.labels(model_key="luna", provider="openai").observe(4.7, exemplar={"trace_id": call_id})Three production details the docs assume you know:
- Registration is global by default. Every
Counter(...)registers into the defaultREGISTRYat construction. Creating the same metric twice (e.g. on module re-import in tests) raisesValueError: Duplicated timeseries. The fix is to construct metrics once at module level and import them, or passregistry=Nonein tests. - Labels are validated at
.labels()call time, not construction. A typo'd label name raisesValueErrorwhen you call.labels(bad_name=...). Keep label names in one constant set. - Thread-safety is built in.
inc/observeare safe under the GIL and across threads; the client uses locks internally. Your own aggregation logic (if any) needs its own lock.
3.2 llm_service/metrics.py: the full module#
The module's design constraint: everything must be unit-testable without Prometheus running. So metrics.py defines a backend protocol with two implementations — PrometheusBackend (real exposition) and MemoryBackend (stdlib dicts, for tests and the free local path). The Metrics facade is what hooks and routes call; it doesn't know which backend is live.
# llm_service/metrics.py
"""Metrics for llm_service.
One Metrics facade, two backends:
- PrometheusBackend: real counters/histograms/gauges (prometheus-client)
- MemoryBackend: dict-backed, stdlib only — tests, notebooks, the free path
Everything the hooks and routes record flows through Metrics methods, so the
metric NAMES and LABELS are defined exactly once, in _CATALOGUE.
"""
from __future__ import annotations
import contextvars
import threading
from dataclasses import dataclass
from typing import Any, Protocol
# ---------------------------------------------------------------------------
# Buckets — tuned for LLM latency (seconds), see 2.3
# ---------------------------------------------------------------------------
LLM_LATENCY_BUCKETS = [0.5, 1, 2.5, 5, 10, 20, 30, 45, 60, 90, 120, 180, 300]
TTFT_BUCKETS = [0.1, 0.25, 0.5, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
COST_BUCKETS_USD = [0.0001, 0.0005, 0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1.0, 5.0]
AGENT_STEP_BUCKETS = [1, 2, 3, 5, 8, 13, 21, 34, 55]
# Bounded label vocabularies. Anything not in these sets is coerced to "other"
# — a safety net so a bug can't mint unbounded series (see 1.5).
_OUTCOMES = {"ok", "invalid", "failed", "abandoned", "refused", "blocked",
"truncated", "other"}
_KINDS = {"uncached_input", "cached_input", "cache_write", "output"}
_ERROR_CLASSES = {"transport", "rate_limit", "timeout", "server_error",
"http_4xx", "invalid_output", "client_error", "other"}
# Attempt.error_type and LLMError class names are CamelCase ("RateLimited",
# "Timeout", ...) plus the sentinels "FinishFallback:<finish_reason>" and
# "Abandoned" — NEVER the snake_case classes above. Map explicitly: without
# this table every failure coerces to "other" and the error metrics say nothing.
_ERROR_CLASS = {
"ConnectionFailed": "transport",
"RateLimited": "rate_limit",
"Timeout": "timeout",
"Overloaded": "server_error",
"ServerError": "server_error",
"QuotaExceeded": "http_4xx",
"AuthFailed": "http_4xx",
"PermissionDenied": "http_4xx",
"BadRequest": "http_4xx",
"ContextTooLong": "http_4xx",
"Truncated": "invalid_output",
"Refused": "invalid_output",
"ContentBlocked": "invalid_output",
"ResponseFailed": "invalid_output",
"OutputInvalid": "invalid_output",
"UnsupportedFeature": "client_error",
"ConfigError": "client_error",
"HookError": "client_error",
}
def _coerce(value: str | None, allowed: set[str]) -> str:
return value if value in allowed else "other"
def error_class_for(error_type: str | None) -> str:
"""Map an Attempt.error_type / LLMError class name onto the bounded
error_class vocabulary. "FinishFallback:*" is a billed reply we discarded
for the next model — invalid_output. "Abandoned" and anything unmapped
land on "other"."""
if not error_type:
return "other"
if error_type.startswith("FinishFallback:"):
return "invalid_output"
return _ERROR_CLASS.get(error_type, "other")
# Carries the last call-level business outcome up to the request middleware,
# so llm_requests_total{outcome} sees refused/blocked/truncated - not just
# ok/failed (the SLO-1 good/bad split in 4.2 depends on it).
#
# Why a shared "box" instead of ContextVar.set() inside the hook: FastAPI's
# @app.middleware("http") is Starlette's BaseHTTPMiddleware, which runs the
# endpoint in a separate task, and Starlette documents that "changes to
# contextvars.ContextVars [don't propagate] upwards" - a value SET downstream
# is invisible to the middleware. So the middleware SETS the variable once,
# before call_next, to a mutable dict; the endpoint's context copy holds a
# reference to the SAME dict, and hooks MUTATE it. Mutation is visible on both
# sides, including inside asyncio.gather/create_task (they copy the context,
# not the dict).
_request_outcome: contextvars.ContextVar[dict[str, str | None] | None] = (
contextvars.ContextVar("llm_service_request_outcome", default=None))
# ---------------------------------------------------------------------------
# Backend protocol
# ---------------------------------------------------------------------------
class Backend(Protocol):
def inc(self, name: str, labels: dict[str, str], amount: float = 1.0) -> None: ...
def observe(self, name: str, labels: dict[str, str], value: float,
exemplar: dict[str, str] | None = None,
buckets: list[float] | None = None) -> None: ...
def set_gauge(self, name: str, labels: dict[str, str], value: float) -> None: ...
def add_gauge(self, name: str, labels: dict[str, str], delta: float) -> None: ...
class MemoryBackend:
"""Stdlib-only backend: counters, histograms-as-lists, gauges in dicts.
Not for production — for tests and the free local path. `snapshot()` gives
you the same numbers Prometheus would compute, so assertions stay honest.
"""
def __init__(self) -> None:
self._lock = threading.Lock()
self.counters: dict[tuple[str, tuple], float] = {}
self.gauges: dict[tuple[str, tuple], float] = {}
self.histograms: dict[tuple[str, tuple], list[float]] = {}
@staticmethod
def _key(name: str, labels: dict[str, str]) -> tuple:
return (name, tuple(sorted(labels.items())))
def inc(self, name: str, labels: dict[str, str], amount: float = 1.0) -> None:
with self._lock:
k = self._key(name, labels)
self.counters[k] = self.counters.get(k, 0.0) + amount
def observe(self, name: str, labels: dict[str, str], value: float,
exemplar: dict[str, str] | None = None,
buckets: list[float] | None = None) -> None:
# buckets are a Prometheus concern — we keep raw values, so any
# percentile is computable later regardless of bucket choice.
with self._lock:
k = self._key(name, labels)
self.histograms.setdefault(k, []).append(value)
def set_gauge(self, name: str, labels: dict[str, str], value: float) -> None:
with self._lock:
self.gauges[self._key(name, labels)] = value
def add_gauge(self, name: str, labels: dict[str, str], delta: float) -> None:
with self._lock:
k = self._key(name, labels)
self.gauges[k] = self.gauges.get(k, 0.0) + delta
@staticmethod
def _fmt_labels(lbls: tuple) -> str:
"""tuple(sorted(labels.items())) -> "k=v,k=v". Tuples can't be JSON
object keys, so snapshot() renders them Prometheus-style instead."""
return ",".join(f"{k}={v}" for k, v in lbls)
def snapshot(self) -> dict[str, Any]:
"""Counter totals, gauge values, and histogram count/sum/min/max/quantiles."""
import statistics
out: dict[str, Any] = {"counters": {}, "gauges": {}, "histograms": {}}
with self._lock:
for (name, lbls), v in self.counters.items():
out["counters"].setdefault(name, {})[self._fmt_labels(lbls)] = v
for (name, lbls), v in self.gauges.items():
out["gauges"].setdefault(name, {})[self._fmt_labels(lbls)] = v
for (name, lbls), vals in self.histograms.items():
s = sorted(vals)
out["histograms"].setdefault(name, {})[self._fmt_labels(lbls)] = {
"count": len(s), "sum": sum(s),
"min": s[0], "max": s[-1],
"p50": statistics.median(s),
"p95": s[min(len(s) - 1, int(0.95 * len(s)))],
"p99": s[min(len(s) - 1, int(0.99 * len(s)))],
}
return outThe PrometheusBackend is thinner — it owns the actual prometheus_client objects and translates the same calls:
# llm_service/metrics_prometheus.py
"""Prometheus backend for llm_service.metrics. Construct once at startup."""
import threading
from prometheus_client import Counter, Gauge, Histogram
from .metrics import (
COST_BUCKETS_USD, LLM_LATENCY_BUCKETS, TTFT_BUCKETS, Backend,
)
class PrometheusBackend:
def __init__(self) -> None:
# Counters: name -> Counter (labels declared per metric below)
self._counters: dict[str, Counter] = {}
self._gauges: dict[str, Gauge] = {}
self._histograms: dict[str, Histogram] = {}
self._lock = threading.Lock()
# -- registration ------------------------------------------------------
def _counter(self, name: str, help_text: str, labels: tuple[str, ...]) -> Counter:
with self._lock:
if name not in self._counters:
self._counters[name] = Counter(name, help_text, list(labels))
return self._counters[name]
def _gauge(self, name: str, help_text: str, labels: tuple[str, ...]) -> Gauge:
with self._lock:
if name not in self._gauges:
self._gauges[name] = Gauge(name, help_text, list(labels))
return self._gauges[name]
def _histogram(self, name: str, help_text: str, labels: tuple[str, ...],
buckets: list[float]) -> Histogram:
with self._lock:
if name not in self._histograms:
self._histograms[name] = Histogram(name, help_text, list(labels), buckets=buckets)
return self._histograms[name]
# -- backend protocol ---------------------------------------------------
def inc(self, name: str, labels: dict[str, str], amount: float = 1.0) -> None:
c = self._counter(name, "llm_service counter", tuple(sorted(labels)))
c.labels(**labels).inc(amount)
def observe(self, name: str, labels: dict[str, str], value: float,
exemplar: dict[str, str] | None = None,
buckets: list[float] | None = None) -> None:
# `buckets` comes from the metric's _MetricSpec via Metrics.observe —
# a cost histogram and a latency histogram MUST NOT share buckets.
h = self._histogram(name, "llm_service histogram", tuple(sorted(labels)),
buckets if buckets is not None else LLM_LATENCY_BUCKETS)
h.labels(**labels).observe(value, exemplar=exemplar)
def set_gauge(self, name: str, labels: dict[str, str], value: float) -> None:
g = self._gauge(name, "llm_service gauge", tuple(sorted(labels)))
g.labels(**labels).set(value)
def add_gauge(self, name: str, labels: dict[str, str], delta: float) -> None:
g = self._gauge(name, "llm_service gauge", tuple(sorted(labels)))
g.labels(**labels).inc(delta)Now the facade — this is the file hooks actually call:
# llm_service/metrics.py (continued)
@dataclass
class _MetricSpec:
kind: str # "counter" | "gauge" | "histogram"
help: str
labels: tuple[str, ...]
buckets: list[float] | None = None
# The catalogue: every metric llm_service emits, declared once.
_CATALOGUE: dict[str, _MetricSpec] = {
# -- request-level (service layer) -------------------------------------
"llm_requests_total": _MetricSpec("counter", "Requests by feature and outcome",
("feature", "outcome")),
"llm_inflight_requests": _MetricSpec("gauge", "Requests in flight",
("feature",)),
"llm_queue_depth": _MetricSpec("gauge", "Queued requests waiting for a worker",
("queue",)),
"llm_request_duration_seconds": _MetricSpec(
"histogram", "End-to-end request latency (queue + call + stream)",
("feature",), LLM_LATENCY_BUCKETS),
# -- call-level (client hooks) ------------------------------------------
"llm_attempts_total": _MetricSpec("counter", "Provider attempts by result",
("model_key", "provider", "result")),
"llm_call_duration_seconds": _MetricSpec(
"histogram", "Per-attempt latency (every try, incl. retries/fallbacks)",
("model_key", "provider"), LLM_LATENCY_BUCKETS),
"llm_ttft_seconds": _MetricSpec(
"histogram", "Time to first token (streaming calls)",
("model_key",), TTFT_BUCKETS),
"llm_tokens_total": _MetricSpec("counter", "Tokens by kind",
("model_key", "kind")),
"llm_reasoning_tokens_total": _MetricSpec(
"counter", "Reasoning tokens — a SUBSET of output_tokens; never sum "
"with llm_tokens_total or totals double-count",
("model_key",)),
"llm_served_model_total": _MetricSpec(
"counter", "Calls by served (resolved) model — provider snapshot drift",
("model_key", "served_model")),
"llm_cost_usd_total": _MetricSpec("counter", "Cost in USD",
("feature", "model_key")),
"llm_cost_per_request_usd": _MetricSpec(
"histogram", "Cost distribution per call",
("model_key",), COST_BUCKETS_USD),
"llm_errors_total": _MetricSpec("counter", "Errors by class",
("model_key", "error_class")),
"llm_fallbacks_total": _MetricSpec("counter", "Fallback events",
("from_model", "to_model", "reason")),
"llm_outcomes_total": _MetricSpec("counter", "Call outcomes",
("model_key", "outcome")),
"llm_rate_limit_hits_total": _MetricSpec("counter", "429s received",
("model_key", "provider")),
"llm_retries_total": _MetricSpec("counter", "Retry attempts",
("model_key",)),
"llm_rate_limit_remaining": _MetricSpec("gauge", "Provider-reported remaining quota",
("model_key", "window")),
# -- pipeline/domain (RAG, agents, guardrails, evals) --------------------
# These are emitted by pipeline code (retrieval stage, agent loop,
# guardrails), NOT by the client hooks — same catalogue, same discipline.
"rag_retrieval_hits_total": _MetricSpec(
"counter", "Retrieved chunks by feature and backend — incremented by "
"the hit count per query; a flat zero while requests flow "
"means retrieval is returning empty context (6.3)",
("feature", "backend")),
"llm_cache_lookups_total": _MetricSpec("counter", "Cache lookups",
("cache", "result")),
"llm_guardrail_events_total": _MetricSpec("counter", "Guardrail triggers",
("guardrail", "decision")),
"llm_tool_calls_total": _MetricSpec("counter", "Tool calls by tool and result",
("tool", "result")),
"llm_agent_steps": _MetricSpec(
"histogram", "Agent loop steps per run", ("feature",), AGENT_STEP_BUCKETS),
"eval_score": _MetricSpec("gauge", "Online eval score — normalise to 0-1 "
"before recording",
("feature", "eval_name",)),
"llm_feedback_total": _MetricSpec("counter", "User feedback",
("feature", "sentiment")),
}The Metrics class wraps a backend, enforces the catalogue, coerces labels, and exposes typed methods:
# llm_service/metrics.py (continued)
class Metrics:
"""The single entry point for all llm_service metrics.
Usage:
metrics = Metrics(backend) # PrometheusBackend() or MemoryBackend()
metrics.record_request_start("ask") # inflight+1
metrics.record_call(resp, ctx) # tokens, cost, duration, outcome
metrics.record_error(err, ctx) # error class counter
"""
def __init__(self, backend: Backend) -> None:
self._b = backend
# served_model values seen per model_key — bounded so provider snapshot
# rotation can't mint unbounded series (see _served_label).
self._served_lock = threading.Lock()
self._served_seen: dict[str, set[str]] = {}
# -- low-level (catalogue-checked) --------------------------------------
def _check(self, name: str, labels: dict[str, str]) -> _MetricSpec:
spec = _CATALOGUE.get(name)
if spec is None:
raise KeyError(f"unknown metric {name!r} — add it to _CATALOGUE")
extra = set(labels) - set(spec.labels)
missing = set(spec.labels) - set(labels)
if extra or missing:
raise ValueError(f"{name}: label mismatch extra={extra} missing={missing}")
return spec
def inc(self, name: str, **labels: str) -> None:
self._check(name, labels)
self._b.inc(name, labels)
def observe(self, name: str, value: float, *,
exemplar: dict[str, str] | None = None, **labels: str) -> None:
spec = self._check(name, labels)
self._b.observe(name, labels, value, exemplar, spec.buckets)
def set_gauge(self, name: str, value: float, **labels: str) -> None:
self._check(name, labels)
self._b.set_gauge(name, labels, value)
def add_gauge(self, name: str, delta: float, **labels: str) -> None:
self._check(name, labels)
self._b.add_gauge(name, labels, delta)
# -- high-level: what hooks and routes actually call ---------------------
def record_request_start(self, feature: str) -> None:
self.add_gauge("llm_inflight_requests", 1.0, feature=feature)
def record_request_end(self, feature: str, outcome: str,
duration_s: float, trace_id: str | None = None) -> None:
self.add_gauge("llm_inflight_requests", -1.0, feature=feature)
self.inc("llm_requests_total", feature=feature,
outcome=_coerce(outcome, _OUTCOMES))
self.observe("llm_request_duration_seconds", duration_s, feature=feature,
exemplar={"trace_id": trace_id} if trace_id else None)
def begin_request_outcome(self) -> dict[str, str | None]:
"""Middleware: open the per-request box BEFORE call_next and keep the
returned dict; read box["outcome"] when the request ends."""
box: dict[str, str | None] = {"outcome": None}
_request_outcome.set(box)
return box
def note_request_outcome(self, outcome: str) -> None:
"""Stash a call-level business outcome for the enclosing HTTP request.
ServiceMetricsHook calls this from after/error/abandoned. Last write
wins: the request takes the outcome of its LAST call event - for a
sequential pipeline that is the call that produced the answer the user
got; for concurrent fan-out it is simply whichever finished last, so
derive the request outcome at the endpoint if that matters. Outside a
request (a script, a test) there is no box and this is a no-op.
"""
box = _request_outcome.get()
if box is not None:
box["outcome"] = _coerce(outcome, _OUTCOMES)
def record_attempt(self, *, model_key: str, provider: str, ok: bool,
error_type: str | None, latency_ms: float,
trace_id: str | None = None) -> None:
# error_type is a CamelCase class name / "FinishFallback:*" / "Abandoned"
# — error_class_for maps it onto the bounded vocabulary, so a real
# "RateLimited" lands on result="rate_limit", not "other".
result = "ok" if ok else error_class_for(error_type)
self.inc("llm_attempts_total", model_key=model_key, provider=provider,
result=result)
self.observe("llm_call_duration_seconds", latency_ms / 1000.0,
model_key=model_key, provider=provider,
exemplar={"trace_id": trace_id} if trace_id else None)
_SERVED_MODEL_CAP = 32 # distinct served_model values kept per model_key
def _served_label(self, model_key: str, served: str) -> str:
"""Bound the served_model label: providers rotate dated snapshots, so
the value set grows slowly forever — cap it and bucket the tail."""
with self._served_lock:
seen = self._served_seen.setdefault(model_key, set())
if served in seen:
return served
if len(seen) < self._SERVED_MODEL_CAP:
seen.add(served)
return served
return "other"
def record_call(self, *, feature: str, model_key: str,
outcome: str, usage: Any, cost_usd: float | None,
served_model: str | None = None,
trace_id: str | None = None) -> None:
"""One completed call: outcome, tokens, cost, served model."""
self.inc("llm_outcomes_total", model_key=model_key,
outcome=_coerce(outcome, _OUTCOMES))
if served_model:
self.inc("llm_served_model_total", model_key=model_key,
served_model=self._served_label(model_key, served_model))
if usage is not None:
for kind, val in (
("uncached_input", usage.uncached_input_tokens),
("cached_input", usage.cached_input_tokens),
("cache_write", sum(getattr(usage, "cache_write_tokens", {}).values())),
("output", usage.output_tokens),
):
if val:
self._b.inc("llm_tokens_total",
{"model_key": model_key,
"kind": _coerce(kind, _KINDS)}, float(val))
# reasoning_tokens is a SUBSET of output_tokens (03.11 Usage) —
# its own counter, never a kind of llm_tokens_total.
reasoning = getattr(usage, "reasoning_tokens", 0) or 0
if reasoning:
self._b.inc("llm_reasoning_tokens_total",
{"model_key": model_key}, float(reasoning))
if cost_usd is not None:
self._b.inc("llm_cost_usd_total",
{"feature": feature, "model_key": model_key}, cost_usd)
self.observe("llm_cost_per_request_usd", cost_usd, model_key=model_key,
exemplar={"trace_id": trace_id} if trace_id else None)
def record_error(self, *, model_key: str, error_class: str) -> None:
self.inc("llm_errors_total", model_key=model_key,
error_class=_coerce(error_class_for(error_class), _ERROR_CLASSES))
def exposition(self) -> tuple[str, str]:
"""(body, media_type) for GET /metrics.
MemoryBackend -> a JSON debug dump (stdlib only; prometheus_client is
never imported on this path). PrometheusBackend -> the real text
exposition."""
if isinstance(self._b, MemoryBackend):
import json
return json.dumps(self._b.snapshot(), indent=2), "application/json"
from prometheus_client import CONTENT_TYPE_LATEST, generate_latest
return generate_latest().decode(), CONTENT_TYPE_LATEST3.3 Wiring it into the hooks#
Metrics is backend-agnostic; the glue to provider_agnostic is a Hook implementation — the production replacement for 03.11's in-memory MetricsHook (which literally says "Swap the body for Prometheus, StatsD or OpenTelemetry (Module 11)", now Module 11A):
# llm_service/metrics_hook.py
"""Hook that feeds llm_service.metrics from provider_agnostic call events.
Drop-in replacement for provider_agnostic.hooks.MetricsHook. List it AFTER
OTelHook so exemplars can carry trace context; observer order otherwise
doesn't matter — the client contains observer failures (03.11, Part 9).
"""
from __future__ import annotations
import threading
# Attempt lives in provider_agnostic.types but is not re-exported by the
# package __init__ (as of 03.11) — import it from the submodule.
from provider_agnostic import CallContext, Hook, LLMError, Request, Response
from provider_agnostic.types import Attempt
from .metrics import Metrics, error_class_for
# FinishReason.value -> llm_outcomes_total{outcome}. The client's canonical
# enum is stop / length / context_full / tool_calls / content_filter /
# refusal / paused / error / other (03.11 types.py) — map every member on
# purpose; a value that isn't here silently becomes "other".
_FINISH_OUTCOME = {
"stop": "ok",
"tool_calls": "ok", # the call succeeded; running the tools is the app's next step
"paused": "ok", # Anthropic pause_turn: billed and intentional — continue with another call
"length": "truncated",
"context_full": "truncated",
"content_filter": "blocked",
"refusal": "refused",
"error": "failed", # the provider reported failure inside a 200
# "other" falls through to the "other" outcome via _coerce
}
def _fallback_reason(error_type: str | None) -> str:
"""Why the previous model was abandoned: the finish reason for a discarded
billed reply ("FinishFallback:<reason>"), else the mapped error class."""
if error_type and error_type.startswith("FinishFallback:"):
return "finish_" + error_type.split(":", 1)[1]
return error_class_for(error_type)
class ServiceMetricsHook(Hook):
fail_closed = False # observer: a metrics bug must never break a call
def __init__(self, metrics: Metrics, *, feature_of: dict[str, str] | None = None) -> None:
self.m = metrics
# alias -> feature, a FALLBACK for callers that don't tag requests.
# Feature is a request-level fact: it arrives in Request.metadata,
# which the client validates, scrubs and copies to ctx.tags — several
# endpoints can share one alias, so tags win over this map.
self._feature_of = feature_of or {}
# call_id -> (model_key, provider, error_type) of the last attempt,
# for fallback detection. Attempt.n resets per model, so a changed
# (model_key, provider) within one call_id IS a fallback.
self._last_attempt: dict[str, tuple[str, str, str | None]] = {}
self._lock = threading.Lock()
def _feature(self, ctx: CallContext) -> str:
return ctx.tags.get("feature") or self._feature_of.get(ctx.alias, "unknown")
def _trace_id(self, ctx: CallContext) -> str | None:
# The OTelHook stores spans by call_id; a real impl would pull
# trace_id from the active span. Placeholder: use call_id as the
# exemplar key until OTel context propagation is wired (11A.1).
return ctx.call_id
def _forget(self, ctx: CallContext) -> None:
with self._lock:
self._last_attempt.pop(ctx.call_id, None)
def attempt(self, ctx: CallContext, attempt: Attempt) -> None:
self.m.record_attempt(
model_key=attempt.model_key, provider=attempt.provider,
ok=attempt.ok, error_type=attempt.error_type,
latency_ms=attempt.latency_ms, trace_id=self._trace_id(ctx),
)
if attempt.n > 1:
self.m.inc("llm_retries_total", model_key=attempt.model_key)
if error_class_for(attempt.error_type) == "rate_limit":
self.m.inc("llm_rate_limit_hits_total",
model_key=attempt.model_key, provider=attempt.provider)
with self._lock:
prev = self._last_attempt.get(ctx.call_id)
self._last_attempt[ctx.call_id] = (
attempt.model_key, attempt.provider, attempt.error_type)
if prev is not None and prev[:2] != (attempt.model_key, attempt.provider):
self.m.inc("llm_fallbacks_total",
from_model=prev[0], to_model=attempt.model_key,
reason=_fallback_reason(prev[2]))
def after(self, ctx: CallContext, req: Request, resp: Response) -> Response:
outcome = _FINISH_OUTCOME.get(resp.finish_reason.value, "other")
self.m.record_call(
feature=self._feature(ctx), model_key=resp.model_key,
outcome=outcome, usage=resp.usage,
cost_usd=resp.cost.usd if resp.cost else None,
served_model=resp.resolved_model, trace_id=self._trace_id(ctx),
)
# Hand the business outcome to the request middleware — this is how
# refused/blocked/truncated reach llm_requests_total (SLO-1, 4.2).
self.m.note_request_outcome(outcome)
self._forget(ctx)
return resp
def error(self, ctx: CallContext, req: Request, err: LLMError) -> None:
self.m.record_error(
model_key=err.attempts[-1].model_key if err.attempts else "unknown",
error_class=type(err).__name__,
)
# A billed-but-rejected reply still cost money: record its usage.
paid = err.response or err.partial
if paid is not None:
self.m.record_call(
feature=self._feature(ctx), model_key=paid.model_key,
outcome="invalid", usage=paid.usage,
cost_usd=paid.cost.usd if paid.cost else None,
served_model=paid.resolved_model, trace_id=self._trace_id(ctx),
)
# The call failed after retries/fallbacks — the request inherits
# "failed" unless a later call event overwrites it.
self.m.note_request_outcome("failed")
self._forget(ctx)
def abandoned(self, ctx: CallContext, req: Request, partial: Response) -> None:
self.m.record_call(
feature=self._feature(ctx), model_key=partial.model_key,
outcome="abandoned", usage=partial.usage,
cost_usd=partial.cost.usd if partial.cost else None,
served_model=partial.resolved_model, trace_id=self._trace_id(ctx),
)
self.m.note_request_outcome("abandoned")
self._forget(ctx)3.4 Wiring the service: requests, streams and /metrics#
The hooks cover per-call truth. The FastAPI layer owns per-request truth (1.4): which feature was hit, how long the whole request took, how many are in flight, how deep the queue is. A middleware is the honest place for it — it sees every path, including the ones that raise:
# llm_service/main.py (excerpt — the metrics wiring; 11C.1 builds the app in create_app(),
# so there these lines go inside it, with @app.middleware on the app it returns)
import time
from fastapi import FastAPI, Request
from fastapi.responses import PlainTextResponse, StreamingResponse
from provider_agnostic import LLMClient
from provider_agnostic.types import Done, ReasoningDelta, TextDelta
from .metrics import Metrics, MemoryBackend # or PrometheusBackend in prod
from .metrics_hook import ServiceMetricsHook
app = FastAPI()
# In production: Metrics(PrometheusBackend()); locally/tests: Metrics(MemoryBackend())
metrics = Metrics(MemoryBackend()) # swap for PrometheusBackend() when deployed
# ... wire metrics into the provider_agnostic client hooks ...
# client = LLMClient(registry, hooks=[ServiceMetricsHook(metrics), ...])
def feature_of_request(request: Request) -> str:
"""The feature label comes from the ROUTE, not the model: several endpoints
can share one model alias, so path -> feature is the service's own mapping."""
return request.url.path.strip("/").split("/")[0] or "unknown"
@app.middleware("http")
async def request_metrics(request: Request, call_next):
"""Request-level SLIs the client hooks can't see: in-flight count, request
duration, outcome.
record_request_end runs on EVERY path — success, HTTP error, exception —
so llm_inflight_requests can't leak (the classic +1-without-(-1) bug).
For SSE streams this times until the response is handed off; the stream's
own lifetime is a separate signal (TTFT below).
Outcome has two sources: the hooks write the LAST call's business outcome
into a per-request box (begin_request_outcome / note_request_outcome -
that's how refused/blocked/truncated reach this metric), and the HTTP
status is the floor: a >=400 response is "failed" even if the last call
"succeeded", because the endpoint broke afterwards. For SSE streams the
box is read when the response is handed off, before the stream finishes,
so a streamed request records "ok" here; the stream's true outcome is on
llm_outcomes_total (call level).
"""
feature = feature_of_request(request)
metrics.record_request_start(feature)
box = metrics.begin_request_outcome() # BEFORE call_next, see metrics.py
t0 = time.monotonic()
try:
response = await call_next(request)
status = response.status_code
except Exception:
metrics.record_request_end(feature, "failed", time.monotonic() - t0)
raise
outcome = (box["outcome"] or "ok") if status < 400 else "failed"
metrics.record_request_end(feature, outcome, time.monotonic() - t0)
return responseTwo more request-level producers, then the endpoint itself:
# Queue depth: the worker queue maintains llm_queue_depth itself — set it on
# enqueue/dequeue (or from a periodic sampler if the queue lives elsewhere):
# metrics.set_gauge("llm_queue_depth", queue.qsize(), queue="llm")
async def sse_answer(canonical_req):
"""TTFT is measured by the CONSUMER: StreamEvents carry no timestamps, so
the hook layer can't see it. Record it when Done arrives — only then do we
know model_key (the catalogue label for llm_ttft_seconds)."""
t0 = time.monotonic()
ttft_s: float | None = None
async for ev in client.astream(canonical_req):
if (ttft_s is None and isinstance(ev, (TextDelta, ReasoningDelta))
and ev.text): # empty deltas aren't content
ttft_s = time.monotonic() - t0
if isinstance(ev, Done) and ttft_s is not None:
metrics.observe("llm_ttft_seconds", ttft_s,
model_key=ev.response.model_key,
exemplar={"trace_id": ev.response.call_id})
yield ev
@app.get("/metrics")
async def metrics_endpoint() -> PlainTextResponse:
"""Prometheus scrape endpoint. MemoryBackend -> a JSON debug dump;
PrometheusBackend -> the real exposition."""
body, media_type = metrics.exposition()
return PlainTextResponse(body, media_type=media_type)Prometheus scrapes; your app serves. Metrics.exposition() keeps the route backend-agnostic — no metrics._b private-attribute poking, and the MemoryBackend debug path returns JSON with string label keys (a tuple-keyed snapshot() would crash json.dumps). For the OpenMetrics format (needed for exemplars), swap generate_latest for prometheus_client.openmetrics.exposition.generate_latest and set the content type accordingly — Prometheus negotiates it automatically, but Grafana's direct /api/datasources/proxy calls may need the explicit OpenMetrics endpoint.
3.5 OpenTelemetry metrics: the vendor-neutral path#
If your platform is OTel-native (11A.1 already wires OTel traces), emitting metrics through OTel keeps one instrumentation stack. The Python metrics API is stable and maps cleanly:
# llm_service/otel_metrics.py — OTel metrics alongside (or instead of) Prometheus
from opentelemetry import metrics
from opentelemetry.sdk.metrics import MeterProvider
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter
from opentelemetry.sdk.resources import Resource
def setup_otel_metrics(endpoint: str = "http://localhost:4318/v1/metrics") -> MeterProvider:
provider = MeterProvider(
resource=Resource.create({"service.name": "llm_service"}),
metric_readers=[PeriodicExportingMetricReader(
OTLPMetricExporter(endpoint=endpoint))],
)
metrics.set_meter_provider(provider)
return provider
meter = metrics.get_meter("llm_service")
call_duration = meter.create_histogram(
"llm.call.duration", unit="s",
description="Per-call LLM latency",
)
tokens = meter.create_counter(
"llm.tokens", unit="{token}",
description="Tokens by kind",
)
cost = meter.create_counter(
"llm.cost", unit="USD",
description="Cost in USD",
)Then in the hook:
call_duration.record(latency_ms / 1000.0,
attributes={"model_key": resp.model_key})
tokens.add(float(val), attributes={"model_key": model_key, "kind": kind})
cost.add(cost_usd, attributes={"feature": feature, "model_key": model_key})Key differences from prometheus_client:
- Temporality matters. OTel supports cumulative and delta; Prometheus-compatible backends want cumulative (the default for
PeriodicExportingMetricReaderis cumulative for counters/histograms — verify per backend). If your backend shows counters resetting to zero every interval, you picked delta by accident. - Attributes, not labels. Same idea, different name —
attributes={...}instead oflabels(...). Cardinality rules are identical. - No
/metricsendpoint for free. OTel exports via OTLP push to a collector; to expose Prometheus-format scraping you needopentelemetry-exporter-prometheus(version 0.66b2 as of November 2026 — beta, and it explicitly does not support multiprocessing). Most teams pick one: Prometheus pull or OTel push, not both. - Names: yours or the conventions'? The snippet uses our own
llm.*names to stay consistent with the Prometheus catalogue. The OTel GenAI conventions define their own metric names — for examplegen_ai.client.inference.duration(a histogram in seconds) on the caller side (the oldergen_ai.client.operation.durationshould not be reported for model calls: see the naming trap in 11A.1, 3.13) andgen_ai.server.time_to_first_token/gen_ai.server.time_per_output_tokenon the model-server side — all at Development status as of November 2026 (11A.1, 3.2). The same rule applies as for span attributes: if a platform's built-in LLM dashboards need thegen_ai.*names, add them beside your own behind one mapping module, not instead of them. - Exemplars are not in the Python OTel metrics API as of 1.45.2 — trace correlation happens via trace IDs in logs/ Exemplars are a Prometheus-client feature here.
3.6 Alternatives at pattern level#
- StatsD / DogStatsD: UDP fire-and-forget counters/timers/gauges. Cheaper than Prometheus (no scrape), loses histograms' exactness (StatsD timers are server-side approximations), and adds a local agent (Datadog, Telegraf, StatsD). Pattern: same metric names,
client.incr("llm.requests", tags=["feature:ask"]). Fine for small deployments; the cardinality and query ergonomics are worse. - Datadog / cloud-native: vendor SDKs or OTel→vendor collectors. Same instruments, different backend. The discipline (names, labels, buckets) transfers unchanged.
- Platform-native metrics (Langfuse, LangSmith, Phoenix): they emit their own cost/latency dashboards from traces (11A.1). Use them for per-trace drill-down; keep your Prometheus metrics for alerting and SLOs — you don't want your paging path depending on a third-party UI's retention.
Part 4: SLIs, SLOs and error budgets#
Metrics tell you what is happening. SLIs (service level indicators), SLOs (objectives) and error budgets turn that into a contract: a measurable definition of "good enough", a target, and a policy for what to do when you miss it. This is where metrics stop being a dashboard and start being an engineering governance tool.
4.1 SLI and SLO defined for LLM services#
An SLI is a ratio: good events / total events, measured over a window. An SLO is the target for that ratio over a compliance period (usually 30 days). The error budget is the complement: how much badness you can afford — (1 - SLO) × window, expressed as allowed bad events or allowed downtime-equivalent.
The hard part for LLM services is defining "good". For a CRUD API it's "2xx and <500ms". For llm_service it depends on the feature:
| SLI | Good event | Bad event | Why this definition |
|---|---|---|---|
| Availability | Request returns a usable answer (any finish reason except error/timeout) | Exception, timeout, 5xx, provider error after retries | The user got something — but see quality SLI below |
| Latency | TTFT < 5s AND total < 60s (per feature tier) | Either bound exceeded | Two bounds because streaming UX has two clocks |
| Quality pass rate | Sampled judge/eval score ≥ threshold, or deterministic check passes | Below threshold | Needs online evals (4.4) — can't be a per-request check |
| Freshness | Retrieval results younger than N hours (RAG features) | Stale index served | Data correctness is an SLI too |
| Cost efficiency | Cost per request < budgeted p95 | Above budget | A cost SLO prevents silent spend regressions |
Notice what's not an SLI: raw request count, raw error count, average latency. Those are metrics; SLIs are ratios with a goodness definition.
4.2 The worked SLO document for llm_service#
A real SLO document is short enough to fit on one page and specific enough to implement. Here's the shape for llm_service (illustrative targets — pick yours from product requirements and error-cost analysis, not from copying):
# llm_service SLOs — v1 (as of November 2026)
Window: rolling 30 days. Review: monthly or after any SLO change.
## SLO-1: Availability (all features)
- SLI: usable_answer / total_requests
- Target: 99.5% (error budget = 0.5% of requests ≈ 3.6h-equivalent of full outage)
- Excludes: client disconnects (abandoned) — not the service's failure.
Refusals, blocks and truncations ARE completed calls: the provider answered
definitively; whether the answer satisfies the user is SLO-3's job, not
availability's.
- Measured by: llm_requests_total{outcome=~"ok|refused|blocked|truncated"} /
llm_requests_total{outcome!="abandoned"}
## SLO-2: Latency (feature "ask" — interactive chat)
- SLI: requests with ttft < 5s AND total < 60s / total requests
- Target: 95% (error budget = 5% of requests may be slow)
- Rationale: chat users tolerate occasional slowness; a p95 bound is honest
## SLO-3: Quality (feature "extract" — invoice extraction)
- SLI: sampled judge pass rate ≥ 0.90
- Target: 90% (measured weekly on a 200-example sample from production traces)
- Excludes: cases where the document is genuinely unreadable (labelled in eval set)
- Dependency: Module 10A online eval pipeline; judge calibrated per 10A.5
## SLO-4: Cost (all features)
- SLI: daily_cost_usd / daily_requests < $0.05 p95
- Target: 95% of days under budget
- Alert-only SLO: cost is a guardrail, not a paging SLOThe document's value isn't the numbers — it's that every number maps to a metric and an alert. If you can't write the PromQL for an SLI, the SLI isn't measurable yet.
4.3 Error budgets and the budget policy#
An error budget answers: "how much unreliability can we afford?" For a 99.5% SLO over 30 days, budget = 0.5% of requests. At 10,000 requests/day that's ~1,500 bad requests — or, expressed as time, ~3.6 hours of complete outage. The budget is a resource to spend on change: releases, experiments, risky migrations.
A budget policy says what happens at consumption thresholds:
| Budget consumed | Policy |
|---|---|
| < 50% | Business as usual; ship normally |
| 50–100% | Freeze non-essential releases; prioritize reliability work; no risky experiments |
| ≥ 100% (exhausted) | Freeze all releases except fixes; postmortem mandatory; SLO review within 1 week |
This is the mechanism that makes SLOs governance rather than decoration: the budget is the currency that buys you the right to take risks, and spending it forces a conversation.
4.4 Quality SLOs: why they need online evals#
Availability and latency SLIs measure operations. Quality SLIs measure outcomes — and they cannot be computed per-request cheaply enough to alert on every call. The pattern:
- Sample a fraction of production traffic (1–10%, or all of it for low-volume features).
- Score each sample with a judge or deterministic check (Module 10A owns the methodology — LLM-as-judge, calibration (10A.5), online evals (10A.9)).
- Aggregate into
eval_score{feature, eval_name}— the gauge yourmetrics.pyalready defines. - Alert on the score's trend, not individual samples (a single bad judge verdict is noise; a 3-day decline is signal).
The trap to name honestly: quality SLOs are only as good as the judge. A miscalibrated judge produces a confident, wrong SLO. 10A.5 owns judge calibration; the operational rule here is: never alert on a quality SLO whose judge hasn't been validated against human labels in the last quarter — 10A.5 owns that validation.
4.5 Multi-window, multi-burn-rate alerting#
The naive alert — "error rate > SLO threshold" — fires constantly on noise and misses slow burns. The fix (from the Google SRE Workbook, ch. 5) is burn-rate alerting: instead of "is the error rate high?", ask "how fast are we consuming error budget?"
Burn rate = (observed bad-event ratio) / (allowed bad-event ratio). A burn rate of 1 means you're spending budget exactly as fast as allowed — you'll exhaust it right at the end of the window. A burn rate of 14.4 means you'll exhaust a 30-day budget in ~2 days.
Multi-window means requiring the burn rate to be high over both a long window (catches sustained problems) and a short window (catches spikes fast, filters flapping). The SRE workbook's recommended configuration:
| Severity | Long window | Short window | Burn rate | Budget consumed | Notification |
|---|---|---|---|---|---|
| Page | 1 hour | 5 minutes | 14.4× | 2% | Wake someone up |
| Page | 6 hours | 30 minutes | 6× | 5% | Wake someone up (slower burn) |
| Ticket | 3 days | 6 hours | 1× | 10% | Fix during business hours |
The PromQL for the fast-burn page alert (for a 99.9% availability SLO, slo_target = 0.999):
# Recording rules: the "bad event" ratio the SLOs define — failed, invalid
# and uncategorised outcomes over all non-abandoned requests — over each
# window an alert consumes. (The full set for all three severities lives in
# 6.2's llm-alerts.yml.)
record: job:slo_errors_per_request:ratio_rate1h
expr: |
sum(rate(llm_requests_total{outcome=~"failed|invalid|other"}[1h])) by (job)
/
sum(rate(llm_requests_total{outcome!="abandoned"}[1h])) by (job)
record: job:slo_errors_per_request:ratio_rate5m
expr: |
sum(rate(llm_requests_total{outcome=~"failed|invalid|other"}[5m])) by (job)
/
sum(rate(llm_requests_total{outcome!="abandoned"}[5m])) by (job)
# Alert: burn rate > 14.4 over BOTH 1h and 5m windows
alert: LLMBurnRateFast
expr: |
(
job:slo_errors_per_request:ratio_rate1h > (14.4 * (1 - 0.999))
and
job:slo_errors_per_request:ratio_rate5m > (14.4 * (1 - 0.999))
)
for: 2m
labels:
severity: page
annotations:
summary: "llm_service burning error budget at >14.4x — SLO at risk"
runbook: "https://wiki.internal/llm-service/runbooks/burn-rate"Writing these rules by hand for every SLO gets repetitive; SLO generators such as Sloth turn a short SLO spec into the recording and alerting rules, which is worth adopting once you have more than a couple of SLOs. The and is the multi-window part: both conditions must hold, so a 2-minute blip doesn't page but a sustained spike does. The (1 - 0.999) is the allowed error ratio (0.1%); 14.4 × 0.001 = 0.0144 is the burn-rate threshold as an error ratio.
4.6 Page vs ticket: routing by severity#
The difference between a page and a ticket is who gets interrupted and when:
- Page — the on-call engineer is woken. Reserve for: fast burn (budget gone in hours), total outage, data-loss risk, security incident. If it can wait until morning, it's not a page.
- Ticket — a backlog item. Reserve for: slow burn, budget trending toward exhaustion, degraded-but-functional states, quality drift below SLO but above critical.
- Dashboard only — informational. Everything else: single-sample anomalies, expected fluctuations, low-traffic-period noise.
The failure mode to avoid: everything is a page. If your pager fires more than ~2 times per shift on average, the thresholds are wrong — either the SLO is too tight for the traffic level, or the windows are too short. Alert fatigue is a real cost: engineers learn to ignore pages, and the one that matters gets missed.
4.7 The SLO calculator#
Error-budget arithmetic is simple enough to do by hand, but a calculator removes the mental overhead and makes the burn-rate thresholds concrete. This is pure stdlib — run it for real:
# slo_calc.py — error budget and burn-rate calculator (stdlib only)
from __future__ import annotations
def error_budget(slo: float, window_days: float = 30.0) -> dict:
"""Allowed bad-event ratio and time-equivalent for a given SLO."""
allowed_ratio = 1.0 - slo
# For an availability SLO, budget-as-time = allowed_ratio × window
budget_hours = allowed_ratio * window_days * 24
return {
"slo": slo,
"window_days": window_days,
"allowed_bad_ratio": allowed_ratio,
"budget_hours_equiv": budget_hours,
"budget_pct": allowed_ratio * 100,
}
def burn_rate(observed_bad_ratio: float, slo: float) -> float:
"""How many times faster than allowed are we consuming budget?
observed_bad_ratio: fraction of events that were bad in the window
slo: target (e.g. 0.999)
"""
allowed = 1.0 - slo
if allowed <= 0:
raise ValueError("SLO must be < 1.0")
return observed_bad_ratio / allowed
def time_to_exhaust(observed_bad_ratio: float, slo: float,
window_days: float = 30.0) -> float:
"""Days until budget exhaustion at the current burn rate.
A burn rate below 1 never exhausts WITHIN the window — the budget resets
— so the return value is really "days at this rate", which can exceed
window_days. Callers should treat > window_days as "never in-window".
"""
br = burn_rate(observed_bad_ratio, slo)
if br <= 0:
return float("inf")
return window_days / br
def multi_window_alert(observed_1h: float, observed_5m: float,
slo: float = 0.999) -> dict:
"""Evaluate the fast-burn page condition: burn >14.4 over BOTH windows."""
threshold = 14.4 * (1 - slo)
br_1h = burn_rate(observed_1h, slo)
br_5m = burn_rate(observed_5m, slo)
fires = observed_1h > threshold and observed_5m > threshold
return {
"threshold_ratio": round(threshold, 6),
"burn_1h": round(br_1h, 2), "burn_5m": round(br_5m, 2),
"fires": fires,
"severity": "page" if fires else "none",
}
if __name__ == "__main__":
# 99.9% SLO over 30 days
b = error_budget(0.999)
print(f"SLO 99.9% / 30d: allowed bad ratio = {b['allowed_bad_ratio']:.4%}, "
f"budget ≈ {b['budget_hours_equiv']:.1f}h of full outage")
# Healthy: 0.05% errors (half the allowed rate) → burn 0.5 → below 1×,
# budget never exhausts within the 30-day window (it resets).
days = time_to_exhaust(0.0005, 0.999)
print(f"\nHealthy (0.05% bad): burn={burn_rate(0.0005, 0.999):.2f}x, "
f"would take {days:.0f} days at this rate "
f"(> 30d window: budget resets, never exhausts)")
# Degraded: 0.5% bad → burn 5x → exhausts in 6 days
print(f"Degraded (0.5% bad): burn={burn_rate(0.005, 0.999):.1f}x, "
f"exhausts in {time_to_exhaust(0.005, 0.999):.0f} days")
# Critical: 2% bad → burn 20x → exhausts in 1.5 days
print(f"Critical (2% bad): burn={burn_rate(0.02, 0.999):.1f}x, "
f"exhausts in {time_to_exhaust(0.02, 0.999):.1f} days")
# Multi-window: sustained spike vs blip
print("\nMulti-window fast-burn check (SLO 99.9%):")
print(" Sustained spike (1h=2%, 5m=2%):",
multi_window_alert(0.02, 0.02))
print(" Blip (1h=0.5%, 5m=5%): ",
multi_window_alert(0.005, 0.05))
print(" Slow burn (1h=0.3%, 5m=0.3%): ",
multi_window_alert(0.003, 0.003))SLO 99.9% / 30d: allowed bad ratio = 0.1000%, budget ≈ 0.7h of full outage
Healthy (0.05% bad): burn=0.50x, would take 60 days at this rate (> 30d window: budget resets, never exhausts)
Degraded (0.5% bad): burn=5.0x, exhausts in 6 days
Critical (2% bad): burn=20.0x, exhausts in 1.5 days
Multi-window fast-burn check (SLO 99.9%):
Sustained spike (1h=2%, 5m=2%): {'threshold_ratio': 0.0144, 'burn_1h': 20.0, 'burn_5m': 20.0, 'fires': True, 'severity': 'page'}
Blip (1h=0.5%, 5m=5%): {'threshold_ratio': 0.0144, 'burn_1h': 5.0, 'burn_5m': 50.0, 'fires': False, 'severity': 'none'}
Slow burn (1h=0.3%, 5m=0.3%): {'threshold_ratio': 0.0144, 'burn_1h': 3.0, 'burn_5m': 3.0, 'fires': False, 'severity': 'none'}The blip case is the instructive one: a 5-minute spike to 5% errors looks catastrophic (50× burn) but the 1-hour rate is only 0.5% (5× burn) — below the 14.4× threshold — so no page. That's the multi-window design working: it distinguishes "something bad is happening right now" from "something bad happened briefly".
4.8 Agent metrics: steps per run, tool error rate and cost per task#
Everything so far treats a request as one unit. An agent run is a loop: the model picks a tool, the tool runs, the result goes back to the model, and this repeats until the model answers or a limit stops it (08A.2). One run can make 3 model calls or 30. A request-level SLI such as availability can stay at 99.9% while the loop inside gets slower, flakier and ten times more expensive, because the run still "finished". So agent features need three extra numbers, each with its own SLI, panel and alert.
| Metric | What it tells you | Catalogue name (3.2) | Type | Source |
|---|---|---|---|---|
| Steps per run | How long the loop runs. A rising p95 with a flat p50 means a few runs are looping | llm_agent_steps{feature} |
Histogram | agent loop, one observation when the run ends |
| Run end reason | Why the loop stopped: done, step_cap, budget, timeout, error. A rising step_cap share means runs are being cut off, not finishing |
agent_runs_total{feature, end_reason} |
Counter | agent loop (new, see below) |
| Tool calls by result | Whether the tools the agent depends on work | llm_tool_calls_total{tool, result} |
Counter | tool executor, one increment per call |
| Cost per run | What one task costs, tail included | agent_run_cost_usd{feature} |
Histogram | agent loop: the sum of every model call and paid tool call in the run |
The first and third rows already exist in the 3.2 catalogue. Two small additions complete the set (same discipline as before: one owner per metric, a bounded label vocabulary, names defined once in _CATALOGUE):
# llm_service/metrics.py, added to _CATALOGUE (pipeline/domain section)
"agent_runs_total": _MetricSpec("counter", "Agent runs by end reason",
("feature", "end_reason")),
"agent_run_cost_usd": _MetricSpec(
"histogram", "Total cost of one agent run, model + tool calls",
("feature",), COST_BUCKETS_USD),Keep end_reason and result to short fixed sets (for example result is one of ok, error, timeout, invalid_args, denied). Never put a run id, a tool argument or a user id in a label (1.5). Those belong on the trace (11A.1), and the exemplar from 2.4 links the two.
Tool error rate as a named SLI
An SLI is a ratio with a definition of "good" (4.1). For tools, define it like this and name it, so everyone means the same thing:
- Tool success ratio (the SLI): calls with
result="ok"divided by counted calls, per tool. - Tool error rate: one minus the tool success ratio. This is the number on the dashboard and in the alert.
- Bad events:
error,timeoutandinvalid_args. The last one is the model's fault (it sent bad arguments), not the tool's, but the run still wasted a step, so count it, and look at it separately when you debug. - Excluded:
denied. A call blocked by policy or refused at an approval gate is the safety layer working, not a failure. Treat it likeabandonedin SLO-1.
Add it to the SLO document from 4.2 (illustrative target, pick yours from the cost of a failed tool call):
## SLO-5: Tool success (agent features, per tool)
- SLI: tool calls with result="ok" / tool calls with result in
(ok, error, timeout, invalid_args), per tool
- Target: 99% per tool over 30 days (error budget = 1% of that tool's calls)
- Excludes: result="denied" (policy and approval blocks)
- Why per tool: one flaky tool is invisible in the all-tools average
- Measured by: llm_tool_calls_total{result="ok"} /
llm_tool_calls_total{result!="denied"}, grouped by tool
## SLO-6: Cost per agent run (agent features)
- SLI: runs with agent_run_cost_usd <= $0.25 / completed runs
- Target: 95% of runs
- Alert-only, like SLO-4: cost is a guardrail, not a paging SLOCost per task, online
A task here is one agent run. Cost per task is total spend divided by the number of runs, and its tail (the p95) matters more than its mean, because a stuck loop is the expensive run. Online you usually cannot tell if the run succeeded (that needs a grader), so the online number is cost per completed run, plus the share of runs under a budget. The offline version, cost per successful task with graded outcomes and failed runs' spend included, is in 10A.7, 5.6; use it in CI to compare changes, and use the online number to watch production. When you sample runs for an online judge (4.4), divide total spend by judged-good runs to get an online cost per successful task too. Organisation-level budgets, quotas, attribution and chargeback for agents are in 11B.6 (see also 9.2 for per-tenant caps here).
Computing the SLIs from run records
The three SLIs are plain arithmetic over what the agent loop already logs. This sketch uses fake run records (one dict per run) so you can see the numbers before you wire up Prometheus. It is pure stdlib; run it for real:
# agent_slis.py: agent SLIs from a list of run records (stdlib only)
from __future__ import annotations
import math
import random
from collections import Counter, defaultdict
MAX_STEPS = 20 # the loop's step cap (the agent stops here)
TOOL_SLO = 0.99 # SLO-5: 99% of tool calls succeed, per tool
COST_BUDGET_USD = 0.25 # SLO-6: a run within this cost is a "good" run
COST_SLO = 0.95
BAD_RESULTS = {"error", "timeout", "invalid_args"} # "denied" is excluded
def make_fake_runs(n: int = 300, seed: int = 7) -> list[dict]:
"""Fake run records, shaped like what an agent loop would log per run."""
rng = random.Random(seed)
runs = []
for i in range(n):
steps = min(MAX_STEPS, max(1, round(rng.lognormvariate(1.5, 0.55))))
if rng.random() < 0.04: # a stuck loop
steps = MAX_STEPS
calls = []
for _ in range(max(0, steps - 1)):
tool = rng.choice(["search_docs", "get_order", "send_email", "calc"])
bad = {"search_docs": 0.004, "get_order": 0.06, # get_order is flaky
"send_email": 0.01, "calc": 0.0}[tool]
roll = rng.random()
if roll < bad:
result = rng.choice(["error", "timeout", "invalid_args"])
elif tool == "send_email" and roll > 0.93:
result = "denied" # policy blocked it: not a failure
else:
result = "ok"
calls.append((tool, result))
cost = 0.012 * steps * rng.uniform(0.6, 1.5)
if steps == MAX_STEPS:
cost *= 1.4
runs.append({"run_id": f"r{i:03d}", "feature": "support_agent",
"steps": steps,
"end_reason": "step_cap" if steps == MAX_STEPS else "done",
"cost_usd": round(cost, 4), "tool_calls": calls})
return runs
def percentile(values: list[float], q: float) -> float:
"""Nearest-rank percentile: simple, and good enough for a dashboard."""
ordered = sorted(values)
return ordered[max(0, math.ceil(q * len(ordered)) - 1)]
def tool_sli(runs: list[dict]) -> dict[str, tuple[int, int]]:
"""tool -> (good, counted). 'denied' is left out of both sides."""
out: dict[str, list[int]] = defaultdict(lambda: [0, 0])
for run in runs:
for tool, result in run["tool_calls"]:
if result == "denied":
continue
out[tool][1] += 1
out[tool][0] += result == "ok"
return {t: (g, n) for t, (g, n) in out.items()}
def burn_rate(bad_ratio: float, slo: float) -> float:
return bad_ratio / (1 - slo)
runs = make_fake_runs()
steps = [r["steps"] for r in runs]
print(f"runs: {len(runs)}")
print(f"steps per run: p50={percentile(steps, .5):.0f} p95={percentile(steps, .95):.0f} "
f"max={max(steps)}")
ends = Counter(r["end_reason"] for r in runs)
print(f"step-cap rate: {ends['step_cap'] / len(runs):.1%} ({dict(ends)})")
print("\ntool success SLI (SLO 99%):")
total_good = total_n = 0
for tool, (good, n) in sorted(tool_sli(runs).items()):
total_good, total_n = total_good + good, total_n + n
ratio = good / n
bad = 1 - ratio
flag = "BREACH" if ratio < TOOL_SLO else "ok"
print(f" {tool:<12} {good:>4}/{n:<4} success={ratio:.2%} "
f"error_rate={bad:.2%} burn={burn_rate(bad, TOOL_SLO):.1f}x {flag}")
print(f" {'ALL TOOLS':<12} {total_good:>4}/{total_n:<4} "
f"success={total_good / total_n:.2%} <- one flaky tool drags the average")
denied = sum(1 for r in runs for _, res in r["tool_calls"] if res == "denied")
print(f" (excluded: {denied} denied calls, policy working as intended)")
costs = [r["cost_usd"] for r in runs]
within = sum(c <= COST_BUDGET_USD for c in costs) / len(costs)
print(f"\ncost per task: mean=${sum(costs) / len(costs):.4f} "
f"p95=${percentile(costs, .95):.4f} total=${sum(costs):.2f}")
print(f"runs within ${COST_BUDGET_USD:.2f}: {within:.1%} (SLO {COST_SLO:.0%}) -> "
f"{'ok' if within >= COST_SLO else 'BREACH'}")
stuck = [c for r, c in zip(runs, costs) if r["end_reason"] == "step_cap"]
rest = [c for r, c in zip(runs, costs) if r["end_reason"] != "step_cap"]
print(f"step-capped runs cost ${sum(stuck) / len(stuck):.4f} each vs "
f"${sum(rest) / len(rest):.4f} for the others")runs: 300
steps per run: p50=5 p95=14 max=20
step-cap rate: 3.7% ({'done': 289, 'step_cap': 11})
tool success SLI (SLO 99%):
calc 347/347 success=100.00% error_rate=0.00% burn=0.0x ok
get_order 347/377 success=92.04% error_rate=7.96% burn=8.0x BREACH
search_docs 368/368 success=100.00% error_rate=0.00% burn=0.0x ok
send_email 324/329 success=98.48% error_rate=1.52% burn=1.5x BREACH
ALL TOOLS 1386/1421 success=97.54% <- one flaky tool drags the average
(excluded: 30 denied calls, policy working as intended)
cost per task: mean=$0.0762 p95=$0.1838 total=$22.86
runs within $0.25: 97.7% (SLO 95%) -> ok
step-capped runs cost $0.2973 each vs $0.0678 for the othersRead it the way you would read a dashboard:
- Steps: a median of 5 and a p95 of 14 is a healthy shape. The 3.7% of runs that hit the 20-step cap are the loop problem, and they cost about four times as much as a normal run ($0.30 against $0.07). They are small in number but each one costs real money, which is why the step-cap rate gets its own panel.
- Tools: the all-tools success ratio is 97.54%, which looks like "a bit under target". The per-tool rows show the real story:
get_orderis at 92.04%, an 8x burn rate, andsend_emailis just under its SLO at 98.48%. Without the per-tool split you would not know where to look. - Cost: 97.7% of runs are inside the $0.25 budget, so SLO-6 holds. The p95 ($0.18) sits under the budget too. If more runs started to loop, the share inside the budget would fall before the mean moved much.
Dashboard panels and alerts
These go on the Pipeline internals dashboard from 5.1. The alert rules follow the style of 6.2; thresholds are illustrative.
| Panel (question it answers) | Query | Alert and severity |
|---|---|---|
| Steps per run p50 and p95 (are loops getting longer?) | histogram_quantile(0.95, sum by (le, feature) (rate(llm_agent_steps_bucket[1h]))) |
AgentStepsP95High: p95 above 13 for 30m, ticket (a loop regression is rarely an emergency; the cost alert catches the money) |
| Step-cap rate (how many runs get cut off?) | sum(rate(agent_runs_total{end_reason="step_cap"}[1h])) by (feature) / sum(rate(agent_runs_total[1h])) by (feature) |
AgentStepCapRateHigh: above 5% for 1h, ticket |
| Tool error rate by tool (which tool is failing?) | 1 - sum by (tool) (rate(llm_tool_calls_total{result="ok"}[1h])) / sum by (tool) (rate(llm_tool_calls_total{result!="denied"}[1h])) |
ToolErrorBudgetBurn: multi-window burn rate on SLO-5 as in 4.5 (14.4x over 1h and 5m is a page for a critical tool; 1x over 3d is a ticket) |
| Tool-call volume by result (is traffic or the failure mix changing?) | sum by (tool, result) (rate(llm_tool_calls_total[5m])) |
none (context for the alert above) |
| Cost per run, mean and p95 (what does a task cost?) | sum(rate(agent_run_cost_usd_sum[1h])) / sum(rate(agent_run_cost_usd_count[1h])), and histogram_quantile(0.95, sum by (le) (rate(agent_run_cost_usd_bucket[1h]))) |
AgentCostPerRunHigh: mean above 2x the trailing 7-day mean for 1h, ticket |
| Runs over budget (is SLO-6 holding?) | sum(rate(agent_run_cost_usd_bucket{le="0.25"}[1d])) / sum(rate(agent_run_cost_usd_count[1d])) |
below 0.95 for a day, ticket (alert-only, like SLO-4) |
Two cautions. First, rate() over a histogram's _sum and _count gives a mean, and a mean can sit still while the tail grows: always put the p95 on the same panel. Second, a tool-error alert fires on the tool's own health but cannot tell why: check the trace for that tool's spans, and split invalid_args from error before you blame the tool. The depth on agent dashboards, audit logs and SLOs belongs to 11A.3, the next lesson in this module.
Part 5: Dashboards#
Deep-dive
A dashboard is a question-answering surface: each panel exists to answer one question fast, during an incident or a weekly review. The failure mode is the "wall of graphs" — twenty panels nobody reads. The discipline: one dashboard per question-set, not per team.
5.1 The dashboard template set#
llm_service gets five dashboards, each answering a distinct set of questions:
| Dashboard | Questions it answers | Key panels |
|---|---|---|
| Service health | Is it up? Is it slow? Is it failing? | Request rate, error rate by class, TTFT p50/p95/p99, total-duration p95, in-flight requests, queue depth, served-model distribution (llm_served_model_total — snapshot drift shows here before users notice) |
| Cost | What is it spending? Where? Is it trending up? | llm_cost_usd_total rate by feature/model, cost per request p50/p95, tokens by kind, cache hit rate, daily spend vs budget |
| Quality | Is it getting worse? | eval_score by feature/eval, feedback sentiment ratio, refusal/abstention rate, judge-score trend |
| Pipeline internals (RAG/agent features) | Which stage is slow or empty? | Retrieval hit count, rerank score distribution, tool-call count per run, agent step count, guardrail triggers, citation coverage. For agents, add the panels in 4.8: steps per run, step-cap rate, tool error rate by tool, cost per run |
| Per-tenant / per-feature | Who is affected? Who is expensive? | All of the above sliced by tenant_tier or feature — the drill-down view |
The first four are operational; the fifth is the "who" view you pivot to when the first four show a problem. Notice what's absent: no raw request IDs, no prompt text, no per-user panels — those live in traces (11A.1) and logs (03.10), not dashboards.
5.2 Dashboards as code: Grafana provisioning#
Dashboards built by clicking in the UI are unversioned, unreviewable and unreproducible. Dashboards as code — JSON files provisioned into Grafana — fixes all three. The mechanism: Grafana's provisioning system reads provisioning/dashboards/*.yml for where to find dashboards and the dashboard JSON files themselves for what they contain.
Directory layout:
grafana/
provisioning/
dashboards/
dashboards.yml # tells Grafana where dashboard JSON lives
dashboards/
llm-service-health.json # the dashboard itself
llm-service-cost.json
llm-service-quality.jsonprovisioning/dashboards/dashboards.yml:
apiVersion: 1
providers:
- name: llm-service
orgId: 1
folder: LLM Service
type: file
disableDeletion: false
updateIntervalSeconds: 30
allowUiUpdates: false # dashboards are code; UI edits get overwritten
options:
path: /etc/grafana/dashboards
foldersFromFilesStructure: falseA minimal dashboard JSON (trimmed — real dashboards are larger, but this is the shape). schemaVersion tracks your Grafana release — export a real dashboard from your instance and copy its value if provisioning warns:
{
"title": "llm_service — Health",
"uid": "llm-service-health",
"schemaVersion": 39,
"version": 1,
"panels": [
{
"id": 1,
"type": "timeseries",
"title": "Request rate by outcome",
"gridPos": {"h": 8, "w": 12, "x": 0, "y": 0},
"targets": [{
"expr": "sum by (outcome) (rate(llm_requests_total[5m]))",
"legendFormat": "{{outcome}}"
}],
"fieldConfig": {"defaults": {"unit": "reqps"}}
},
{
"id": 2,
"type": "timeseries",
"title": "Latency p50/p95/p99 (call duration)",
"gridPos": {"h": 8, "w": 12, "x": 12, "y": 0},
"targets": [
{"expr": "histogram_quantile(0.50, sum by (le, model_key) (rate(llm_call_duration_seconds_bucket[5m])))", "legendFormat": "p50 {{model_key}}"},
{"expr": "histogram_quantile(0.95, sum by (le, model_key) (rate(llm_call_duration_seconds_bucket[5m])))", "legendFormat": "p95 {{model_key}}"},
{"expr": "histogram_quantile(0.99, sum by (le, model_key) (rate(llm_call_duration_seconds_bucket[5m])))", "legendFormat": "p99 {{model_key}}"}
],
"fieldConfig": {"defaults": {"unit": "s"}}
},
{
"id": 3,
"type": "timeseries",
"title": "Served model share (snapshot drift)",
"gridPos": {"h": 8, "w": 12, "x": 0, "y": 8},
"targets": [{
"expr": "sum by (served_model) (rate(llm_served_model_total[1h]))",
"legendFormat": "{{served_model}}"
}],
"fieldConfig": {"defaults": {"unit": "reqps"}}
}
]
}The histogram_quantile calls are the heart of LLM latency dashboards: they turn bucket counts into the percentiles users actually feel. sum by (le, model_key) aggregates across all llm_service replicas before computing the quantile — the correct order (Part 2.1).
For Datadog or cloud-native dashboards, the same principle applies: dashboards are API/Terraform-managed resources, not click-ops artifacts. The metric names and queries differ; the "one dashboard per question-set" discipline is identical.
5.3 Annotating deploys, prompts and model changes#
The most valuable dashboard feature for LLM systems is annotations: vertical markers on every chart showing when something changed. Without them, a latency spike at 14:32 is a mystery; with them, it's "the deploy at 14:30" or "the prompt v3 promotion at 14:15".
What to annotate:
- Deploys — every release, with version/commit
- Prompt changes — prompt version promotions (04.10 owns prompt versioning; you own the marker)
- Model changes — model alias repoints, snapshot updates, provider-side deprecations
- Config changes — timeout changes, concurrency limits, feature flags
- Eval gates — CI eval results (pass/fail) as annotations on the quality dashboard
Implementation options, simplest first:
- Grafana annotations API —
POST /api/annotationswith{dashboardId, time, tags, text}. Your deploy pipeline calls this after a successful rollout. - Annotation tags in metrics — a
deploy_infogauge or achanges_totalcounter that dashboards query as an annotation source. More robust (survives Grafana restarts) but requires a recording rule. - GitOps — dashboard JSON changes are themselves commits; the diff is the annotation for dashboard changes.
The minimum viable version: your CI/CD pipeline (11C.2) posts an annotation on every production deploy with the commit SHA and a link to the release notes. That alone answers "did this deploy cause the spike?" 80% of the time.
5.4 The metrics pipeline, end to end#
flowchart LR
subgraph app ["llm_service (FastAPI)"]
HOOK["ServiceMetricsHook<br/>(provider_agnostic hooks)"]
SVC["Route handlers<br/>(feature, tenant, queue)"]
M["Metrics facade<br/>(catalogue + backends)"]
HOOK --> M
SVC --> M
end
subgraph backends ["Backends"]
PM["PrometheusBackend<br/>/metrics endpoint"]
MB["MemoryBackend<br/>(tests, local)"]
OTEL["OTel MeterProvider<br/>OTLP push"]
M --> PM
M --> MB
M -.->|optional| OTEL
end
subgraph observe ["Observation stack"]
PROM["Prometheus<br/>(scrape + rules)"]
GRAF["Grafana<br/>(dashboards + alerts)"]
DD["Datadog / vendor<br/>(optional)"]
end
PM -->|"scrape GET /metrics"| PROM
PROM --> GRAF
OTEL -->|"OTLP push via a collector, or Prometheus OTLP receiver"| PROM
PROM -->|alert rules| GRAF
GRAF -->|page/ticket| ONCALL["On-call / ticket queue"]The key property: metrics flow one way — app → backend → visualization/alerting. Nothing in the observation stack writes back into the request path. A broken Prometheus or Grafana must never slow or fail an LLM request; the MemoryBackend and the fail_closed = False observer pattern (3.3) guarantee that.
Part 6: Alerting#
6.1 Alert design principles#
An alert is a notification that someone must act. Every alert you ship should pass four tests:
- Actionable — when it fires, there's a known response (runbook, rollback, scale, investigate). If the only response is "look at it", it's a dashboard panel, not an alert.
- Symptom-based — alert on what users experience (error rate, latency, cost spike), not on causes (CPU, memory, a specific dependency's health). Causes belong in dashboards; symptoms belong in alerts.
- Thresholded with hysteresis — fire when the condition is true, resolve when it's been false for a sustained period. Avoid flapping: a condition that's borderline will fire/resolve repeatedly and train people to ignore it.
- Routed by severity — page for "wake someone now", ticket for "fix today", dashboard for "be aware". (4.6 covered the page/ticket split.)
The LLM-specific additions:
- Alert on outcomes, not just errors. A spike in
refusedortruncatedoutcomes is an alert even with zero exceptions. - Alert on silent failures. "Zero retrieval hits", "100% abstention", "cache hit rate dropped to 0%" — conditions that look like success but aren't. (6.3)
- Alert on cost anomalies. A 10× cost-per-request spike is as urgent as a 10× error spike. (6.4)
6.2 The alert rules file#
Alert rules live in Prometheus (or Grafana's alerting engine, or Alertmanager). Here's a reference llm-alerts.yml covering the core set — Prometheus rule-group format:
# Burn-rate thresholds below assume SLO-1's 99.5% target: the allowed bad-event
# ratio is (1 - 0.995) = 0.005. Adjust every `* 0.005` if your SLO differs.
groups:
- name: llm_service.target # is anything being measured at all?
rules:
- alert: LLMTargetDown
expr: up{job="llm_service"} == 0
for: 5m
labels: {severity: page}
annotations:
summary: "llm_service scrape target down — every other alert is blind"
runbook: "https://wiki.internal/llm-service/runbooks/target-down"
- alert: LLMNoMetrics
expr: |
absent(llm_requests_total{job="llm_service"})
and on(job) (up{job="llm_service"} == 1)
for: 15m
labels: {severity: page}
annotations:
summary: "llm_service /metrics returns no series while the target is up — app alive, metrics broken?"
runbook: "https://wiki.internal/llm-service/runbooks/no-metrics"
- name: llm_service.slo_recording # the ratios every burn-rate alert consumes
rules:
# "Bad event" = the SLO-1 definition: failed / invalid / uncategorised
# outcomes over all non-abandoned requests.
- record: job:slo_errors_per_request:ratio_rate1h
expr: |
sum(rate(llm_requests_total{outcome=~"failed|invalid|other"}[1h])) by (job)
/
sum(rate(llm_requests_total{outcome!="abandoned"}[1h])) by (job)
- record: job:slo_errors_per_request:ratio_rate5m
expr: |
sum(rate(llm_requests_total{outcome=~"failed|invalid|other"}[5m])) by (job)
/
sum(rate(llm_requests_total{outcome!="abandoned"}[5m])) by (job)
- record: job:slo_errors_per_request:ratio_rate30m
expr: |
sum(rate(llm_requests_total{outcome=~"failed|invalid|other"}[30m])) by (job)
/
sum(rate(llm_requests_total{outcome!="abandoned"}[30m])) by (job)
- record: job:slo_errors_per_request:ratio_rate6h
expr: |
sum(rate(llm_requests_total{outcome=~"failed|invalid|other"}[6h])) by (job)
/
sum(rate(llm_requests_total{outcome!="abandoned"}[6h])) by (job)
- record: job:slo_errors_per_request:ratio_rate3d
expr: |
sum(rate(llm_requests_total{outcome=~"failed|invalid|other"}[3d])) by (job)
/
sum(rate(llm_requests_total{outcome!="abandoned"}[3d])) by (job)
- name: llm_service.availability
rules:
- alert: LLMHighErrorRate
expr: job:slo_errors_per_request:ratio_rate5m{job="llm_service"} > 0.02
for: 5m
labels: {severity: ticket}
annotations:
summary: "llm_service bad-outcome ratio >2% for 5m"
runbook: "https://wiki.internal/llm-service/runbooks/high-error-rate"
- alert: LLMBurnRateFast
expr: |
(
job:slo_errors_per_request:ratio_rate1h > (14.4 * 0.005)
and
job:slo_errors_per_request:ratio_rate5m > (14.4 * 0.005)
)
for: 2m
labels: {severity: page}
annotations:
summary: "llm_service burning error budget at >14.4x"
runbook: "https://wiki.internal/llm-service/runbooks/burn-rate"
- alert: LLMBurnRateSlow
expr: |
(
job:slo_errors_per_request:ratio_rate6h > (6 * 0.005)
and
job:slo_errors_per_request:ratio_rate30m > (6 * 0.005)
)
for: 15m
labels: {severity: page}
annotations:
summary: "llm_service burning error budget at >6x — slow burn"
runbook: "https://wiki.internal/llm-service/runbooks/burn-rate"
- alert: LLMBudgetBurnTicket
expr: |
(
job:slo_errors_per_request:ratio_rate3d > (1 * 0.005)
and
job:slo_errors_per_request:ratio_rate6h > (1 * 0.005)
)
for: 1h
labels: {severity: ticket}
annotations:
summary: "llm_service bad-outcome ratio above the SLO allowance for days — budget trending to exhaustion"
runbook: "https://wiki.internal/llm-service/runbooks/burn-rate"
- name: llm_service.latency
rules:
- alert: LLMHighTTFT
expr: |
histogram_quantile(0.95,
sum by (le, model_key) (rate(llm_ttft_seconds_bucket[5m]))) > 5
for: 10m
labels: {severity: ticket}
annotations:
summary: "llm_service TTFT p95 > 5s for {{ $labels.model_key }}"
- alert: LLMHighTotalLatency
expr: |
histogram_quantile(0.95,
sum by (le, model_key) (rate(llm_call_duration_seconds_bucket[5m]))) > 60
for: 10m
labels: {severity: ticket}
annotations:
summary: "llm_service call duration p95 > 60s for {{ $labels.model_key }}"
- name: llm_service.cost
rules:
- alert: LLMCostSpike
expr: |
sum(rate(llm_cost_usd_total[1h])) by (feature)
>
3 * sum(rate(llm_cost_usd_total[1h] offset 1d)) by (feature)
for: 30m
labels: {severity: ticket}
annotations:
summary: "llm_service cost for {{ $labels.feature }} is 3x yesterday's rate"
- alert: LLMCacheHitRateDrop
expr: |
sum(rate(llm_cache_lookups_total{result="hit"}[30m])) by (cache)
/
sum(rate(llm_cache_lookups_total[30m])) by (cache)
< 0.5
for: 1h
labels: {severity: ticket}
annotations:
summary: "llm_service cache {{ $labels.cache }} hit rate <50% for 1h"
- name: llm_service.silent_failures
rules:
- alert: LLMNoRetrievalHits
# Traffic guard: at 3 a.m. with no requests, zero hits is normal, not an
# outage. Scope the `llm_requests_total` selector to your RAG feature(s).
expr: |
sum(rate(rag_retrieval_hits_total[15m])) == 0
and
sum(rate(llm_requests_total{feature="ask"}[15m])) > 0
for: 15m
labels: {severity: page}
annotations:
summary: "llm_service RAG returning zero retrieval hits — pipeline broken?"
- alert: LLMAllAbstaining
expr: |
sum(rate(llm_outcomes_total{outcome="refused"}[30m])) by (model_key)
/
sum(rate(llm_outcomes_total[30m])) by (model_key)
> 0.8
for: 30m
labels: {severity: ticket}
annotations:
summary: "llm_service {{ $labels.model_key }} refusing >80% of requests"
- alert: LLMFallbacksElevated
expr: |
sum(rate(llm_fallbacks_total[30m])) by (from_model, to_model)
>
3 * sum(rate(llm_fallbacks_total[30m] offset 1d)) by (from_model, to_model)
for: 30m
labels: {severity: ticket}
annotations:
summary: "llm_service fallbacks {{ $labels.from_model }} -> {{ $labels.to_model }} at 3x yesterday's rate — primary degraded?"
- name: llm_service.drift
rules:
# A served_model label value with real traffic today that had ~none in
# the week before yesterday = the provider moved the alias to a new
# snapshot. `unless` drops label sets seen in the baseline window, so
# only genuinely NEW (or revived) snapshots fire. Tune the >20 floor to
# your traffic; low-volume features may want a lower bar or a longer window.
- alert: LLMServedModelShift
expr: |
sum by (model_key, served_model) (increase(llm_served_model_total[1d])) > 20
unless
sum by (model_key, served_model) (increase(llm_served_model_total[7d] offset 1d)) > 0
labels: {severity: ticket}
annotations:
summary: "llm_service {{ $labels.model_key }} now served by {{ $labels.served_model }} — provider snapshot moved?"
runbook: "https://wiki.internal/llm-service/runbooks/model-shift"Notes on the rules:
for:duration matters.for: 5mmeans "the condition must hold continuously for 5 minutes before firing" — it filters transient spikes. Longerfor= fewer false positives, slower detection. Tune per alert.offsetin the cost spike rule compares current rate to the same hour yesterday — a simple, dependency-free anomaly baseline. (6.4 shows a smarter version.)- Silent-failure alerts use
== 0or high ratios, not error rates. "Zero retrieval hits" and ">80% refusals" catch the cases where the service looks healthy but isn't doing its job.
6.3 Silent-failure alerts#
The most dangerous LLM failures return success. Your alert set must include conditions that are too quiet:
| Silent failure | Metric signal | Alert |
|---|---|---|
| Retrieval pipeline broken | rag_retrieval_hits_total rate = 0 while RAG requests are flowing |
Page — RAG is returning empty context |
| Model refusing everything | llm_outcomes_total{outcome="refused"} / total > 80% |
Ticket — prompt injection, policy change, or model regression |
| Cache dead | llm_cache_lookups_total{result="hit"} rate = 0 while lookups continue |
Ticket — cache key bug, Redis down, or TTL misconfiguration |
| All answers truncated | llm_outcomes_total{outcome="truncated"} / total > 20% |
Ticket — max_tokens too low, or model behaviour change |
| Fallbacks always firing | llm_fallbacks_total rate > baseline |
Ticket — primary provider degraded, or fallback misconfigured |
| Eval score flatlined | eval_score unchanged for 24h |
Ticket — eval pipeline broken (not necessarily quality) |
| Queue never drains | llm_queue_depth monotonically increasing |
Page — workers stuck, back-pressure failing |
| Scrape target down | up{job="llm_service"} == 0 |
Page — nothing is being measured; every metric alert is blind |
| Metrics pipeline dead, app alive | absent(llm_requests_total) while up == 1 |
Page — /metrics broken or emission stopped (6.2 llm_service.target) |
The pattern: alert on the absence of expected signal, not just the presence of bad signal. A counter that should be incrementing and isn't is as much a failure as one that increments too fast — and a series that isn't there at all is the quietest failure of all. Note the mechanics: rate() of an absent series returns an empty vector, not zero, so rate(missing[15m]) == 0 never fires. Every == 0 quiet-signal alert above only works while its series exists — pair them with the up/absent() rules in 6.2, or a dead pipeline silences the whole alert set.
6.4 Anomaly detection for cost: the z-score detector#
Fixed thresholds ("cost > $100/day") don't adapt to growth or seasonality. A z-score compares today's value to its recent history: z = (x - mean) / std. A z-score above ~3 means "unusually high for this service's own behaviour" — no absolute threshold needed.
This is pure stdlib — run it for real:
# cost_anomaly.py — z-score anomaly detection on cost PER REQUEST (stdlib only)
from __future__ import annotations
import statistics
def zscore(values: list[float], window: int = 14) -> list[float | None]:
"""Rolling z-score: how many std devs above the trailing mean is each point?
The first `window` points return None (not enough history).
Uses population std (statistics.pstdev) — for anomaly detection on your
own series, sample std (stdev) is also defensible; be consistent.
"""
out: list[float | None] = [None] * len(values)
for i in range(window, len(values)):
hist = values[i - window:i]
mean = statistics.mean(hist)
std = statistics.pstdev(hist)
out[i] = None if std == 0 else (values[i] - mean) / std
return out
def flag_anomalies(values: list[float], threshold: float = 3.0,
window: int = 14) -> list[tuple[int, float, float]]:
"""Return (index, value, z) for points exceeding the z threshold."""
zs = zscore(values, window)
return [(i, v, z) for i, (v, z) in enumerate(zip(values, zs))
if z is not None and abs(z) > threshold]
if __name__ == "__main__":
# Simulated cost PER REQUEST (USD) for llm_service: stable ~$0.004–0.005
# with weekly variation, then a spike on day 22 (a prompt regression
# doubled input tokens per call). Per-request is the right series: total
# daily cost conflates traffic growth with per-call regressions — the
# distinction this whole lesson preaches. Run the same detector per
# feature/tenant in production.
cost_per_request = [
0.00421, 0.00453, 0.00389, 0.00512, 0.00478, 0.00445, 0.00496, # week 1
0.00432, 0.00467, 0.00413, 0.00521, 0.00489, 0.00451, 0.00504, # week 2
0.00448, 0.00472, 0.00435, 0.00518, 0.00493, 0.00460, 0.00509, # week 3
0.00884, # day 22: spike!
0.00912, # day 23: still high
0.00471, 0.00498, 0.00456, 0.00513, # recovered
]
print("Cost per request (USD):")
flagged = {a[0] for a in flag_anomalies(cost_per_request)}
for i, v in enumerate(cost_per_request):
marker = " <-- ANOMALY" if i in flagged else ""
print(f" day {i+1:2d}: ${v:.5f}{marker}")
anomalies = flag_anomalies(cost_per_request)
print(f"\nAnomalies (|z| > 3.0, window=14):")
for i, v, z in anomalies:
print(f" day {i+1}: ${v:.5f} (z={z:.1f})")Cost per request (USD):
day 1: $0.00421
day 2: $0.00453
day 3: $0.00389
day 4: $0.00512
day 5: $0.00478
day 6: $0.00445
day 7: $0.00496
day 8: $0.00432
day 9: $0.00467
day 10: $0.00413
day 11: $0.00521
day 12: $0.00489
day 13: $0.00451
day 14: $0.00504
day 15: $0.00448
day 16: $0.00472
day 17: $0.00435
day 18: $0.00518
day 19: $0.00493
day 20: $0.00460
day 21: $0.00509
day 22: $0.00884 <-- ANOMALY
day 23: $0.00912 <-- ANOMALY
day 24: $0.00471
day 25: $0.00498
day 26: $0.00456
day 27: $0.00513
Anomalies (|z| > 3.0, window=14):
day 22: $0.00884 (z=12.5)
day 23: $0.00912 (z=3.7)The detector catches the spike on day 22 — the first anomalous day — not day 23. That's the point: by the time a human notices a doubled per-request cost, you've already spent two days of budget. The z-score flags it on day one. In production you'd run the same detector per feature (and per tenant_tier) on the llm_cost_per_request_usd histogram's daily mean — a spike in one feature hides inside a healthy global average.
6.5 Synthetic probes and canary requests#
Metrics tell you about traffic you have. A synthetic probe generates traffic you control — a fixed request sent on a schedule, measuring whether the service works end-to-end. This catches failures that real traffic might not: a dead provider key, a broken prompt, a stalled queue — before users hit them.
The probe for llm_service is deliberately minimal: hit /health, then (if configured) send a tiny LLM request and check it returns a parseable response within a deadline. Pure-local version with a fake service:
# probe.py — synthetic probe for llm_service (stdlib only)
"""Probe: check service health and LLM path end-to-end.
Usage against a real deployment:
python probe.py --url https://llm-service.internal --api-key $KEY
This demo uses a FakeService so it runs with no network:
python probe.py --demo
"""
from __future__ import annotations
import json
import sys
import time
import urllib.request
import urllib.error
class ProbeResult:
def __init__(self, name: str, ok: bool, latency_ms: float, detail: str = ""):
self.name, self.ok, self.latency_ms, self.detail = name, ok, latency_ms, detail
def __repr__(self):
status = "OK " if self.ok else "FAIL"
return f"[{status}] {self.name}: {self.latency_ms:.0f}ms {self.detail}"
def probe_health(base_url: str, timeout: float = 5.0) -> ProbeResult:
"""GET /health — is the process alive and not overloaded?"""
t0 = time.monotonic()
try:
with urllib.request.urlopen(f"{base_url}/health", timeout=timeout) as r:
body = json.loads(r.read())
ok = r.status == 200 and body.get("status") == "ok"
return ProbeResult("health", ok, (time.monotonic() - t0) * 1000,
f"status={body.get('status')}")
except Exception as e:
return ProbeResult("health", False, (time.monotonic() - t0) * 1000,
f"{type(e).__name__}: {e}")
def probe_llm(base_url: str, api_key: str | None = None,
timeout: float = 30.0) -> ProbeResult:
"""POST /ask with a fixed tiny prompt — does the LLM path work end-to-end?
This is the canary: a fixed input means a fixed expected output shape.
We don't assert content (models vary); we assert structure and latency.
"""
t0 = time.monotonic()
payload = json.dumps({
"feature": "ask",
"messages": [{"role": "user", "content": "Reply with exactly: OK"}],
"max_tokens": 10,
}).encode()
req = urllib.request.Request(
f"{base_url}/ask", data=payload,
headers={"Content-Type": "application/json",
**({"Authorization": f"Bearer {api_key}"} if api_key else {})},
method="POST",
)
try:
with urllib.request.urlopen(req, timeout=timeout) as r:
body = json.loads(r.read())
has_text = bool(body.get("text") or body.get("content"))
ok = r.status == 200 and has_text
return ProbeResult("llm_call", ok, (time.monotonic() - t0) * 1000,
f"status={r.status} has_text={has_text}")
except urllib.error.HTTPError as e:
return ProbeResult("llm_call", False, (time.monotonic() - t0) * 1000,
f"HTTP {e.code}")
except Exception as e:
return ProbeResult("llm_call", False, (time.monotonic() - t0) * 1000,
f"{type(e).__name__}: {e}")
def run_probes(base_url: str, api_key: str | None = None) -> list[ProbeResult]:
results = [probe_health(base_url)]
# Only probe LLM if health passed — don't pile onto a dead service
if results[0].ok:
results.append(probe_llm(base_url, api_key))
return results
# --- Demo with a fake service (no network) ---------------------------------
class FakeService:
"""Stands in for llm_service: /health always OK, /ask returns canned text."""
def __init__(self, healthy: bool = True, llm_ok: bool = True):
self.healthy, self.llm_ok = healthy, llm_ok
def handle(self, path: str, payload: dict | None = None) -> tuple[int, dict]:
if path == "/health":
return (200, {"status": "ok" if self.healthy else "degraded"})
if path == "/ask":
if not self.llm_ok:
return (503, {"error": "provider unavailable"})
return (200, {"text": "OK", "model": "fake-1"})
return (404, {"error": "not found"})
def demo() -> None:
"""Mirror the two probe checks against FakeService instances — real output, no net.
probe_health() and probe_llm() call urllib, so they need a live URL; this demo
repeats their pass/fail rules on the fake's canned replies instead."""
for label, svc in [
("healthy service", FakeService(healthy=True, llm_ok=True)),
("LLM provider down", FakeService(healthy=True, llm_ok=False)),
("service degraded", FakeService(healthy=False, llm_ok=True)),
]:
print(f"--- {label} ---")
# Same rules as probe_health/probe_llm, applied to the fake's replies
health_status, health_body = svc.handle("/health")
health_ok = health_status == 200 and health_body.get("status") == "ok"
print(f" health: {'OK' if health_ok else 'FAIL'}")
if health_ok:
ask_status, ask_body = svc.handle("/ask", {})
llm_ok = ask_status == 200 and bool(ask_body.get("text"))
print(f" llm_call: {'OK' if llm_ok else 'FAIL'} (HTTP {ask_status})")
print()
if __name__ == "__main__":
if "--demo" in sys.argv:
demo()
else:
import argparse
p = argparse.ArgumentParser()
p.add_argument("--url", required=True)
p.add_argument("--api-key", default=None)
args = p.parse_args()
for r in run_probes(args.url, args.api_key):
print(r)--- healthy service ---
health: OK
llm_call: OK (HTTP 200)
--- LLM provider down ---
health: OK
llm_call: FAIL (HTTP 503)
--- service degraded ---
health: FAILThe demo shows the probe's value: in the "LLM provider down" case, /health passes (the process is alive) but the LLM call fails — exactly the gap that metrics alone miss if you only alert on process health. Run this on a schedule (cron, Kubernetes CronJob, or your CI) and feed failures into your alerting pipeline.
6.6 Routing, runbooks and alert fatigue#
Routing decides who gets notified and how. The minimum viable setup:
- Page → PagerDuty/Opsgenie/phone call → on-call engineer
- Ticket → Jira/Linear/GitHub issue → backlog
- Dashboard → Grafana → anyone looking
Every alert annotation should include a runbook link — a wiki page or doc that tells the responder what to check first. The runbook for LLMHighErrorRate might say: "1. Check provider status pages (Part 7). 2. Check llm_errors_total by error_class — is it rate_limit (provider throttling → check 03.8 Part 9), timeout (provider slow → check status), or invalid_output (model regression → check eval scores)? 3. Check recent deploys on the dashboard annotations. 4. If provider issue, enable fallback (11C.3); if your bug, roll back."
Alert fatigue is the chronic condition of too many alerts. Symptoms: pages ignored, MTTR creeping up, "it's probably nothing" as the default response. Cures:
- Measure alert precision — what fraction of pages led to a real action? Below ~50% and your thresholds are too tight.
- Tune
for:durations — most alerts benefit from 5–15 minutes of sustained condition. - Group related alerts — one "llm_service degraded" page with links to the specific failing metric beats five separate pages for the same root cause.
- Review quarterly — delete alerts that never fired or always fired; they carry no information.
6.7 Status pages#
Your users deserve a status page too — status.yourservice.com showing whether the LLM features are up. The components map to your SLOs: "Ask AI" (the chat feature), "Document Extraction", "Summarization". When an alert fires, update the status page manually or automatically — users checking the page during an incident is itself a signal (and reduces support load). Tools: Atlassian Statuspage, Instatus, Better Stack, or a simple static page your deploy pipeline updates. The key discipline: only declare incidents you can verify — a status page that says "all operational" during a real outage destroys trust faster than no status page at all.
Part 7: Provider health#
Reference
Your service's metrics tell you that calls are failing; provider health tells you why — and whether the fix is yours or theirs.
7.1 Watching the providers' status pages and APIs#
Each provider publishes a status page; the four you use are:
| Provider | Status page | Machine-readable? |
|---|---|---|
| OpenAI | status.openai.com |
Yes — Atlassian Statuspage API at /api/v2/status.json and /api/v2/summary.json |
| Anthropic (Claude) | status.claude.com (status.anthropic.com redirects here) |
Yes — same Statuspage API shape |
| Google (Gemini) | status.cloud.google.com |
Yes — different API shape (Google Service Health) |
| OpenRouter | status.openrouter.ai |
Partial — Datadog-powered status page; its public JSON is not the Statuspage shape (/api/v2/status.json returns 403, verified Nov 2026). Poll the page or rely on your own error metrics |
The Statuspage JSON API returns the overall indicator (none, minor, major, critical) and a component list with per-component status — exactly what a probe needs. A minimal poller (reference — don't run against production without rate-limit respect):
# provider_health.py — poll provider status pages (stdlib only)
import json
import urllib.request
# OpenRouter's status.openrouter.ai is Datadog-powered and does NOT serve the
# Statuspage JSON API — deliberately absent from STATUSPAGES. Check the page
# manually, or (better) let your own error/latency metrics be the signal.
STATUSPAGES = {
"openai": "https://status.openai.com/api/v2/status.json",
"anthropic": "https://status.claude.com/api/v2/status.json",
}
def check_provider(name: str, url: str) -> dict:
try:
with urllib.request.urlopen(url, timeout=10) as r:
data = json.loads(r.read())
status = data.get("status", {})
return {"provider": name, "indicator": status.get("indicator", "unknown"),
"description": status.get("description", "")}
except Exception as e:
return {"provider": name, "indicator": "unreachable", "description": str(e)}
if __name__ == "__main__":
for name, url in STATUSPAGES.items():
print(check_provider(name, url))Feed this into your dashboard as a "provider health" row of stat panels, and into alerting as a correlation signal: when your error rate spikes, the first dashboard check is "is the provider also reporting an incident?" — a provider incident changes the response from "debug our code" to "enable fallback and wait".
7.2 Your own leading indicators#
The metrics that predict a provider problem before the status page does:
- Error rate by class — a spike in
http_5xxortimeoutacross all models on one provider points upstream; the same spike on one model points at that model. - Latency drift — TTFT p95 creeping up over hours is often the earliest provider-degradation signal.
- Rate-limit headroom — the
x-ratelimit-remaining-*headers (03.8, 9.3) as gauges: when remaining quota approaches zero, you're about to hit 429s — scale back or enable fallback before the errors start. - Retry rate —
llm_retries_totalclimbing means the SDK is absorbing failures you can't see; sustained retries are a leading indicator of degradation.
7.3 Quotas, spend limits and incident correlation#
Two provider-side controls matter for operations:
- Spend limits / quotas — OpenAI, Anthropic and Google all offer budget caps and usage tiers (03.7, Part 13 covers the usage/cost APIs for reconciliation). Set a hard monthly cap per provider as a circuit breaker against runaway spend — a bug that loops calls shouldn't be able to spend the quarter's budget in an hour.
- Incident correlation — when your
llm_errors_total{provider="openai"}spikes at 14:32 andstatus.openai.comdeclares an incident at 14:35, that's correlation, not coincidence. Log provider status transitions as annotations on your dashboards so the timeline is visible during postmortems.
The boundary with 11C.3: this lesson covers detecting provider trouble; 11C.3 covers responding to it (circuit breakers, fallback chains, multi-provider failover). The metrics you emit here — error rate per provider, latency per provider, rate-limit headroom — are exactly the signals 11C.3's circuit breakers consume.
Part 8: Capacity and load#
Deep-dive
8.1 What "load" means for an LLM service#
Load testing a CRUD API means "how many requests per second before it falls over?" Load testing an LLM service has three extra dimensions:
- Concurrency ≠ request rate. An LLM call holds a connection open for seconds to minutes (especially streaming). 100 concurrent streams at 30s each is very different from 100 RPS of instant responses. Your bottleneck is often concurrent connections, not requests-per-second.
- Token throughput is the real capacity. Providers rate-limit by tokens-per-minute (TPM) and requests-per-minute (RPM) (03.8, 9.1–9.2). Your capacity is bounded by
min(your worker capacity, provider TPM/RPM limits, your budget). - Cost scales with load. A load test that doubles traffic doubles spend. Know your per-request cost before you test — a "harmless" 10× load test can cost real money.
8.2 Load testing: Locust reference#
Locust (version 2.47.0 as of November 2026, MIT licensed) is the pragmatic choice for Python teams — tests are plain Python, and it handles thousands of concurrent greenlets. k6 (Grafana's Go-based tool) is the alternative if you want a single binary and JS scripting.
A minimal Locustfile for llm_service (reference — run against staging, not production):
# locustfile.py — load test for llm_service
from locust import HttpUser, task, between
class LLMUser(HttpUser):
wait_time = between(1, 3) # think time between requests
host = "https://llm-service-staging.example.com"
def on_start(self):
# Auth once per simulated user
self.client.post("/auth/token", json={"user": "loadtest"})
@task(3)
def ask(self):
"""Interactive chat — the common case."""
self.client.post("/ask", json={
"feature": "ask",
"messages": [{"role": "user", "content": "What is the capital of France?"}],
"stream": False,
"max_tokens": 100,
}, timeout=90)
@task(1)
def extract(self):
"""Structured extraction — heavier, slower."""
self.client.post("/extract", json={
"feature": "extract",
"document": "Invoice INV-2042: 3 items, total $1,247.50",
}, timeout=120)
# For streaming endpoints, use self.client.stream("POST", ...) — but note
# Locust's HttpSession doesn't natively handle SSE; you'll need a custom
# client or accept that streaming load is tested via the non-stream path.Run it:
locust -f locustfile.py --users 50 --spawn-rate 5 --run-time 10m --headlessWhat to watch during the test (link to your dashboards): TTFT p95, total-duration p95, error rate, in-flight requests vs worker capacity, queue depth, provider 429 rate, and cost burn rate.
8.3 Capacity planning arithmetic#
The formula that matters: required concurrency = arrival rate × average service time (Little's Law). For llm_service:
concurrent_calls_needed = requests_per_second × avg_call_secondsExample (illustrative numbers): 5 req/s × 8s average call = 40 concurrent calls in flight. If each call uses one async worker slot and you have 100 slots, you have headroom; if calls queue, queue depth grows linearly with overload.
For streaming: a 30-second stream at 5 req/s = 150 concurrent SSE connections. That's a connection capacity problem (file descriptors, proxy limits, provider connection pools) as much as a compute problem.
For provider limits: if your peak is 5 req/s × 2,000 tokens avg = 10,000 TPM, and your provider tier allows 500,000 TPM, you're at 2% utilisation — plenty of headroom. If you're at 80%+, you're one traffic spike from 429s.
8.4 Tail latency under load and back-pressure#
Two phenomena to plan for:
- Tail latency grows with load. p50 might stay flat while p99 doubles — queuing theory guarantees this. Your SLOs should be on percentiles, not averages, and your load tests should measure p99/p999, not just throughput.
- Back-pressure is a feature, not a bug. When you exceed capacity, the system should shed load gracefully — return 429 with
Retry-After, queue with a depth limit and timeout, or degrade to a cheaper model — rather than accept everything and collapse. 11C.1 owns the queue/worker architecture; 11C.3 owns the circuit breakers. Your metrics (llm_queue_depth,llm_inflight_requests) are how you see back-pressure working vs failing.
Part 9: Cost monitoring#
Deep-dive
9.1 Budgets, thresholds and forecasts#
Cost monitoring has three layers, each catching a different failure:
| Layer | Mechanism | Catches |
|---|---|---|
| Real-time | llm_cost_usd_total rate alerts (6.2 LLMCostSpike) |
Sudden spikes — prompt regression, retry storm, abuse |
| Daily/weekly | Budget thresholds — "daily spend > $X" alerts | Gradual drift — traffic growth, model upgrade, cache decay |
| Forecast | Linear regression on trailing 7-day spend → projected month-end | "At this rate you'll exceed budget by Friday" — time to act before the cap hits |
The forecast is the most valuable and most neglected. A simple version: take the last 7 days of daily cost, fit a least-squares line (slope = Σ(x−x̄)(y−ȳ) / Σ(x−x̄)², ~6 lines of stdlib), project to month-end, alert if projection > budget × 0.9. 11B.1 owns the full forecast calculator (forecast_monthly() in llm_service/economics.py); the same z-score machinery from 6.4 generalises the idea (detect the trend, not just the spike).
9.2 Per-tenant caps and showback#
For multi-tenant llm_service, cost attribution isn't optional — it's how you price, bill and prevent abuse:
- Showback — report cost per tenant per feature per day (the
llm_cost_usd_total{feature, model_key}counter sliced by tenant tier or hashed tenant ID). Answers "which customer is expensive?" - Caps — hard limits per tenant: "tenant X may not exceed $50/day". Enforced in the
before()hook (03.11) — a budget gate that raisesQuotaExceededwhen the tenant's daily counter exceeds the cap. The hook'sfail_closeddesign means the gate stops the call, not just logs it. - Anomaly per tenant — the z-score detector (6.4) applied per
tenant_tieror hashed tenant: "tenant Y's cost per request doubled this week" catches a tenant-specific problem (a runaway agent loop, a misconfigured integration) that global metrics miss.
9.3 Reconciliation: metrics vs invoice#
Your llm_cost_usd_total counter is your estimate; the provider's invoice is truth. 03.7, Part 13 covers the provider cost APIs (OpenAI Costs API, Anthropic Usage and Cost Analytics, OpenRouter generation costs) for reconciliation. The operational rule: reconcile weekly, alert on divergence >5%. A persistent gap means a bug in your cost tracking (a token kind you're not counting, a price-table version that's stale, a provider billing you for something you didn't record) — and cost bugs compound silently until the invoice arrives.
9.4 The decision table: which metrics stack#
| Your situation | Backend | Why |
|---|---|---|
| Standard Prometheus + Grafana stack (most teams) | PrometheusBackend + /metrics scrape |
The de facto standard; pull model survives restarts and gives you up{}/absent() for free |
| OTel-native platform (collector → vendor backend) | OTel metrics SDK (3.5) | One instrumentation stack with your traces; push model suits ephemeral targets |
| Tests, notebooks, local dev | MemoryBackend + snapshot()/exposition() |
Zero deps, JSON-debuggable, every percentile computable later |
| Serverless / ephemeral instances | OTel push (OTLP) or StatsD | Pull scraping struggles when targets come and go; push fits the lifecycle |
| One box, no Prometheus | StatsD or Datadog agent | Fire-and-forget UDP; nothing to secure or scrape |
| Vendor-locked shop already on a platform | Platform-native metrics (Langfuse scores, Datadog LLM obs) | Zero new infra — but export a Prometheus-compatible feed anyway so alerts survive a vendor change |
9.5 The failure gallery#
| Failure | What it looks like | Catch it with |
|---|---|---|
| Cardinality explosion | Prometheus memory/CPU melts; queries time out | 1.5 label discipline; _coerce bounded vocabularies in metrics.py |
| Counter reset on deploy | rate() spike/dip at every restart |
Counters are monotonic by design — never "fix" them into gauges (2.1) |
| Mis-tuned histogram buckets | histogram_quantile returns bucket-edge garbage |
2.3's tuning loop; check _bucket counts after a week of traffic |
/metrics down, app fine |
Dashboard flatlines; up == 1 but no series |
llm_service.target group's absent() alert (6.2) |
| Alert on an absent series | rate(missing[15m]) == 0 silently never fires |
Empty vector ≠ zero — pair quiet-signal alerts with up/absent() (6.3) |
| Gauge leak on exception | llm_inflight_requests only climbs |
record_request_end on every path — the middleware's try/except (3.4) |
| Exemplar trace_id is really call_id | Exemplars link nowhere until OTel is wired | The _trace_id placeholder comment (3.3); wire OTel context per 11A.1 |
| Cost counter drifts from invoice | llm_cost_usd_total ≠ provider invoice |
Monthly reconciliation (9.3); price-table drift checks (11B.1) |
| Histogram buckets ignored | Cost/TTFT percentiles meaningless | spec.buckets plumbed through observe() — each metric keeps its own buckets (3.2) |
| Finish-reason vocabulary drift | truncated/content_filter counted as ok |
_FINISH_OUTCOME maps the real FinishReason enum (3.3) |
| Error class collapse | Every failure lands on result="other" |
error_class_for maps the CamelCase error_type taxonomy (3.2) |
| Fallbacks invisible | llm_fallbacks_total flat during a provider outage |
Per-call_id model-change detection in attempt() (3.3) |
| MemoryBackend snapshot crashes | /metrics debug path 500s on json.dumps |
String label keys in snapshot() (3.2) |
| Provider silently swaps snapshot | Quality drift with all operational metrics green | llm_served_model_total + LLMServedModelShift (3.2, 6.2) |
What this means for you#
You now own the metrics → SLO → alert loop end to end: the catalogue enforces bounded labels, the hooks turn every call into counters and histograms, the SLO math turns ratios into budgets, and the alert rules turn budgets into pages. The durable takeaways: measure symptoms (error ratio, TTFT, cost per request), alert on burn rate rather than thresholds, and never trust a quiet signal until you've proven the series exists. The same llm_service/metrics.py feeds 11B.3's cache hit-rate panels, 11B.1's cost levers, 11C.3's circuit breakers and 11C.1's queue/back-pressure work — and 11C.2/11C.4 turn these alerts into eval gates and runbooks. If you remember one thing: a metric you can't trace back to a trace, a budget and a runbook is a graph, not observability.
Common misconceptions#
| Misconception | Reality |
|---|---|
| "Error rate is the only metric that matters." | LLM services fail quietly: refusals, truncations, wrong answers and cost spikes all return HTTP 200. You need outcome-based metrics, quality scores and cost counters alongside error rate. |
| "Average latency tells me if it's slow." | LLM latency is bimodal (fast chat vs slow reasoning). p50 can look great while p99 is unacceptable. Use histograms and percentiles, and track TTFT separately from total duration for streaming. |
"I can put user_id or request_id as a metric label." |
That's unbounded cardinality — a million users means a million time series and a melted Prometheus. Those IDs belong in traces and logs, not metrics. Use bounded labels (feature, model, outcome, tenant_tier). |
| "A counter that resets on restart is broken." | Counters are supposed to be monotonic; Prometheus's rate() and increase() handle resets correctly. If a value can go down, it's a gauge — don't misuse the type. |
| "My SLO is 'the API stays up'." | For LLM services, "up" isn't enough — you need SLIs for latency, quality and cost too. A service can be 100% available and 0% useful. Quality SLOs need online evals. |
| "Alerting on error rate > 1% is enough." | That fires on noise and misses slow burns. Use multi-window multi-burn-rate alerting (SRE Workbook ch. 5) to distinguish "budget threatened now" from "budget trending down". |
| "Dashboards are for looking at, alerts are for paging." | Dashboards answer questions during incidents and reviews; alerts are only for conditions that need action now. If you can't write a runbook for it, it's a dashboard panel. |
| "The provider's status page tells me when they're down." | Status pages lag reality — they declare incidents after users notice. Your own error rate, latency and TTFT metrics are the ground truth; the status page is corroboration. |
| "Cost anomalies need machine learning." | A z-score on trailing history catches most cost spikes. ML anomaly detection is for when you have enough data and enough anomalies to justify it — start simple. |
| "Load testing means hitting it with as many requests as possible." | For LLM services, concurrency (long-lived connections) and token throughput matter more than raw RPS. And every load test costs real money in API calls — know your per-request cost first. |
| "Prometheus and Grafana are the only options." | They're the most common open-source stack, but Datadog, cloud-native monitoring, and observability platforms (Langfuse, Phoenix) all work. The discipline — metric names, labels, SLIs, alerts — transfers unchanged. |
| "I can figure out my SLOs by copying Google or Netflix." | SLOs are product-specific: they encode your users' tolerance for badness and your cost of failure. Start from your error-cost analysis, not someone else's targets. |
Key takeaways#
- Metrics for LLM services are different from classic web metrics. Errors aren't the expensive failures — refusals, truncations, wrong answers and cost spikes all return HTTP 200. You need outcome-based metrics, quality scores and cost counters alongside error rate.
- The catalogue is organised by question: rate, errors by class, latency percentiles (TTFT + total + inter-token), token throughput, queue/concurrency, rate-limit hits, retries, tokens and cost by kind, cache hit rates, fallback rates, refusal/abstention rates, guardrail triggers, quality scores, feedback rates, drift indicators.
- RED, USE and golden signals adapt but don't suffice. Add cost and quality as first-class signals. Duration is a distribution (percentiles), not a number — and for streaming you need TTFT and total separately.
- Cardinality is the trap.
user_id,request_id,session_idand rawtenant_idnever go on metrics — they're unbounded. Metrics answer "how is the system"; traces and logs answer "what did this request do". prometheus_clientis the pragmatic default (0.26.0 as of Nov 2026): counters, gauges, histograms with custom buckets for LLM latencies (seconds to minutes), exemplars linking spikes to traces. OTel metrics (1.45.2) is the vendor-neutral alternative.llm_service/metrics.pyuses a backend protocol —PrometheusBackendfor production,MemoryBackendfor tests — so everything is unit-testable without Prometheus running. TheServiceMetricsHookplugs intoprovider_agnostic's hook points.- SLIs are ratios with a goodness definition; SLOs are targets; error budgets are the complement. For LLM services, "good" includes usable answers, latency bounds, quality pass rates and cost efficiency — not just "didn't crash".
- Multi-window multi-burn-rate alerting (SRE Workbook ch. 5) is the right way to alert on SLOs: page at 14.4× burn over 1h+5m, page at 6× over 6h+30m, ticket at 1× over 3d+6h.
- Quality SLOs need online evals — you can't compute "was the answer good" per-request cheaply enough to alert on every call. Sample, score with a calibrated judge, aggregate into
eval_score, alert on trends. - Dashboards are question-answering surfaces — one per question-set (health, cost, quality, pipeline internals, per-tenant), provisioned as code, annotated with deploys/prompt/model changes.
- Alerts must be actionable, symptom-based, thresholded with hysteresis, and routed by severity. Silent-failure alerts (zero retrieval hits, all abstaining, cache dead) catch what error-rate alerts miss.
- Provider health is monitored, not assumed. Status pages corroborate; your own metrics are ground truth. Rate-limit headroom gauges predict 429s before they happen.
- Capacity for LLM services = concurrency × service time × token throughput, bounded by provider TPM/RPM limits and budget. Load tests cost real money.
- Cost monitoring has three layers: real-time spike alerts, daily/weekly budget thresholds, and forecast (project month-end spend). Per-tenant caps and z-score anomaly detection catch what global metrics miss.
Terms introduced in this lesson#
| Term | One-line definition |
|---|---|
| SLI (service level indicator) | A ratio of good events to total events, measured over a window |
| SLO (service level objective) | A target for an SLI over a compliance period (e.g. 99.9% over 30 days) |
| Error budget | The allowed badness complement of an SLO: (1 - SLO) × window |
| Burn rate | How fast error budget is being consumed relative to the allowed rate |
| Multi-window multi-burn-rate alerting | Alerting that requires high burn over both long and short windows to avoid noise |
| Cardinality | The number of distinct label-value combinations — unbounded labels melt metrics systems |
| Time series | A metric's values over time for one label combination |
| Counter | A monotonically increasing metric (requests, tokens, cost) |
| Gauge | A metric that goes up and down (queue depth, in-flight requests, scores) |
| Histogram | A metric that counts observations into buckets for percentile estimation |
| Summary | A metric with client-side quantiles — can't be aggregated across instances |
| Exemplar | A trace ID attached to a metric observation, linking a spike to the exact trace |
| OpenMetrics | The Prometheus exposition format that supports exemplars and native histograms |
| Recording rule | A Prometheus rule that pre-computes a query result as a new metric |
| Alert rule | A Prometheus/Grafana rule that fires a notification when a condition holds |
for: duration |
How long a condition must hold before an alert fires — filters flapping |
| Annotation | A marker on a dashboard chart showing when something changed (deploy, prompt, model) |
| Dashboard as code | Dashboards defined in JSON/YAML files, provisioned into Grafana, versioned in git |
| Synthetic probe | A scheduled, controlled request that tests the service end-to-end |
| Canary request | A fixed probe request with known expected behaviour, run continuously |
| Status page | A public page showing service health components and incidents |
| Statuspage API | Atlassian's JSON API for machine-readable status (/api/v2/status.json) |
| Rate-limit headroom | Remaining provider quota from x-ratelimit-remaining-* headers, as a gauge |
| Little's Law | concurrency = arrival rate × service time — the capacity planning formula |
| Back-pressure | Shedding or queueing load when capacity is exceeded, rather than collapsing |
| Z-score | (value - mean) / std — a dimensionless anomaly score relative to recent history |
| Showback | Reporting cost per tenant/feature without necessarily billing them |
| Chargeback | Actually billing tenants for their LLM usage |
| Reconciliation | Comparing your cost metrics against the provider's invoice to find discrepancies |
| TTFT (time to first token) | Latency from request sent to first content token in a streaming response |
Served model (resolved_model) |
The concrete model snapshot the provider reports it ran — differs from the alias you requested; a change is silent provider drift |
| Inter-token latency | The gap between tokens during streaming decode — reveals provider-side degradation |
| Token throughput | Tokens per second — the real capacity unit for LLM services |
| Outcome taxonomy | The classification of call results: ok, refused, blocked, truncated, invalid, failed, abandoned, other |
| Agent run | One pass of the agent loop from task to final answer or stop; the unit for steps, tool errors and cost per task |
| Steps per run | The number of loop iterations (model call plus tool calls) in one agent run, recorded as a histogram |
| Tool success ratio / tool error rate | The SLI "ok tool calls over counted calls" per tool, and its complement; denied calls are excluded |
| Cost per task (online) | Total spend divided by completed agent runs, with its p95 tail; the offline version is cost per successful task (10A.7) |
| Step cap | The hard limit on loop iterations; the share of runs that hit it is a loop-health signal |
All terms are also collected in the glossary.
Exercises#
-
Metric catalogue audit: Take the
_CATALOGUEdict fromllm_service/metrics.pyand add three metrics your project needs that aren't there (e.g.llm_inter_token_seconds— the streaming decode-gap histogram 1.2 says high-throughput deployments deserve,rag_retrieval_latency_seconds,llm_eval_cases_total). For each, write the_MetricSpecand explain why the labels you chose are bounded. -
Cardinality hunt: Review your existing observability code (or the
provider_agnostichooks). Find any place where a per-request value (user ID, request ID, prompt hash, session ID) could end up as a metric label. Explain what would happen to Prometheus at 1M users and how you'd fix it. -
Bucket tuning: The
LLM_LATENCY_BUCKETSinmetrics.pyare[0.5, 1, 2.5, 5, 10, 20, 30, 45, 60, 90, 120, 180, 300]. If your service only ever calls small models with <10s calls, which buckets would you remove? If you add reasoning models with 5-minute calls, what changes? -
SLO document: Write a one-page SLO document for a feature you actually run (or a hypothetical "support ticket auto-responder"). Define 3 SLIs (availability, latency, quality), set targets, and write the PromQL for each.
-
Burn-rate alert: Using the
slo_calc.pycode, compute the burn rate for your SLO-1 availability target at 99.5% when the observed error rate is 0.3%. Does it page (14.4× threshold)? What's the time to exhaust? -
Z-score detector: Run
cost_anomaly.pywith a different anomaly pattern — e.g. a gradual 2-week cost creep instead of a spike. Does the z-score catch it? Why or why not? What would you add to catch slow drift? -
Probe design: Write a probe for a different endpoint in your service (e.g.
/extractfor document extraction). What fixed input would you use? What would you assert — structure, latency, or content? -
Dashboard panel: Write the PromQL for a "cost per request by feature" panel:
sum(rate(llm_cost_usd_total[5m])) by (feature) / sum(rate(llm_requests_total[5m])) by (feature). Explain why this is a ratio of rates, not a rate of ratios. -
Silent failure: Pick one silent-failure scenario from 6.3 (e.g. "all answers abstaining") and write the PromQL alert for it. What
for:duration would you choose and why? -
Provider health: Modify
provider_health.pyto also checkstatus.cloud.google.com(Google's API shape differs — you'll need to research the endpoint). What does the response look like?
Hints for the exercises
- A histogram needs
buckets; a counter needs only labels. Bounded labels come from enums in your code (feature,backend,result), never from request data. Remember to add the metric to_CATALOGUEorMetrics._checkraisesKeyError. - Typical hits: a
prompt_hashorsession_idlabel on a token counter. At 1M users each metric would hold 1M series per other-label combination; the fix is to drop the label, bucket it (tenant_tier) or move the value to a trace attribute (11A.1). - With only sub-10s calls, drop 30/45/60/90/120/180/300 and add finer buckets (0.1, 0.25) near the real p50; with 5-minute reasoning calls keep 180 and 300 and add 420/600, or the tail lands in
+Infandhistogram_quantilecaps at the last finite edge. - Latency SLI as PromQL:
sum(rate(llm_request_duration_seconds_bucket{feature="ask",le="60"}[30d])) / sum(rate(llm_request_duration_seconds_count{feature="ask"}[30d]))(needs a bucket edge at your bound — here 60 s is one). Note a histogram gives you one bound at a time: "TTFT < 5s AND total < 60s" per request needs a per-request counter incremented by the service, not two histograms. - Burn = 0.003 / 0.005 = 0.6×. It does not page (below 14.4×) or even open a ticket (below 1×); at this rate the budget is never exhausted inside the 30-day window (30 / 0.6 = 50 days).
- A slow creep is absorbed by the trailing 14-day window, so z stays small. Add an absolute budget alert (Part 9) and a trend check against a fixed baseline, e.g. today vs the same weekday four weeks ago.
- Assert structure (valid JSON, expected keys), status and latency; do not assert exact wording. Use a fixed, tiny input so the probe's own cost is negligible.
- Dividing the summed rates gives total cost per total request. A rate of ratios would average per-series ratios and weight a tiny low-traffic series the same as a huge one.
- Example:
sum(rate(llm_outcomes_total{outcome="refused"}[30m])) / sum(rate(llm_outcomes_total[30m])) > 0.8withfor: 30m; long enough to ignore a short blip, short enough to catch a bad deploy within the hour. - Google publishes incident data as JSON at
https://status.cloud.google.com/incidents.json: an array of objects with keys such asid,begin,end,service_name,affected_products,severityandstatus_impact(checked 12 November 2026; each object also carriesnumber,created,modified,external_desc,service_key,uriand affected-location lists, and the per-updatestatuslives inside itsupdatesarray, not on the incident). There is no singleindicatorfield, so decide what "unhealthy" means for you (for example: an incident with noendthat lists a Vertex AI or Gemini product).
Check yourself#
- What's the difference between a counter and a gauge, and why does it matter for
llm_inflight_requests?A counter only increases (requests, tokens, cost); a gauge goes up and down (queue depth, in-flight requests).llm_inflight_requestsmust be a gauge because it decreases when requests complete — making it a counter would breakrate()calculations. - Why can't you put
user_idas a Prometheus label? What cardinality problem does it cause?user_idis unbounded — a million users means a million time series per metric, melting Prometheus's memory and query performance. Those IDs belong in traces/logs, not metrics. - What's the difference between TTFT and total request duration, and why do you need both for streaming?TTFT is time to first token (how fast the user sees something); total duration is the whole response. A stream can have great TTFT but terrible total (fast start, slow finish) or vice versa — you need both.
- What are the four instrument types in Prometheus, and which one do you use for request latency distribution?Counter, gauge, histogram, summary. Request latency uses a histogram because you need percentiles (p50/p95/p99), and histograms can be aggregated across instances before computing quantiles.
- What is an exemplar, and what two things do you need for it to work end-to-end?An exemplar is a trace ID attached to a metric observation. You need: (1) OpenMetrics exposition format (not the default Prometheus text format), and (2) Prometheus running with
--enable-feature=exemplar-storage. - Define SLI, SLO and error budget in one sentence each.SLI = ratio of good events to total events. SLO = target for that ratio over a period. Error budget = the allowed badness complement
(1 - SLO) × window. - What is burn rate, and why is a burn rate of 14.4× significant for a 30-day SLO?Burn rate = observed bad-event ratio / allowed bad-event ratio. 14.4× means you're consuming budget 14.4 times faster than allowed — for a 30-day SLO, that exhausts the budget in ~2 days.
- Why does multi-window multi-burn-rate alerting use two time windows instead of one?Two windows distinguish sustained problems (long window confirms) from transient spikes (short window detects fast). Requiring both prevents flapping and false positives.
- What's the difference between a page and a ticket alert?A page wakes the on-call engineer now (budget threatened in hours, outage, data loss). A ticket is a backlog item for business hours (slow burn, degraded but functional).
- Name three silent-failure conditions that error-rate alerts would miss — and one failure mode no counter-based alert can see.Zero retrieval hits (pipeline broken), all answers abstaining (model/prompt regression), cache hit rate dropped to 0% (cache bug), all answers truncated (max_tokens too low), fallback always firing (primary provider degraded). The one no counter-based alert can see: the scrape target itself being down or the metrics series going absent —
rate()of a missing series is an empty vector, not zero. - What is the z-score formula, and what does a z-score of 12.5 (day 22 of the demo) mean?
z = (value - mean) / stdover a trailing window. A z-score of 12.5 means the value is 12.5 standard deviations above the recent average — extremely unusual for this service's own behaviour. - What is Little's Law, and how does it apply to LLM service capacity planning?
concurrency = arrival rate × service time. For LLM services: 5 req/s × 8s avg call = 40 concurrent calls needed. For streaming, a 30s stream at 5 req/s = 150 concurrent connections. - Why do you need per-tenant cost caps in addition to global budget alerts?Global budgets catch total spend; per-tenant caps catch one tenant's runaway usage (a buggy agent loop, a misconfigured integration) before it exhausts the global budget. Showback reports who is expensive.
- What does "dashboards as code" mean, and why is it better than click-ops dashboards?Dashboards defined in JSON/YAML files, provisioned into Grafana, versioned in git. Better than click-ops because they're reviewable, reproducible, and can't be accidentally deleted or drift from the code.
- What are the three layers of cost monitoring, and what does each catch?Real-time spike alerts (sudden cost jumps), daily/weekly budget thresholds (gradual drift), and forecast (projected month-end spend — time to act before the cap hits).
Further resources#
- Google SRE Workbook, Alerting on SLOs (ch. 5): the multi-window multi-burn-rate framework this lesson teaches — the authoritative source.
- Google SRE Book, Monitoring Distributed Systems: the four golden signals and why symptoms matter more than causes.
- Prometheus documentation: metric types, histograms and quantiles, alerting rules, exemplars.
prometheus_clientPython docs: https://prometheus.github.io/client_python/ — instrumenting, exemplars, OpenMetrics.- OpenTelemetry Python docs: https://opentelemetry.io/docs/languages/python/ — metrics API, exporters, collectors.
- Grafana provisioning: https://grafana.com/docs/grafana/latest/administration/provisioning/ — dashboards-as-code.
- Locust docs: https://docs.locust.io — load testing in Python.
- k6 docs: https://grafana.com/docs/k6/latest/ — the Go-based alternative.
- Atlassian Statuspage API: https://developer.statuspage.io/ — machine-readable status for OpenAI and Anthropic (OpenRouter's Datadog page does not expose it; Google's shape differs — Exercise 10).
- This module: 11A.1 Tracing (the traces your exemplars link to), 11B.3 Caching (cache hit metrics), 11B.1 Cost optimization (the cost playbook), 11C.3 Reliability (circuit breakers consuming your metrics), 11C.1 Deployment (queues and back-pressure), 11C.2 CI/CD (eval gates as annotations), 11C.4 Operations (runbooks and incidents).
← 11A.1 — Tracing and Observability for LLM Applications | Module 11A overview | 11A.3 — Latency Percentiles, Error Classification, Audit Logs, Session Replay, Dashboards and SLOs →