Skip to content

Lesson 35 of 40Building LLM systems

LLM Observability, Gateways and Ops

Run LLM features like real services: traces with OpenTelemetry GenAI conventions, online evals, gateways, failover, cost controls and model lifecycle.

22 min read0/3 questions

On Tuesday a product manager forwards a screenshot: the support assistant told a customer their order "ships today" without saying which order. Was it one bad answer or thousands? Did it start with Monday's prompt change, the retrieval index rebuild, or the provider's new model snapshot? The basic logging fields from AI Features in Production tell you a request happened. They do not tell you what the model saw, which documents were retrieved, which tool failed, or whether quality has been sliding for a week. This lesson is about running LLM features the way you run any production service: traced, measured, routed through one controlled entry point, and resilient when a provider has a bad day.

Traces, not log lines

A single user request to an LLM feature is rarely a single model call. It might embed the question, search a vector index, call the model, run two tools, call the model again, and validate the result. Separate log lines for each step are hard to stitch together. A trace is the whole request as a tree of timed spans, each one a step with its own attributes, all sharing a trace id.

One support request as a trace
POST /support/reply4.2s, trace rootembeddings embed-v340msvector search120msretrieve help-center180ms, 5 docschat claude-sonnet-5-51.9s, tool_useexecute_tool lookup_order300ms, error 404chat claude-sonnet-5-51.6s, end_turnvalidate reply5ms, passedroot

The root span is the user's request. Its duration is what the user felt: 4.2 seconds.

1/5

That last step is the real payoff. Traces turn "the AI is being weird" into a specific, fixable cause.

The OpenTelemetry GenAI conventions

You could invent your own attribute names, but then every dashboard, vendor and teammate needs a translation. OpenTelemetry (OTel) is the open standard for traces, metrics and logs, and its GenAI semantic conventions define shared names for LLM work. A model call span is named after the operation and model (for example chat claude-sonnet-5-5) and carries attributes such as:

AttributeWhat it holds
gen_ai.operation.namechat, embeddings, execute_tool, invoke_agent ...
gen_ai.provider.nameWhich provider served the call
gen_ai.request.model / gen_ai.response.modelThe model you asked for, and the exact one that answered
gen_ai.usage.input_tokens / gen_ai.usage.output_tokensToken counts
gen_ai.usage.cache_read.input_tokensInput tokens served from the prompt cache
gen_ai.response.finish_reasonsWhy generation stopped
gen_ai.input.messages / gen_ai.output.messagesFull content. Opt-in only, because it may hold personal data

