Skip to main content
All posts
Engineering

10 challenges building an OTel LLM tracer

Dr. Harry Cruz

Dr. Harry Cruz

• 18 min read

10 challenges building an OTel LLM tracer

Everyone uses tracing. Almost nobody has built a tracer. If you've worked with Datadog or Jaeger, you know what traces look like from the consumer side: a waterfall of spans, some timing data, maybe a few tags. The tooling feels mature, the concepts feel simple.

Then you try to build one for LLM applications, and you discover a set of problems that the finished product hides completely.

This post walks through those problems. We built an OpenTelemetry-compliant tracing system for LLM applications, and the AI ecosystem turned out to be far more fragmented than it looks from the outside. Most of the hard work had nothing to do with distributed systems theory. It was about provider inconsistencies, naming conventions, and timing bugs.

The problems you don't see from the outside

If you've instrumented a web service, you know the routine. Wrap your HTTP handlers, capture request/response metadata, ship spans to a collector. The data is small (a URL, a status code, a few headers), the execution model is linear (request in, response out), and the cost of each operation is negligible.

LLM applications differ in ways that affect almost every design decision in a tracer.

Cost matters more than latency. A single GPT-4 call can cost $0.50. A RAG pipeline might fire five LLM calls per request. An agentic loop with tool use can iterate unpredictably, each step burning tokens. Traditional APM doesn't track cost per request because for most services, the marginal cost is effectively zero. For LLM applications, cost is often the metric you care about most, and your tracer needs to compute it.

The payloads are large, and the content matters. An HTTP span records a URL and a status code. An LLM span needs the full prompt (10-100KB), the completion, token counts broken down by input and output, model parameters, and the model name. When an LLM hallucinates, the only way to debug it is to read the exact prompt and response. You can't get away with just capturing metadata.

Execution is non-linear. An agent loop can call tools, receive results, reason, call more tools, and repeat for an unknowable number of iterations. These create deep, branching span trees that you need to model correctly as parent-child relationships.

Frameworks churn fast. In 2022, most teams called the OpenAI API directly. In 2023, LangChain dominated. By 2024, LangGraph, CrewAI, AutoGen, and custom implementations were all in active use. If your tracer is coupled to one framework's abstractions, you'll be rewriting it every year or so.

None of this is obvious when you're just using a tracing tool. You only see it when you try to build one.

Challenge 1: Choosing a trace format

The first decision is whether to build on OpenTelemetry or design a custom trace format.

A custom format is tempting. You can define a compact JSON schema, skip the OTLP serialization overhead, and ship something fast. Each span weighs ~2KB instead of ~5KB. You control the schema entirely.

The argument for OpenTelemetry is that your traces slot into any compatible backend (Jaeger, Grafana, whatever comes next) without adapters. Teams that already run an OTEL collector can ingest your LLM traces alongside their HTTP and database spans. As OTEL's AI semantic conventions mature, your data aligns with a standard rather than drifting into a format nobody else can read.

The price is verbosity. OTLP spans carry metadata you don't need. At low volume (tens to hundreds of traces per minute), the overhead is negligible. At high volume, you'd need to evaluate whether the extra bytes matter for your storage and network costs.

We chose OpenTelemetry. Standards compound in value over time; custom formats don't. But either choice is defensible depending on your scale and ecosystem constraints.

Challenge 2: The naming problem [instrumentation]

This one seems trivial until you actually face it. What do you name your spans?

Every LLM framework uses different abstractions. LangChain has "chains" and "agents." LangGraph has "graphs" and "nodes." CrewAI has "crews" and "tasks." If you name spans after these concepts, your data becomes framework-specific: ai.chain.sequential from one app, ai.graph.node from another, ai.crew.task from a third. You can't compare them. You can't build dashboards that work across projects using different frameworks. Every query needs framework-specific logic.

The solution we found is to enforce primitive operations. Span names describe what the code does at the machine level, not how the developer organized it:

