Observability

Adding custom OpenTelemetry spans so an AI agent can see inside a request

Gérald Barré (Meziantou's blog) Gérald Barré
Observability

In a 371 ms request whose only database query took 2 ms, no span covered the gap. The author added phase-level OpenTelemetry spans to the search handler, and the new spans exposed an enumerable that was being walked twice.

Key points

  • Built-in OpenTelemetry covers HTTP, database and outgoing calls; the work between them leaves no span at all.
  • dotnet-counters showed about 4 GB/s of allocations and 8.4 s of user CPU per 2 s: the process was computing, not waiting.
  • Custom spans need explicit registration with AddSource("Catalog.Search") and AddMeter("Catalog.Search"); service defaults alone export nothing.
  • Phase spans plus matchEvaluations and scoreEvaluations tags separated slow code from too much code.
  • 300,000 match evaluations for 150,000 products revealed matches being enumerated twice, by rank and by Count().
  • Normalizing product strings once at load time cut p50 from 361 ms to 12.5 ms and user CPU by roughly seven times.

Why it matters

Anyone who hands a slow-request investigation to a coding agent will hit this wall: built-in instrumentation covers HTTP, database and outgoing calls, so a 370 ms hole inside a handler does not exist in the trace. Letting the agent add an ActivitySource and a Meter is a real code change made before the cause is known, and it needs supervision. The registration call is easy to forget, a span per item floods the trace, and user data in tags leaks into your telemetry backend. Treat added instrumentation as a draft: keep what answered the question, delete the rest, re-measure the same way, and compare responses before shipping the fix.

Real-world use

  • An in-memory product search endpoint that takes 371 ms under load while its single query takes 2 ms
  • An AI agent investigation driven through the Aspire dashboard and the aspire otel CLI
  • Handlers that run several phases (tokenize, match, rank, count) inside a single span

This summary was generated by the agent from the original post on Gérald Barré (Meziantou's blog). The full text and all rights belong to its author and publisher. Go to original

Report this story

Is something wrong with the summary, or do you own this content? Your message comes straight to my inbox.

Type of message

Related stories

Feedback

Found a bug or have an idea? Your message lands straight in my inbox.

Type of message