📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

How do you make AI calls observable in a .NET production system? Explain how you trace LLM and tool calls with OpenTelemetry, what you record about tokens, latency and cost, how you handle prompts and responses that may contain personal data, and what dashboards and alerts you set up.

Observability for LLM features and agents: OpenTelemetry GenAI semantic conventions, UseOpenTelemetry in Microsoft.Extensions.AI, spans for model and tool calls, token and cost metrics, content capture and PII, Application Insights and Aspire dashboards, quality signals and alerting.

Senior Theory Advanced ai application-insights llm-cost microsoft-extensions-ai observability opentelemetry

🎯 Key points

  • Microsoft.Extensions.AI UseOpenTelemetry emits spans and metrics using the OpenTelemetry GenAI semantic conventions (Development status as of late 2026: adopt now, pin versions, expect renames)
  • Span per model call (chat {model}) and per tool call (execute_tool {tool}); agent runs as a parent span; tool call id links them
  • Record model, deployment, input/output tokens, finish reason, latency incl. time to first token, retries and 429s
  • Cost = tokens × price per model, attributed per feature, tenant and user; near-real-time budgets and alerts
  • Prompts and responses hold names, emails, addresses, health or financial details pasted by users: content capture off by default (EnableSensitiveData false)
  • If content is needed: redacted sample, separate restricted workspace, short retention, documented under APP 11 data governance
  • Quality signals: user feedback, groundedness/safety evaluation on sampled traffic, tool error rates, iterations per run
  • Export via the Azure Monitor OpenTelemetry distro or OTLP/Collector so AI spans sit in the same trace as the HTTP request and DB calls

⏱ 30-second answer

Treat every model and tool call as a dependency in your distributed trace. In .NET, IChatClient pipelines get .UseOpenTelemetry(), which emits spans and metrics following the OpenTelemetry GenAI semantic conventions: a chat {model} span per model call with model, input and output tokens, finish reason, and an execute_tool {name} span per tool call, under the agent or request span. From those I build token, latency (including time to first token) and cost metrics attributed per feature and tenant. Prompt and response content is off by default because it often holds personal data; when I need it, I capture a redacted sample with short retention. On top I add quality signals: user feedback, sampled groundedness and safety evaluations, tool error rates and iterations per run. The trade-off: richer capture makes debugging easy but creates a privacy and cost liability.

🗣 Full answer (senior)

How I would answer this in an interview

"I want an AI request to look like any other request in Application Insights: one trace with the HTTP request, the model calls, the tool calls and the database queries under it. In .NET that's mostly configuration. I add .UseOpenTelemetry() to the IChatClient pipeline and AddSource/AddMeter for the Microsoft.Extensions.AI sources in the OpenTelemetry setup, and I export with the Azure Monitor distro or OTLP. Each model call becomes a chat span tagged with the GenAI semantic conventions: model, input and output token counts, finish reason. FunctionInvokingChatClient adds an execute_tool span per tool call, so I can see exactly which tool ran with which call id, how long it took and whether it failed. The conventions are still marked Development in late 2026, so I pin the version and expect attribute names to move.

From that I derive the metrics that matter: tokens and cost per feature and per tenant, p95 latency and time to first token, throttling (429s) per deployment, iterations per agent run and tool error rates. For example, at [company] a cost dashboard by feature showed that [a summarisation job] was [60%] of our spend because it re-sent the full document on every retry; fixing the retry policy cut the bill by […]. Content is the hard part. Prompts and responses contain whatever the user typed, so content capture is off by default. When we need it for quality investigations, we capture a small redacted sample into a separate store with [14-day] retention and restricted access.

The mistake I see is logging full prompts into the main log store 'for debugging', which turns observability into a data breach waiting to happen. My rule: trace everything structural, capture content deliberately."


What to record

Signal Where Why
Model call span (chat {model}) Trace Latency, model, tokens, finish reason per call
Tool call span (execute_tool {name}) Trace Which tool, duration, errors, call id
Agent / workflow span Trace Groups the loop; iterations per run
Token usage histogram Metric Cost and capacity per feature and tenant
Operation duration, time to first token Metric User-perceived latency, streaming health
429 / retry counts Metric Quota exhaustion per deployment
Prompt / response content Separate, opt-in, redacted Quality debugging only
Feedback, evaluation scores Metric / events Quality over time

Dashboards and alerts

Dashboard panel Alert
Cost per day by feature and tenant Daily cost > 150% of 7-day average
p95 latency and time to first token p95 above SLO for 15 min
429 rate per deployment > 2% of calls for 10 min
Iterations per agent run (p99) p99 at the cap: likely loops
Tool error rate by tool > 5% for 15 min
Groundedness / thumbs-down rate Drop beyond a threshold after a release