Two warnings that save real debugging time. First, these conventions are still marked as in development, and names have changed between versions (an older gen_ai.system attribute became gen_ai.provider.name, for example). Pin the convention version your instrumentation emits and check the current spec before building dashboards on it. Second, providers count tokens differently. The convention says input tokens include cached tokens, while some APIs (Anthropic's among them) report cache reads and cache writes separately from input_tokens. Add them up before you record, or your cost dashboards will be wrong in a way nobody notices.

tracing.py
from opentelemetry import trace
 
tracer = trace.get_tracer("support-assistant")
 
def answer(question, prompt_version):
    with tracer.start_as_current_span(
        "chat claude-sonnet-5-5", kind=trace.SpanKind.CLIENT
    ) as span:
        span.set_attribute("gen_ai.operation.name", "chat")
        span.set_attribute("gen_ai.provider.name", "anthropic")
        span.set_attribute("gen_ai.request.model", "claude-sonnet-5-5")
        span.set_attribute("app.prompt.version", prompt_version)  # your own namespace
 
        response = client.messages.create(
            model="claude-sonnet-5-5",
            max_tokens=2000,
            messages=[{"role": "user", "content": question}],
        )
 
        u = response.usage
        cache_read = u.cache_read_input_tokens or 0
        cache_write = u.cache_creation_input_tokens or 0
        span.set_attribute("gen_ai.response.model", response.model)
        span.set_attribute("gen_ai.response.id", response.id)
        span.set_attribute("gen_ai.usage.input_tokens", u.input_tokens + cache_read + cache_write)
        span.set_attribute("gen_ai.usage.cache_read.input_tokens", cache_read)
        span.set_attribute("gen_ai.usage.output_tokens", u.output_tokens)
        span.set_attribute("gen_ai.response.finish_reasons", [response.stop_reason])
        return response

In practice you rarely write this by hand for every call. Instrumentation packages exist for the popular SDKs and frameworks, and most tracing vendors ship their own. Writing one span manually is still the best way to understand what those packages record, and to add what they miss: your prompt version, feature name and tenant.

What to record, and what to keep out

Beyond the standard attributes, the fields that answer real incidents are:

  • Prompt version and feature name, so a quality drop can be tied to a change.
  • Model snapshot actually served (gen_ai.response.model), since an alias can move to a new snapshot underneath you.
  • Time to first token for streamed responses (the conventions call it time to first chunk), separately from total latency. Users judge speed by when text starts appearing.
  • Retrieved document ids and scores, so you can replay what the model saw.
  • Tool errors and retries, as span status and events.
  • Tenant or user id, hashed if possible, for cost attribution and for finding one customer's requests.

Full prompt and response text is the most useful thing for debugging and the most dangerous thing to store. It contains whatever customers typed: names, addresses, health details, sometimes passwords. Treat it as a separate, controlled data stream:

  • Off by default; on for a sample, an internal tenant, or a time-boxed investigation.
  • Redact before export (structured ids with patterns, names with a PII detector), not after storage.
  • A shorter retention period than metadata, and access limited to the people who need it.
  • Deletion that reaches the trace store when a user asks for their data to be erased.

Sampling matters for cost too. Tracing every span of every request at scale gets expensive. A common pattern keeps metadata for 100% of requests, full content for a small random sample, and full content for every request that errored or got negative feedback.

Choosing a tracing tool

LLM-focused tools (Langfuse, LangSmith, Arize Phoenix, Braintrust) and general observability platforms with LLM features (Datadog LLM Observability and others) overlap heavily. Choose on criteria, not on demos:

  • OTel support: can it ingest standard OTel traces, so you are not locked into its SDK?
  • Hosting: self-hostable or open source if trace content must stay in your network (Langfuse and Phoenix can be self-hosted).
  • Evals built in: datasets, LLM judges, and a path from a bad trace to a test case.
  • Where your other telemetry lives: an LLM span that joins the same trace as your API and database spans is worth a lot during an incident.
  • Data controls: redaction, retention settings, access control, region.
Quick check
Users say answers got worse this week. Your dashboard shows normal latency and error rates. Which trace attribute is MOST likely to explain a sudden quality change with no code deploy?
Need a nudge? A hint rules out a wrong answer.

Online evaluation: grading real traffic

The eval set from the Evals lesson checks changes before release. Online evaluation keeps checking after release, on real traffic you never thought to test. The loop:

  1. Sample a fraction of production traces at random.
  2. Grade them asynchronously with code checks or an LLM judge, off the request path so users never wait.
  3. Track the pass rate per prompt version and alert when it drops.
  4. Join user feedback (thumbs down, edits, escalations) to traces.
  5. Turn bad traces into new eval cases, so the same failure is caught before the next release.

Keep two streams apart: the random sample measures quality, while feedback-selected traces feed the eval set. Mixing them inflates the failure rate, because people mostly click thumbs down on bad answers.

Python
import hashlibimport random random.seed(11) # Fake production traces: two prompt versions, v8 shipped halfway through the day.traces = []for i in range(2000): version = "reply@v7" if i < 1000 else "reply@v8" # v8 has a regression: it forgets the order number more often. has_order_ref = random.random() < (0.95 if version == "reply@v7" else 0.80) traces.append({ "trace_id": f"t{i:05}", "prompt_version": version, "output": "Your order #4512 ships today." if has_order_ref else "Your order ships today.", "thumbs_down": random.random() < (0.03 if has_order_ref else 0.25), }) def sampled(trace_id, rate): # Deterministic sampling: the same trace is always in or out of the sample. bucket = int(hashlib.sha256(trace_id.encode()).hexdigest(), 16) % 10_000 return bucket < rate * 10_000 def grade(trace): # Stand-in for an LLM judge or a code check: does the reply cite the order? return "#" in trace["output"] SAMPLE_RATE = 0.10ALERT_BELOW = 0.90results = {}new_eval_cases = []for t in traces: # 1. Quality metric: grade an unbiased random sample only. if sampled(t["trace_id"], SAMPLE_RATE): stats = results.setdefault(t["prompt_version"], {"graded": 0, "passed": 0}) stats["graded"] += 1 stats["passed"] += grade(t) # 2. Learning: every thumbs-down that also fails the check becomes an eval case. if t["thumbs_down"] and not grade(t): new_eval_cases.append(t["trace_id"]) for version, s in results.items(): rate = s["passed"] / s["graded"] flag = " <-- ALERT" if rate < ALERT_BELOW else "" print(f"{version}: {s['graded']:3} graded, pass rate {rate:.0%}{flag}")print(f"failed + thumbs-down traces to add to the eval set: {len(new_eval_cases)}")
Output
Press Run (⌘ Enter) to see what happens.

Try changing SAMPLE_RATE to 0.01. With about ten graded traces per version, the pass rates jump around and the alert becomes noise. Sample size decides whether an alert means anything, which is why low-traffic features often need a higher sample rate than busy ones.

LLM gateways: one door to every model

Once three teams call three providers with keys pasted into a dozen services, you get the same problems every company had with databases before connection pooling: no central view of spend, keys you cannot rotate, no shared rate limits. An LLM gateway is a proxy that every model call goes through. Open-source and managed options include LiteLLM, Portkey and Cloudflare AI Gateway, and the cloud platforms offer their own controls around Bedrock, Vertex AI and Azure.

Model calls through a gateway
Your services: one SDK, one URLYour servicesone SDK, one URLLLM gateway: keys, budgets, routingLLM gatewaykeys, budgets, routingProvider A: primaryProvider AprimaryProvider B: fallbackProvider BfallbackSelf-hosted vLLM: open-weightSelf-hosted vLLMopen-weightTraces and spend: per team, per tenantTraces and spendper team, per tenantvirtual keyrouteon failurecheap tier

Services call the gateway with a virtual key per team. Real provider keys live only in the gateway, so rotating one is a single change.

1/5

LiteLLM's proxy shows the shape. You declare model groups, then fallbacks and retry rules:

litellm-config.yaml
model_list:
  - model_name: support-chat
    litellm_params:
      model: anthropic/claude-sonnet-5-5
      api_key: os.environ/ANTHROPIC_API_KEY
  - model_name: support-chat-fallback
    litellm_params:
      model: hosted_vllm/Qwen/Qwen3-8B
      api_base: http://vllm.internal:8000/v1
 
litellm_settings:
  num_retries: 2
  request_timeout: 30
  fallbacks: [{"support-chat": ["support-chat-fallback"]}]
litellm --config litellm-config.yaml

Services then call the gateway's OpenAI-compatible endpoint with the model name support-chat. Check the LiteLLM docs for the current keys; the configuration surface is large and changes often.

The cost of a gateway is real: one more hop of latency, and a new critical component. If it goes down, every AI feature goes down, so it needs the same redundancy and monitoring as your API tier.

Reliability beyond retries

SDK retries with backoff (from AI Features in Production) handle a blip. A provider outage needs more:

  • Timeouts per call, set from your latency budget, not the SDK default.
  • Separate handling of 429s and overload errors. A 429 means you are over your own limit, so queue and smooth traffic. Overload errors mean the provider is struggling, so fail over.
  • Request queues for non-interactive work, so a spike becomes a delay instead of an error.
  • Circuit breakers, so you stop hammering a provider that is down and fail over at once.
  • Multi-region: cloud platforms offer cross-region inference (Bedrock inference profiles, Vertex AI global endpoints) that spread load across regions for you. Check whether that is compatible with your data residency rules first.

A circuit breaker watches failures. After a threshold it "opens" and sends traffic straight to the fallback for a cooldown period, then lets one probe request through. If the probe succeeds, it closes again:

Python
import random random.seed(3) class CircuitBreaker: """Stop calling a failing provider for a while, then probe it again.""" def __init__(self, failure_threshold=3, cooldown=5): self.failure_threshold = failure_threshold self.cooldown = cooldown # seconds (simulated clock) self.failures = 0 self.opened_at = None def allows(self, now): if self.opened_at is None: return True # closed: normal traffic return now - self.opened_at >= self.cooldown # half-open: one probe def record(self, ok, now): if ok: self.failures, self.opened_at = 0, None # close again else: self.failures += 1 if self.failures >= self.failure_threshold: self.opened_at = now # open (or re-open) def primary(now): # The primary provider is down between t=2 and t=9 inclusive. return not (2 <= now < 10) breaker = CircuitBreaker()for now in range(17): if breaker.allows(now): ok = primary(now) breaker.record(ok, now) route = "primary ok" if ok else "primary FAILED -> fallback" else: route = "breaker open -> fallback (primary not called)" print(f"t={now:2}: {route}")
Output
Press Run (⌘ Enter) to see what happens.

Notice t=9: the probe fails, so the breaker re-opens at once instead of letting a flood of traffic through. Without the breaker, every request during the outage would wait for a timeout before falling back.

Predict the outputPython

What does this print?

failures, threshold, opened = 0, 3, None
for now, ok in enumerate([True, False, False, False, False]):
  if opened is not None:
      continue
  failures = 0 if ok else failures + 1
  if failures >= threshold:
      opened = now
print(opened)
Need a nudge? Hints walk you through it.

Cost engineering at scale

The per-call cost table you built earlier becomes a set of levers at scale:

  • Batch APIs. Major providers offer asynchronous batch endpoints at a substantial discount (half price at the time of writing on several of them) with results within a day. Use them for evals, backfills, nightly summaries and classification jobs. Never for anything a user is waiting on.
  • Cache hit rate as a dashboard. Chart cache read tokens divided by input tokens, per feature. A sudden drop usually means someone put a timestamp or request id near the top of a prompt.
  • Routing. A small classifier or rule sends easy requests to a small model and hard ones to a large model. Measure quality per route, not overall, or a degraded easy route hides inside a good average.
  • Per-tenant attribution. Tag every span with the tenant, so you can see that one customer's integration drives a third of spend, and price or rate-limit accordingly.
Match the pairs0/4 matched

Match each problem to the lever that fits it best.

Choose an item, then its match on the other side.

Model lifecycle

Models are dependencies with an expiry date. Providers publish deprecation and retirement schedules, and a retired model id simply stops working.

  • Pin dated snapshots in production where the provider offers them, rather than aliases that move.
  • Track retirement dates for every model id in use. Your gateway's logs are the easiest inventory.
  • Migrate on your schedule: run the eval suite on the replacement, compare cost and latency from traces, shadow some traffic, then switch with the old model as a fallback.
Key terms
trace
One request recorded as a tree of timed spans sharing an id, showing every step and how long each took.
span
One timed step inside a trace, such as a model call or tool call, with attributes describing it.
GenAI semantic conventions
OpenTelemetry's shared attribute and span names for LLM operations, such as gen_ai.request.model. Still in development.
online evaluation
Grading a sample of real production traffic after release, asynchronously, to catch quality drops.
LLM gateway
A proxy all model calls pass through, handling keys, budgets, rate limits, routing, fallbacks and logging.
circuit breaker
A guard that stops calling a failing dependency after repeated errors, sends traffic to a fallback, and probes later.
batch API
An asynchronous endpoint that processes many requests at a discount, with results returned later rather than live.