Observability for LLM calls: traces, tokens, cost and quality
Which request burned 40,000 tokens, which prompt version made answers worse: measuring an LLM call as an expensive, erratic dependency, following the OpenTelemetry GenAI semantic conventions, tagging feature and prompt version, without leaking user content.
On this page
1. The problem
The LLM bill goes from 1,200 USD to 9,800 USD in a month. Logs only show POST /support/reply 200 4.2s. Three days later the cause turns up: prompt v7 stuffs the whole conversation history into every turn, and a 30-turn session sends 40,000 tokens.
2. Key idea
The cost and quality of an LLM call vary per request, not per endpoint. One request becomes many calls (retrieval, several chat turns, tool calls), and each turn resends the whole context. Treat it as an expensive, erratic external API, with two new dimensions: tokens and prompt version.
| Question | Signal needed | Where |
|---|---|---|
| Which feature costs most? | tokens by model and feature | metrics |
| Why did this request use 40,000 tokens? | tokens per span, number of chat turns | traces |
Is prompt v7 worse than v6? |
quality score per version | metrics + offline evaluation |
2.1 Which signal goes where?
Low-cardinality things you aggregate go into metrics; per-request detail goes into traces; content only when you truly need it.
| Signal | Use when | Don't use when |
|---|---|---|
Metrics labelled model, feature, prompt_version, token_type |
cost dashboards, alerts | labels like user_id, conversation_id: time series explode |
Spans following the OpenTelemetry GenAI conventions (gen_ai.*) |
finding why one request was slow or expensive | you need the monthly total |
| Recording prompt/answer content | quality evaluation on PII-redacted samples | by default in production |
Cost: store token counts and multiply by a price table on the dashboard. Prices change a few times a year; cost computed in code goes silently wrong.
3. In Java
Spring AI already emits observations through Micrometer (duration, tokens, tools, vector store). You only add two business labels:
class LlmUsageAdvisor implements CallAdvisor {
private final MeterRegistry meters;
LlmUsageAdvisor(MeterRegistry meters) { this.meters = meters; }
public String getName() { return "llm-usage"; }
public int getOrder() { return 0; } // outermost: usage summed across the tool loop
public ChatClientResponse adviseCall(ChatClientRequest req, CallAdvisorChain chain) {
ChatClientResponse res = chain.nextCall(req);
Usage u = res.chatResponse().getMetadata().getUsage();
Tags tags = Tags.of(
"feature", String.valueOf(req.context().getOrDefault("feature", "unknown")),
"prompt_version", String.valueOf(req.context().getOrDefault("prompt_version", "unknown")),
"model", res.chatResponse().getMetadata().getModel());
meters.counter("llm.tokens", tags.and("type", "input")).increment(u.getPromptTokens());
meters.counter("llm.tokens", tags.and("type", "output")).increment(u.getCompletionTokens());
return res;
}
}
// Call with: .advisors(a -> a.param("feature", "support-reply").param("prompt_version", "v7"))Other languages: Python and Node have OpenTelemetry instrumentation for the OpenAI and Anthropic SDKs; in Go you write gen_ai.* attributes on spans yourself.
Conventions, content and the dashboards to have
- The GenAI conventions are still in Development; names have changed a few times (
gen_ai.systembecamegen_ai.provider.name). Check the real names at/actuator/prometheusbefore building dashboards. - The returned model (
gen_ai.response.model) can differ from the requested one: a-latestalias may point to a new release. Group quality by the returned model. - Content: Spring AI turns off
log-prompt,log-completionand toolinclude-contentby default. When you need it: a separate store (anllm_sampletable), PII redaction, 1–5% sampling, 14–30 days retention, and keepresponse.idandprompt_versionto join with traces. - Dashboards: input/output tokens by feature × model converted to money; p95 input tokens per request (context bloat); the
finish_reason = lengthrate (cut off bymax_tokens); chat turns per request (agents looping on tools); 429/5xx rates by provider; quality score byprompt_version. - Daily-budget alerts ("feature X above 150% of its 7-day average") catch bugs faster than the month-end invoice.
4. Working with AI
Delegate to AI: a token-measuring advisor, PromQL and dashboards, a PII filter for content samples.
Check yourself:
- No
user_id,conversation_id, question text or full URLs in metric labels. - Prompt and answer content is off by default; where it's on, there's PII redaction, sampling and retention.
- Every call carries
featureandprompt_version; usage covers every tool turn. - Cost comes from tokens and a price table, not hard-coded in the service.
5. Exercises
Exercise 1: Review an advisor that "tracks cost per user"
After a week, Prometheus uses 14 GB of RAM. Find the bugs and fix them.
meters.counter("llm.tokens",
"user", req.context().get("userId").toString(),
"question", userText.substring(0, Math.min(80, userText.length())),
"model", model).increment(u.getTotalTokens());Solution to Exercise 1
userandquestionare unbounded labels: 50,000 users × millions of distinct questions means millions of time series.- Customer questions end up in the metrics system, with no PII redaction and no retention limit.
getTotalTokens()is wrong for cost because input and output are priced differently.get("userId").toString()throws NPE when it's missing.- Fix: labels are only
feature,prompt_version,model,type. Per-user cost is summed into anllm_usage(user_id, day, input_tokens, output_tokens)table, or taken from traces.
Exercise 2: Read the dashboard after a deploy
Thursday afternoon: p95 output tokens go from 420 to 1,024, the finish_reason = length rate from 0.5% to 38%, p95 duration from 4 s to 11 s. prompt_version changed from v12 to v13. Diagnose, act within 15 minutes, fix the root cause.
Solution to Exercise 2
- Output tokens hit exactly 1,024 and 38% of answers are cut: they're capped by
max_tokens = 1024. Promptv13makes the model write much more (perhaps it dropped "answer in at most 5 sentences"). Generation time scales with output tokens. - 15 minutes: flip the
prompt_versionflag back tov12(prompts switch via config, no deploy). - Root fix: diff the two prompts, rerun the golden test set with checks on length and the
lengthrate; alert when thelengthrate passes 5%.
Summary
- Measure every LLM call: model, input/output tokens, duration,
finish_reason, feature, prompt. - Metrics carry only low-cardinality labels; user and conversation ids go in traces.
- Content is off by default; when on, a separate store, PII redaction, sampling.
- Store tokens, compute cost from a price table on the dashboard.
- Alert on daily budgets, don't wait for the invoice.
Further reading: Distributed tracing with OpenTelemetry.
Comments
Community rules