LevelUpWith

Explore / LLMOps in Production: Observe, Release, Recover, Govern / Lesson 2

Lesson 2: Traces, Spans and Context for LLM Apps

Learn the OpenTelemetry basics (traces, spans, attributes, events, resources and exporters) through the lens of one LLM request, and why a trace is the main unit of debugging for AI features.

Free to read, no account needed. Part of LLMOps in Production: Observe, Release, Recover, Govern.

By the end of this level you'll be able to

  • Set up the OpenTelemetry SDK in Python or TypeScript with an OTLP exporter and a local collector
  • Wrap one LLM request in a parent span with child spans for retrieval, the model call and post-processing
  • Read a waterfall view and find where the latency and failures in a request come from

One request, one story

In Level 1 you saw the main problem: the same input can give a different output, and a failure often looks like a confident, wrong answer with an HTTP 200. Logs alone don't help much here. Your logs show retrieval done and model returned as separate lines in a stream shared by every user, and you have to piece one request back together from them.

A trace keeps each request together. It's the record of one request from start to finish. Each timed step inside it is a span. Each span has a parent, so they form a tree. When a user reports "the answer was slow and wrong", you find that request's trace and read the whole thing in one place.

The OpenTelemetry (OTel) vocabulary you need:

Concept What it is In our LLM request
Trace All spans that share one trace ID One /ask request
Span A named operation with a start, an end and a parent retrieve, llm.call, postprocess
Attribute A key-value pair on a span app.retrieval.doc_count = 4
Event A timestamped point inside a span first_token_received
Status Unset (default), Ok or Error Error when the model call times out
Resource Attributes describing who emitted the telemetry service.name=support-bot
Exporter Sends finished spans somewhere OTLP over HTTP to a collector

How to pick between an attribute and an event: if the exact moment matters, use an event ("first token arrived at 812 ms"). If it doesn't, use an attribute.

Step 1: Run a local collector and a trace viewer

The app sends spans to an OpenTelemetry Collector. The collector batches them and forwards them to Jaeger, which draws the waterfall. Your code only knows about the collector, so changing vendors later means editing one config file instead of your application.

# docker-compose.yaml
services:
  collector:
    image: otel/opentelemetry-collector:latest
    volumes:
      - ./collector.yaml:/etc/otelcol/config.yaml
    ports:
      - "4317:4317"   # OTLP over gRPC
      - "4318:4318"   # OTLP over HTTP (our app uses this)
  jaeger:
    image: cr.jaegertracing.io/jaegertracing/jaeger:2.23.0
    ports:
      - "16686:16686" # Jaeger UI; its own OTLP ports stay inside the network
# collector.yaml
receivers:
  otlp:
    protocols:
      grpc: { endpoint: 0.0.0.0:4317 }
      http: { endpoint: 0.0.0.0:4318 }
processors:
  batch: {}
exporters:
  debug: { verbosity: basic }        # prints a line per batch: handy proof spans arrive
  otlp_grpc:                          # called `otlp` before Collector v0.144; old name still works as an alias
    endpoint: jaeger:4317
    tls: { insecure: true }           # local only, never in production
service:
  pipelines:
    traces:
      receivers: [otlp]
      processors: [batch]
      exporters: [debug, otlp_grpc]

Start both with docker compose up -d, then open http://localhost:16686. Jaeger's all-in-one image keeps traces in memory, so a restart wipes them.

Step 2: Set up the SDK (Python)

pip install opentelemetry-sdk opentelemetry-exporter-otlp-proto-http
# tracing.py
from opentelemetry import trace
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter

# Resource = who is speaking. Without service.name you get "unknown_service".
resource = Resource.create({"service.name": "support-bot", "deployment.environment": "dev"})

provider = TracerProvider(resource=resource)
# BatchSpanProcessor buffers spans and sends them in the background,
# so the request never waits on the network.
provider.add_span_processor(
    BatchSpanProcessor(OTLPSpanExporter(endpoint="http://localhost:4318/v1/traces"))
)
trace.set_tracer_provider(provider)
tracer = trace.get_tracer("support-bot")