ai.llm.invoke -- any LLM call, any framework
ai.tool.invoke -- any tool execution
ai.retrieval -- any knowledge retrieval
ai.embedding.generate -- any embedding generation
ai.agent.invoke -- an agent invocation
ai.agent.handoff -- a transfer between agents

Framework concepts like chain, workflow, and pipeline are actively rejected. The validation is shared between SDK and backend through a Pydantic schema:

FORBIDDEN_SPAN_DOMAINS: List[str] = ["chain", "workflow", "pipeline"]
class OTELSpan(BaseModel):
span_name: str
@field_validator("span_name")
@classmethod
def validate_span_name(cls, v: str) -> str:
if v.startswith("function."):
return v
pattern = r"^ai\.[a-z]+(\.[a-z]+)?$"
if not re.match(pattern, v):
raise ValueError(
f"span_name must follow 'ai.<domain>.<action>' "
f"or 'function.<name>' (got: {v})"
)
parts = v.split(".")
if len(parts) >= 2 and parts[1] in FORBIDDEN_SPAN_DOMAINS:
raise ValueError(
f"span_name cannot use framework concept '{parts[1]}'. "
"Use primitive operations: llm, tool, retrieval, embedding"
)
return v

If a client sends ai.chain.execute, the backend returns HTTP 422. This is intentional. You want it to fail loudly during development rather than silently pollute the data model.

Framework context isn't lost. It goes into span attributes, not span names:

span.set_attribute("ai.framework", "langchain")
span.set_attribute("ai.framework.chain_type", "sequential")

This distinction matters in practice. When we migrated a service from LangChain to a custom implementation, the dashboards didn't break. The span names stayed the same. The queries stayed the same. Only the ai.framework attribute changed.

All semantic strings are defined as typed constants in the SDK (AIOperationType.LLM_INVOKE for "ai.llm.invoke", AIAttributes.MODEL_NAME for "ai.model.name", etc.). The backend imports the same constants. IDE autocomplete catches typos at write time, and validation and instrumentation always agree because they reference the same definitions.

Think of it like HTTP observability. You'd trace http.request and database.query, not mvc.controller or microservice.call. The first set describes operations; the second describes architecture. Operations are stable across refactors. Architecture isn't.

The architecture

Before going deeper into individual challenges, here's how the pieces connect:

Architecture diagram: trace flow through instrumentation, export, ingestion, and enrichment
A trace flows through four stages: instrumentation, export, ingestion, and enrichment.

A trace flows through four stages, and most of the challenges in this post map to one of them:

Instrumentation is where spans get created. This happens inside the application process, either through manual @observe decorators or through auto-instrumentation callbacks that hook into frameworks like LangChain. The semantic layer (the naming conventions and typed constants) lives here too. The naming problem, token extraction, auto-instrumentation, the decorator API, and multi-turn conversation support are all instrumentation challenges.

Export is how spans leave the application. The BatchSpanProcessor buffers spans and periodically flushes them to a custom exporter, which converts OTEL's internal representations (128-bit integer trace IDs, nanosecond timestamps) to our Pydantic schema (32-char hex strings, datetime objects) and POSTs them to the backend. The batch timing problem lives here.

Ingestion is the backend receiving and storing spans. The telemetry router validates incoming batches against the same Pydantic schemas the SDK uses, then writes them to PostgreSQL. Storage schema design is an ingestion concern.

Enrichment is what happens after storage. Cost calculation, anomaly detection, metadata extraction, and trace-test linking all run as post-processing, either asynchronously via background workers or synchronously as a fallback.

The SDK absorbs all framework-specific complexity. By the time a span reaches the exporter, its origin framework is invisible at the structural level (it appears only as an attribute). The backend never needs to know whether a span came from LangChain, LangGraph, or a manual decorator.

The Pydantic schemas are shared between SDK and backend. The same OTELSpan model the exporter serializes is the model the backend deserializes. Validation is defined once and enforced at both ends, which eliminates an entire class of producer-consumer mismatch bugs.

