Sub topic 2
Traces and spans: the core model
This chapter explains the data model that every later chapter builds on. It assumes you can read basic Python, including context managers, and that you know what logs and metrics are. You don't need to have installed OpenTelemetry yet. Setup comes in a later chapter.
Why a model comes first
An LLM application rarely does one thing per request. A single user question can trigger a retrieval query, two model calls, a tool call and a retry. Logs show each event in isolation. A trace shows how those events relate: which step caused which, how long each took, and where time went.
OpenTelemetry (OTel) is a vendor-neutral standard for producing this data. Its trace model has a small number of parts. If you understand them, the rest of the tutorial is mostly about naming things consistently.
Traces and spans
A span is one timed unit of work. Examples are a model call, a database query, or a function that runs a tool. A trace is the set of spans that belong to one end-to-end operation, such as handling one user request.
Every span carries these core fields:
| Field | Meaning |
|---|---|
| Trace ID | Identifier shared by every span in the same trace |
| Span ID | Identifier unique to this span |
| Parent span ID | The span ID of the span that started this one. Empty for the root |
| Name | A short label for the operation, such as `chat example-model` |
| Start and end time | Timestamps. The duration is the difference |
| Kind | The role of the span: client, server, internal, producer or consumer |
| Status | Unset, OK or Error |
| Attributes | Key-value pairs that describe the work |
| Events | Timestamped notes inside the span |
| Links | References to spans in other traces |
The parent span ID is what turns a flat list of spans into a tree. A span with no parent is the root span. Every other span points to exactly one parent.
In a trace viewer the same tree appears as a waterfall. Each span is a horizontal bar positioned by start time and sized by duration. Child bars sit inside the time range of their parent. Bars that overlap in time ran concurrently.
Span kind
Span kind tells the backend how a span relates to other services. It is a hint, not behavior.
CLIENT: your code calls a remote service and waits. A model call over HTTP is a client span.SERVER: your code handles a request from a remote caller.INTERNAL: work inside your process, with no remote call. This is the default in the Python API.PRODUCERandCONSUMER: asynchronous messaging, such as putting a job on a queue and processing it later.
Use CLIENT for calls to a hosted model API. Use INTERNAL for your own orchestration code, such as an agent loop.
Span lifecycle
A span moves through three stages: started, recording, ended. You create it, add data to it, and end it. Only after it ends is it handed to the exporter. If you never end a span, it is never exported, which is a common cause of "my span is missing".
The Python API gives you two ways to manage this. The first is a context manager, which ends the span for you even when an exception occurs:
from opentelemetry import trace
tracer = trace.get_tracer("support_agent")
def answer(question):
with tracer.start_as_current_span("answer_question") as span:
span.set_attribute("app.question_length", len(question))
return question.upper()The second is tracer.start_span(...), which creates a span but does not make it current. You must call span.end() yourself. Prefer the context manager unless a span has to outlive a single block, such as one that covers a streaming response.
Without an SDK configured, the code above still runs. The API returns non-recording spans that do nothing. This design lets library authors add instrumentation without forcing a dependency on a backend. The next chapters cover the SDK that makes spans real.
The current span and nesting
start_as_current_span does two things. It starts a span, and it stores that span in a context so that code running inside the with block can find it. Any span started inside the block takes the current span as its parent.
from opentelemetry import trace
tracer = trace.get_tracer("support_agent")
def retrieve(query):
with tracer.start_as_current_span("retrieval docs"):
return ["doc-1", "doc-2"]
def run(question):
with tracer.start_as_current_span("invoke_agent support-agent"):
docs = retrieve(question)
return docsHere retrieval docs becomes a child of invoke_agent support-agent without you passing anything between the functions. You can read the active span anywhere with trace.get_current_span(). Chapter 6 covers how this context travels across threads, async tasks and service boundaries.
Attributes, events and status in brief
Three kinds of data hang off a span. The next chapter treats them in depth, so here is only the distinction.
- Attributes describe the whole span and are set once per key, such as the model name. Setting the same key again overwrites it.
- Events are timestamped points within the span, such as a retry starting or an exception being recorded.
- Status summarizes the outcome. It starts as
Unset. Set it toErrorwhen the operation failed. Instrumentation code normally leaves successful spans asUnsetrather than settingOK.
Edge cases and common mistakes
- Spans that never end. An exception can skip a manual
span.end(). The context manager avoids this. - Orphaned spans. If a new thread or task does not receive the current context, its spans start a new trace instead of joining the existing one. You then see two unrelated traces for one request.
- Wrong parent. Passing a span as current only works within the same context. Starting a span with
start_spandoes not change the current span, so later spans will not nest under it. - Span names with high cardinality. Do not put user IDs or full prompts in the name. Names should describe a class of operation, and variable detail belongs in attributes.
- Long-lived spans. A trace whose root stays open for hours, such as an agent that waits on a human, is hard to view and may be dropped by backends that wait for a trace to complete. Consider splitting such work into separate traces and connecting them with links.
- Too many spans. A span per token or per loop of a tight function adds overhead and noise. Create spans for operations you would want to see in a waterfall.
Choosing what to make a span
A useful rule: make something a span if it takes meaningful time, can fail on its own, or is a step you would want to find in a trace. Make it an attribute if it only describes a span. Make it an event if it marks a moment inside a span.
| You want to record | Use |
|---|---|
| A model call and its duration | Span |
| The model name | Attribute |
| A retry about to happen | Event |
| The call failed | Status plus an exception event |
| A follow-up job that runs later | New trace, with a link |
Exercise
An agent function starts a span with tracer.start_span("plan") and then calls a helper that starts a span with tracer.start_as_current_span("search"). The two spans appear in different places in the trace tree, and "plan" never shows up in the backend. Give two reasons and the fix.
Show answer
First, start_span creates the span but does not make it the current span, so "search" does not become its child. It has whatever parent was current before, or none. Second, "plan" was never ended, and only ended spans are exported. The fix is to use with tracer.start_as_current_span("plan"): around the call. This sets the current span and ends it when the block exits, even if an exception occurs.
Exercise
You want to record that the model call retried twice before succeeding. Should each retry be a span, an attribute or an event? Name one case where a span is the better choice.
Show answer
By default, an event on the model call span works well, because a retry is a moment inside one operation. A span is better when each attempt makes its own network call that you want to time and inspect separately, for example when attempts have different latencies or errors. In that case, create one child span per attempt under a parent span for the whole operation.