In TypeScript the setup is the same: NodeSDK from @opentelemetry/sdk-node with an OTLPTraceExporter from @opentelemetry/exporter-trace-otlp-http. You can also set OTEL_SERVICE_NAME as an environment variable instead of writing the name in code.

Step 3: Wrap one LLM request

import time, random
from opentelemetry.trace import Status, StatusCode
from tracing import tracer, provider

def ask(question: str) -> str:
    with tracer.start_as_current_span("ask") as root:          # parent span = whole request
        root.set_attribute("app.question.length", len(question))  # a size, not the raw text

        with tracer.start_as_current_span("retrieve") as s:      # child: nests automatically
            time.sleep(0.12)                                      # stand-in for a vector search
            s.set_attribute("app.retrieval.doc_count", 4)

        with tracer.start_as_current_span("llm.call") as s:
            time.sleep(0.3)
            s.add_event("first_token_received")                   # timestamp matters -> event
            time.sleep(1.1)
            if random.random() < 0.2:
                s.set_status(Status(StatusCode.ERROR, "provider timeout"))
                raise TimeoutError("model call timed out")

        with tracer.start_as_current_span("postprocess"):
            time.sleep(0.02)                                      # parse, validate, redact
        return "answer"

for _ in range(5):
    try: ask("How do I reset my password?")
    except TimeoutError: pass
provider.shutdown()   # flush buffered spans before the script exits!

Gotcha: if you leave out provider.shutdown() (or force_flush()) in a short script or serverless function, the process can exit before the batch is sent, and the trace never shows up.

Gotcha: start_as_current_span records an uncaught exception as a span event and sets the status to Error for you by default. Setting the status yourself, as above, lets you write a clearer message.

The span names and the app.* attributes here are your own choice. In Level 3 you'll switch to OTel's standard names for model calls.

Step 4: Read the waterfall

In Jaeger, choose support-bot, click Find Traces, and open one trace:

ask          |=========================================| 1.56 s
  retrieve   |===|                                       0.12 s
  llm.call       |==================================|    1.40 s  * first_token_received @0.42s
  postprocess                                       |=|  0.02 s

What to look for:

  • The widest child. llm.call takes about 90% of the time, so speeding up retrieval won't help much. The event shows that 0.3 s of it was time to first token and the other 1.1 s was generation. Each half has a different fix.
  • Gaps. If the parent is 1.56 s but the children add up to 1.1 s, some work isn't covered by a span (a cache lookup, a JSON parse you didn't wrap). Add a span there.
  • Bars one after another vs. side by side. Bars that follow each other are steps that run in sequence. If two retrieval calls don't depend on each other, running them in parallel makes the trace shorter.
  • Red spans. Jaeger marks error spans. Click one to see its status message and the exception event.

Trade-off: each span costs a little memory and a little export bandwidth. Wrap the steps you'd want to blame when something goes wrong, not every helper function.

Exercise

  1. Run the stack and the script, then find a failed trace and a successful one.
  2. Add a rerank span between retrieve and llm.call that sleeps 0.5 s. Check that the waterfall shows it as a new delay between the two.
  3. Remove provider.shutdown(), run the script again, and see which traces go missing.
  4. Write down the slowest step in your slowest trace and one fix you'd try.

Key takeaways

  • A trace is one request. Spans are its timed steps, arranged as a parent-child tree.
  • Attributes describe a span. Events mark moments inside it. Status records failure. The resource says which service sent it.
  • Send spans over OTLP (port 4318 for HTTP, 4317 for gRPC) to a collector so your backend can change without touching your code.
  • Batch exporting keeps requests fast, but you have to flush on shutdown.
  • In a waterfall, check the widest bar, the gaps between bars and the red spans first.

A 6-question knowledge check follows this lesson in the app, free and without an account.

Keep going: levels 3 and 4 are free

Create a free account to open the next two levels, try the AI tutor, save your progress and pick up where you left off. No card needed.

Next: Level 3, OTel GenAI Conventions for Model Calls.

Create a free account →See the whole course

More like this