Production example

After adding GenAI spans and a cost-by-tenant dashboard, we found [one tenant's integration] calling the assistant in a retry loop, responsible for [35%] of tokens; a per-tenant budget alert fired within [20 minutes] of the next spike and the cap stopped it.

🔍 What the interviewer is checking

Checks whether the candidate can make AI features operable: traces, token and cost metrics, quality signals, and privacy-safe handling of prompt content.

Green flags

  • Uses UseOpenTelemetry and the GenAI semantic conventions, aware they are still evolving
  • Distinguishes structural telemetry from content capture and treats content as sensitive
  • Attributes cost per feature and tenant with alerts
  • Adds quality signals beyond latency and errors
  • Correlates AI spans with the rest of the request trace

Red flags

  • "We log every prompt" without redaction or retention limits
  • No idea what the AI feature costs per request
  • Only endpoint-level latency
  • High-cardinality user ids in metrics

📚 Learn in depth

1. The span tree of an AI request

 POST /assistant/ask                           1.9 s
 └─ invoke_agent booking-assistant              1.8 s
    ├─ chat gpt-4.1-mini        in=2,310 out=45    0.6 s  finish=tool_calls
    ├─ execute_tool list_my_bookings              0.08 s
    │  └─ SQL SELECT Bookings ...                  0.03 s
    ├─ chat gpt-4.1-mini        in=2,690 out=120   0.9 s  finish=stop
    └─ (content not captured)

The GenAI conventions define operation names (chat, embeddings, execute_tool, invoke_agent), attributes such as gen_ai.operation.name, gen_ai.request.model, gen_ai.response.model, gen_ai.usage.input_tokens, gen_ai.usage.output_tokens, gen_ai.response.finish_reasons, gen_ai.tool.name and gen_ai.tool.call.id, and metrics such as gen_ai.client.token.usage and gen_ai.client.operation.duration. As of late 2026 they are in Development status and, since June 2026, maintained in a separate semantic-conventions-genai repository, so names can change between versions.

2. How .NET emits them

OpenTelemetryChatClient (added with .UseOpenTelemetry()) wraps each call in an Activity from an ActivitySource and records metrics on a Meter. FunctionInvokingChatClient creates activities for tool invocations. The Agent Framework adds agent-level spans. Your OpenTelemetry setup must subscribe to those sources and meters; the Azure Monitor OpenTelemetry distro or an OTLP exporter sends them to Application Insights, the Aspire dashboard or any OTLP backend. EnableSensitiveData controls whether message content is recorded; it defaults to false.

3. Cost attribution

Providers bill per input and output token, with lower prices for cached input on some models. Compute cost from token metrics and a price table in configuration (prices change), tagged with feature, tenant and model. Keep tenant and user ids out of high-cardinality metric dimensions where they would explode cost; use tenant (bounded) on metrics and user only on traces or logs.

4. Content and privacy

Prompts carry user input, retrieved documents and tool results; responses can echo them. Under the Privacy Act (APP 11) you must protect personal information you hold, including in logs, and a leak can trigger the Notifiable Data Breaches scheme. Options: no content (default); hashed or length-only content; redacted samples (PII detection before storage) in a separate workspace with short retention and restricted RBAC; full capture only in non-production with synthetic data.

5. Quality is a signal too

Latency and errors don't tell you the answer was right. Add: explicit user feedback linked to the trace id; offline evaluation runs per release; online sampled evaluation (groundedness, relevance, safety) using Microsoft.Extensions.AI.Evaluation or Azure AI Foundry evaluations; and proxy metrics such as escalation rate and approval rejection rate.

6. Sampling

AI spans are a small fraction of total spans but very valuable. Use tail-based sampling in the OpenTelemetry Collector to keep all traces with errors, high cost or many iterations, and sample normal ones.

Try it yourself

  1. Add .UseOpenTelemetry() to an IChatClient, run under .NET Aspire and inspect the GenAI spans and token metrics in the dashboard.
  2. Toggle EnableSensitiveData in a dev environment and see what content appears; then decide what you'd allow in production.
  3. Write a KQL query over Application Insights dependencies that sums tokens per feature per day.
  4. Create an alert on p99 iterations per agent run equal to the cap.
  5. Add a thumbs-up/down endpoint that records feedback with the trace id and chart the rate per release.

💻 Code

OpenTelemetry for an AI feature: GenAI spans and metrics, content off, cost per feature recorded as a custom metric.

// Program.cs (.NET 10)
using Azure.Monitor.OpenTelemetry.AspNetCore;
using Microsoft.Extensions.AI;
using OpenTelemetry.Metrics;
using OpenTelemetry.Trace;

var builder = WebApplication.CreateBuilder(args);
const string AiSource = "Contoso.Assistant.AI"; // our own source name for the chat client telemetry

builder.Services.AddOpenTelemetry()
    .UseAzureMonitor()                       // connection string from configuration, not code
    .WithTracing(t => t.AddSource(AiSource, "Microsoft.Extensions.AI*", "Microsoft.Agents.AI*"))
    .WithMetrics(m => m.AddMeter(AiSource, "Microsoft.Extensions.AI*", AiCostMeter.Name));

builder.Services.AddSingleton<AiCostMeter>();
builder.Services.AddChatClient(sp => sp.GetRequiredService<AzureOpenAIClient>()
        .GetChatClient(builder.Configuration["AI:ChatDeployment"]!).AsIChatClient())
    .UseFunctionInvocation()
    .UseOpenTelemetry(sourceName: AiSource, configure: o => o.EnableSensitiveData = false); // no prompt content
using System.Diagnostics;
using System.Diagnostics.Metrics;
using Microsoft.Extensions.AI;

namespace Contoso.Assistant;

// Cost in AUD per feature and tenant, from token usage and a configurable price table.
public sealed class AiCostMeter(IConfiguration config)
{
    public const string Name = "Contoso.Assistant.Cost";
    private static readonly Meter Meter = new(Name);
    private static readonly Counter<double> Cost = Meter.CreateCounter<double>("ai.cost", unit: "AUD");

    public void Record(ChatResponse response, string feature, string tenantId)
    {
        if (response.Usage is not { } usage) return;
        var model = response.ModelId ?? "unknown";
        var inPrice = config.GetValue<double>($"AI:Prices:{model}:InputPerMillion");
        var outPrice = config.GetValue<double>($"AI:Prices:{model}:OutputPerMillion");

        double aud = (usage.InputTokenCount ?? 0) * inPrice / 1_000_000
                   + (usage.OutputTokenCount ?? 0) * outPrice / 1_000_000;

        Cost.Add(aud, new("feature", feature), new("tenant", tenantId), new("model", model));
        Activity.Current?.SetTag("app.ai.cost_aud", aud); // also on the trace for drill-down
    }
}
// Application Insights: tokens and calls per model per day
dependencies
| where timestamp > ago(7d) and name startswith "chat "
| extend model = tostring(customDimensions["gen_ai.request.model"]),
         inTok = toint(customDimensions["gen_ai.usage.input_tokens"]),
         outTok = toint(customDimensions["gen_ai.usage.output_tokens"])
| summarize calls = count(), input = sum(inTok), output = sum(outTok), p95 = percentile(duration, 95)
    by model, bin(timestamp, 1d)

⚠ Common mistakes

  • Mistake: Logging full prompts and responses into the main log workspace. Why it is wrong: They contain personal data and secrets, widely accessible and retained for months. Instead: Keep content capture off; use redacted, sampled capture in a restricted store with short retention.
  • Mistake: Only tracking HTTP latency of the endpoint. Why it is wrong: You can't see which model call or tool made it slow or expensive. Instead: GenAI spans per model and tool call under the request trace.
  • Mistake: No cost attribution. Why it is wrong: The monthly invoice is the first time anyone notices a loop or a heavy tenant. Instead: Token and cost metrics by feature, tenant and model with alerts.
  • Mistake: Putting user ids or prompt text into metric dimensions. Why it is wrong: Cardinality explosion and privacy exposure. Instead: Bounded dimensions on metrics; ids only on traces.
  • Mistake: Treating the GenAI conventions as stable. Why it is wrong: They are in Development status and attribute names have changed between releases. Instead: Pin package versions and build dashboards that are easy to update.
  • Mistake: Measuring only latency and errors. Why it is wrong: A fast, error-free wrong answer looks healthy. Instead: Add feedback, sampled evaluation and escalation metrics.
  • Mistake: Ignoring time to first token for streaming UIs. Why it is wrong: Users judge speed by when text starts appearing. Instead: Track and alert on time to first token separately.

🏛 Senior insight: trade-offs

AI observability is ordinary observability plus two things: cost is now a per-request runtime metric, and the payload is often personal data. I want structural telemetry on 100% of AI calls (cheap and safe) and content on a small, governed sample. The other senior point is that correctness needs its own signal, so I wire feedback and evaluation into the same dashboards as latency.

Option When it fits Cost When not to
Application Insights via Azure Monitor distro Azure-hosted .NET, one place for everything Ingestion cost; sample normal traffic Strict multi-cloud or self-hosted requirement
OTLP to Grafana / Tempo / Prometheus Existing open-source stack Run and scale it yourself Small team without platform support
Dedicated LLM observability tool Heavy prompt iteration, evaluation workflows Another vendor holding prompt data When data residency or privacy rules forbid it
Aspire dashboard Local development and testing Free, not persistent Production

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions keeping all failing or expensive traces Why: Checks tail-based sampling and cost/visibility trade-offs
    How to answer

    Head sampling decides at the start of a trace: the root service keeps, say, 10%, and the decision travels in the traceparent sampled flag so every service records the same traces. In .NET that's ParentBasedSampler(new TraceIdRatioBasedSampler(0.1)). It's cheap, but it decides before knowing whether the request will fail.

    Tail sampling decides after the trace completes: the OpenTelemetry Collector buffers spans (about 30 s), then keeps all errors, all traces slower than a threshold, and a small random baseline. It needs every span of a trace on the same Collector, so you route by trace id with the loadbalancing exporter, and it costs memory.

    Always compute metrics before sampling, so dashboards and alerts stay accurate. The trade-off: head sampling is simple and cheap; tail sampling keeps the interesting traces but adds infrastructure you must run.

  2. When: Candidate mentions prompts containing personal data Why: Checks data leakage controls and Privacy Act obligations
    How to answer

    Treat every prompt, index and log as a copy of your data with its own access controls. Minimise and redact personal information before it goes into a prompt. In RAG, enforce tenant and permission filters inside the search query (or separate indexes); never trust the model to withhold something it was given. Logs and traces are the leak people forget: don't capture prompt content by default, and redact and limit retention when you do.

    Know where the provider processes and stores data: deployment region, Global vs regional deployments, and abuse-monitoring retention. Map it to the Privacy Act: APP 6 purpose, APP 8 cross-border, APP 11 security, the NDB scheme, and automated-decision transparency from December 2026. The trade-off: more context improves answers but widens what can leak.

  3. When: Candidate mentions spans and ActivitySource Why: Checks how Activity maps to OpenTelemetry spans in .NET
    How to answer

    Activity is .NET's span type and ActivitySource is the factory that creates them, the equivalent of an OpenTelemetry Tracer. They live in System.Diagnostics, so libraries can emit spans without referencing OpenTelemetry at all. You call source.StartActivity("name", ActivityKind.Internal) inside a using, add tags (attributes), events and a status, and disposing it records the duration.

    StartActivity returns null when nothing is listening or the sampler drops the span, which is why you write activity?.SetTag(...). The OpenTelemetry SDK only listens to sources registered with AddSource("MyCompany.Orders"). Activity.Current is stored in an AsyncLocal, flows across await, and becomes the parent of the next activity.

    The trade-off: the API is free when tracing is off, but you must name sources consistently or your spans silently go nowhere.

🛠 Real-world problems: how you handle them

AI bill tripled overnight and nobody could tell which feature caused it
Situation
[A SaaS product] had [four] AI features sharing one Azure OpenAI deployment in Australia East, with only endpoint-level request telemetry.
Signals
Azure cost alert on the Azure OpenAI resource at [3x] the daily average; 429 throttling errors for interactive users; no per-feature breakdown in Application Insights.
Investigation
Enabled `UseOpenTelemetry` on all chat clients with a feature tag and deployed within the hour; queried GenAI dependency spans by feature and tenant; found a nightly document-summary job retrying whole documents on 429s without backoff, re-sending [40k-token] prompts; confirmed with Azure OpenAI metrics (processed tokens per deployment).
Resolution
Paused the job and added exponential backoff with jitter and a retry cap. Moved batch work to a separate deployment (and the Batch API where latency allowed) so it couldn't starve interactive traffic.
Prevention
Cost-per-feature and per-tenant dashboard; alert at 150% of the 7-day average; separate deployments or quotas for batch and interactive; load test of the retry policy; runbook entry for AI cost spikes.

How to tell it (STAR)

**S:** Our Azure OpenAI spend tripled overnight and interactive users started seeing throttling errors, but we only had endpoint-level telemetry. **T:** I needed to find the cause fast and make sure we'd see it coming next time. **A:** I turned on OpenTelemetry for every chat client with a feature tag, and within [an hour] the GenAI spans showed a nightly summary job re-sending [40k-token] prompts on every 429 with no backoff. We paused it, fixed the retry policy, moved batch work to its own deployment, and built a cost-by-feature dashboard with an alert. **R:** Spend returned to baseline the next day, interactive throttling dropped to [under 0.5%], and the alert has since caught [two] smaller regressions within minutes.

More in AI Agents and MCP

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me