The exporter is a custom subclass of OTLPSpanExporter:

class RhesisOTLPExporter(OTLPSpanExporter):
def export(self, spans: Sequence[ReadableSpan]) -> SpanExportResult:
batch = self._convert_spans(spans)
response = self._session.post(
self.endpoint,
json=batch.model_dump(mode="json"),
timeout=self._timeout,
)
response.raise_for_status()
return SpanExportResult.SUCCESS

Challenge 3: When to enrich traces [enrichment]

Raw spans are useful but incomplete. You want cost calculations, anomaly detection (slow spans, high token usage, errors), and metadata extraction (which models were used, which tools were called). The question is: when do you compute this?

There are three reasonable approaches.

You can enrich on ingest: process every span inline before the ingestion endpoint returns. Simple, no moving parts, but it adds latency to every trace submission. If enrichment involves external calls (like a pricing API), you're blocking the producer.

You can enrich on read: store raw spans, compute derived data when someone queries a trace. The ingestion path stays fast, and you skip processing traces nobody ever looks at. But the first view of any trace is slow (50-100ms for cost calculation), and the logic is harder to test because it runs in the query path.

Or you can enrich asynchronously: queue enrichment as a background task after storage. Ingestion stays fast, every trace gets enriched, the first query is already warm. The downside is that you need task infrastructure and a fallback for environments where that infrastructure isn't running.

"Task infrastructure" here means a message broker (like Redis) and one or more worker processes that pull jobs from a queue outside the web server process. We use Celery for this. You define a function as a task, call .delay() on it, and a Celery worker picks it up in a separate process. The web request returns immediately.

We went with the third option, with a twist: automatic sync fallback.

class EnrichmentService:
def enqueue_enrichment(self, trace_id, project_id, organization_id,
workers_available=None):
if workers_available is None:
workers_available = self._check_workers_available()
if workers_available:
try:
enrich_trace_async.delay(trace_id, project_id, organization_id)
return True
except Exception:
pass
# Sync fallback
enricher = TraceEnricher(self.db)
enricher.enrich_trace(trace_id, project_id, organization_id)
return False

In production with Celery workers running, ingestion returns in ~10ms and enrichment happens in the background. In development without workers, enrichment happens inline, adding 50-100ms. If workers crash in production, the system degrades to sync mode automatically. No configuration flags, no environment detection.

We considered selective enrichment (process errors immediately, defer successes) but dropped it. At our volume, the savings were trivial. The bugs from maintaining two code paths wouldn't be.

One operational detail: Celery's inspect.ping() takes about 3 seconds. We cache the result for 5 minutes so we don't pay that cost on every request.

Challenge 4: Getting token counts from LLM providers [instrumentation]

You'd think getting the number of tokens from an LLM response would be straightforward. It's not.

Every provider uses different key names for the same concept. OpenAI returns prompt_tokens and completion_tokens. Anthropic returns input_tokens and output_tokens. Google Gemini returns prompt_token_count and candidates_token_count. Some return these in a dict, some as attributes on a UsageMetadata object, some in camelCase variants.

Your extraction code needs to try each known key name, handle both dict access and attribute access, and compute totals when the provider doesn't supply them.

That's the straightforward part. When you add a framework like LangChain on top, the problem multiplies. LangChain wraps provider responses in its own objects, and depending on the provider and LangChain version, token counts can end up in seven different locations:

  1. response.llm_output["token_usage"] (OpenAI, the most common path)
  2. response.llm_output["usage"] (Anthropic format)
  3. response.usage (direct usage attribute)
  4. message.usage_metadata (LangChain v0.1+ with newer providers)
  5. message.response_metadata["token_usage"]
  6. generation.usage_metadata
  7. generation_info (various providers)

The extraction code tries each source in order and stops at the first one that returns non-zero totals. This looks over-engineered until you find yourself debugging why Cohere token counts are always zero in production and trace it to yet another location you didn't know about.

This is easily the most maintenance-heavy part of the system. Each new provider or LangChain version can introduce a new location for token data, and you only discover it from production metrics.

Challenge 5: Auto-instrumenting frameworks [instrumentation]

Manual instrumentation with decorators works, but nobody will actually do it for their entire codebase. You want developers to call auto_instrument("langchain") once and have every LLM call, tool invocation, and agent execution traced automatically.

The problem is that each framework exposes different extension points. LangChain has a callback system. LangGraph inherits it but needs method patching on top. AutoGen uses a different messaging pattern entirely.

For LangChain, we implement a callback handler that translates events into OpenTelemetry spans:

class RhesisLangChainCallback(BaseCallbackHandler):
def __init__(self):
self.tracer = trace.get_tracer(__name__)
self._spans: Dict[str, tuple] = {}
def on_chat_model_start(self, serialized, messages, *,
run_id, parent_run_id=None, **kwargs):
span, parent_token, current_token = self._start_span(
AIOperationType.LLM_INVOKE, run_id, parent_run_id
)
set_llm_attributes(span, serialized, kwargs, request_type="chat")
add_chat_prompt_event(span, messages)
self._spans[str(run_id)] = (span, parent_token, current_token)
def on_llm_end(self, response, *, run_id, **kwargs):
span_data = self._spans.get(str(run_id))
if not span_data:
return
span = span_data[0]
extract_and_set_tokens(span, response)
span.set_status(Status(StatusCode.OK))
self._end_span(run_id)

The callback uses run_id to correlate start and end events, and parent_run_id to build the span tree. Context tokens are managed carefully: when a parent run is active, you attach its span context so child spans nest correctly, then detach in reverse order when the span ends.

Provider detection is its own headache. LangChain wraps providers behind its own classes (ChatOpenAI, ChatAnthropic, etc.), and the module paths vary between versions. You end up checking module paths, class names, and model name patterns in that priority order. Compound model names need care: bedrock-claude is an AWS provider, not Anthropic, even though it runs a Claude model. Getting this wrong means your cost calculations use the wrong pricing table.

There's also a deduplication problem. When developers combine manual @observe.llm() decorators with auto-instrumentation on the same function, both try to create spans for the same LLM call. We handle this through a ContextVar flag: the decorator sets it while active, and the callback checks it before creating a span.

Making it extensible

Without a common integration interface, each new framework is a one-off with its own lifecycle management, and the complexity grows linearly. We defined a minimal abstract class that every integration implements:

class BaseIntegration(ABC):
@property
@abstractmethod
def framework_name(self) -> str: ...
@abstractmethod
def is_installed(self) -> bool: ...
@abstractmethod
def _create_callback(self) -> Any: ...
def enable(self) -> bool:
if not self.is_installed():
return False
self._callback = self._create_callback()
self._enabled = True
return True

Three methods. is_installed probes for the framework's packages (a simple import check). _create_callback returns whatever hook mechanism the framework uses. The base class handles the enable/disable lifecycle and singleton management.

Adding a new framework means writing one class. The semantic layer handles the rest: whatever callback or hook the new integration uses, the spans it creates must use the same AIOperationType and AIAttributes constants. A LangGraph ai.llm.invoke span and a hypothetical CrewAI ai.llm.invoke span are structurally identical at the data level.

When frameworks share infrastructure, integrations can share callbacks. LangGraph is built on LangChain's callback system, so its integration reuses the LangChain callback handler. The _create_callback method just delegates:

class LangGraphIntegration(BaseIntegration):
def _create_callback(self):
lc_integration = get_langchain_integration()
return lc_integration._create_callback()

LangGraph-specific work happens in enable(), which patches CompiledStateGraph.invoke, ainvoke, stream, and astream to inject callbacks transparently. Each patched method stores a reference to the original, then wraps it to merge the callback into the config dict before calling through.

When both LangChain and LangGraph are instrumented, they must share the same callback instance. Without this, you get duplicate spans for every LLM call.

Challenge 6: Computing costs [enrichment]

You need per-request cost tracking, but maintaining your own pricing tables is a losing proposition. LLM pricing changes constantly, there are 100+ models across providers, and each provider structures pricing differently (per-token, per-character, tiered).

We delegate to LiteLLM's cost_per_token() function. During enrichment, the cost calculator filters to LLM spans (identified by AIAttributes.OPERATION_TYPE == "ai.llm.invoke"), extracts model name and token counts from span attributes, and calls litellm.cost_per_token() for each. Unknown models are silently skipped. If a model isn't in LiteLLM's database, you still get the trace, the timing, and the token counts. You just don't get the dollar amount. We track costs in both USD and EUR with a configurable exchange rate since our operations span both sides of the Atlantic.

A missing cost value is annoying. A failed trace ingestion is a bug. We'd rather have the former.

Challenge 7: Storing traces [ingestion]

Traces get written once and queried in two very different ways. Detail queries fetch all spans for a single trace ID, which is a fast indexed lookup. Analytical queries aggregate across thousands of traces, which is scan-heavy. These two access patterns want different storage engines.

We store traces in PostgreSQL, the same database as the rest of the application. The schema uses fixed columns for frequently-filtered fields and JSONB for everything else:

class Trace(Base):
trace_id = Column(String(32), nullable=False, index=True)
span_id = Column(String(16), nullable=False, index=True)
parent_span_id = Column(String(16), nullable=True)
project_id = Column(GUID(), ForeignKey("project.id"), nullable=False)
span_name = Column(String(255), nullable=False, index=True)
start_time = Column(DateTime, nullable=False, index=True)
duration_ms = Column(Float, nullable=False)
status_code = Column(String(20), nullable=False, index=True)
attributes = Column(JSONB, nullable=False, default=dict)
events = Column(JSONB, nullable=False, default=list)
enriched_data = Column(JSONB, default=dict)

A GIN index on the attributes column enables fast containment queries:

SELECT * FROM trace
WHERE attributes @> '{"ai.model.name": "gpt-4"}'

This works at our scale. Writes complete in ~10ms for a 10-span batch. Reads by trace_id take ~5ms. At millions of spans per day, you'd want a dedicated columnar store (ClickHouse, TimescaleDB) for the analytical workload. At our volume, adding a second database would double operational complexity for no measurable benefit.

Challenge 8: Timing problems with batch export [export]

This one caught us off guard.

OpenTelemetry's BatchSpanProcessor accumulates spans and exports them periodically (every 5 seconds by default, or when the batch reaches 512 spans). This is efficient for throughput, but it means spans don't arrive at the backend immediately.

We link traces to test executions so you can see the exact LLM calls from a failed test. The linking mechanism hit a timing problem:

T=0.0s: Test starts
T=0.5s: Test completes, test_result created, try to link traces
T=5.0s: Spans finally arrive at the backend

The traces don't exist yet when you try to link them. This works fine for tests that take longer than 5 seconds (spans arrive before the result is created) and silently fails for fast tests.

The fix is to link at both points and make each operation idempotent:

# 1. After test result creation (catches early-arriving traces)
linking_service.link_traces_for_test_result(
test_run_id=test_run_id,
test_result_id=str(result_id),
organization_id=organization_id,
)
# 2. After span ingestion (catches late-arriving traces)
linking_service.link_traces_for_incoming_batch(
spans=stored_spans,
organization_id=organization_id,
)

The CRUD operation uses test_result_id IS NULL as a guard:

result = (
db.query(models.Trace)
.filter(
models.Trace.test_run_id == test_run_uuid,
models.Trace.test_id == test_id_uuid,
models.Trace.test_result_id.is_(None), # idempotent guard
)
.update({"test_result_id": test_result_uuid})
)

If path 1 links the traces, path 2 finds nothing to update. If path 1 misses them because they haven't arrived yet, path 2 catches them when they do.

This generalizes beyond our use case. Anytime you have batched async writes interacting with synchronous operations, pick multiple linking points and make each one idempotent. Hoping the timing works out is not a strategy.

Challenge 9: Making instrumentation feel lightweight [instrumentation]

Raw OpenTelemetry span management is verbose. For a two-line function, you write ~18 lines of boilerplate: start a span, set attributes, try/except, record exceptions, set status codes, close the span. Nobody will instrument their code if it means tripling the line count of every function.

Here's what we ended up with:

# Raw OTEL: 18 lines for a 2-line function
with tracer.start_as_current_span("ai.llm.invoke") as span:
try:
span.set_attribute("ai.operation.type", "llm.invoke")
span.set_attribute("ai.model.provider", "openai")
span.set_attribute("ai.model.name", "gpt-4")
result = llm.generate(prompt)
span.set_status(Status(StatusCode.OK))
return result
except Exception as e:
span.record_exception(e)
span.set_status(Status(StatusCode.ERROR, str(e)))
raise
# @observe.llm: 2 lines
@observe.llm(provider="openai", model="gpt-4")
def generate_text(prompt: str) -> str:
return llm.generate(prompt)

The namespaced methods (observe.llm(), observe.tool(), observe.retrieval()) are implemented as a callable class following the same pattern as pytest.mark.skip() or @app.get(). Each method delegates to the generic @observe() with the appropriate semantic constants pre-filled. The decorator handles sync functions, async functions, and generators, attaching span context in each case so nested @observe calls produce proper child spans.

Challenge 10: Multi-turn conversations [instrumentation + export]

Stateful endpoints (chatbots, multi-turn agents) need all turns in a conversation to share the same trace ID. OpenTelemetry assigns a new trace ID per root span, so each invocation would normally start a fresh trace.

The workaround is a synthetic parent context. You construct a fake parent SpanContext carrying the conversation's existing trace ID and inject it before span creation. The new span inherits the trace ID from the synthetic parent. A sentinel span ID (0x00000000CAFECAFE) marks these synthetic parents so the exporter can strip them before export, keeping each turn's root span as a true root in the trace view. The exporter also propagates conversation_id to all child spans in a two-pass process: first building a trace_id -> conversation_id mapping from turn-root spans, then copying the ID to every child in the same trace.

This works, but it's the kind of thing that makes you wish OpenTelemetry had first-class support for correlated-but-separate traces.

What building a tracer teaches you

The hardest parts of this project had nothing to do with distributed systems. They were about the AI ecosystem's inconsistencies: token counts in seven locations, provider names buried in framework module paths, cost data that requires a third-party library because no two providers price the same way, semantic conventions that are still being written.

Anyone building LLM observability tooling will run into the same problems. The naming problem, the token extraction maze, the timing issues with batch export, the framework extensibility questions. Your solutions will differ from ours, but the problems are structural. They come from the ecosystem, not from your design choices.

If I had to pick the one decision that mattered most, it's the semantic layer. Get the naming right and enforce it with validation, and everything downstream (queries, dashboards, cost aggregation) falls into place. Get it wrong, and you'll spend more time maintaining framework-specific query logic than building actual features. We learned this the hard way when an early prototype used LangChain's naming conventions and became useless the moment someone tried LangGraph.

Our ai.* namespace is custom. When the official OpenTelemetry AI semantic conventions stabilize, we'll need to migrate. Because everything is defined as typed class attributes, that migration is a find-and-replace on constant values rather than a grep across the codebase.

The biggest gap right now is streaming. We collect the full response before creating the trace. For long-running streaming responses, we'll need incremental span updates, which is a different programming model than what OpenTelemetry's span lifecycle assumes.

Frameworks will keep changing. Providers will keep adding models. The fragmentation isn't going away. A tracing system that describes what code does rather than which framework it uses will survive those shifts. One that doesn't will need rewriting every time the ecosystem moves.