Cost, latency and observability
An AI feature that works in a demo can still fail in production: too slow, too expensive at scale, or quietly looping on some inputs. You can't fix what you can't see, so the first step is recording every model and tool call. Then the savings are usually easy to find.
1. The idea
Three things to get right:
- Observe. Record a trace for every request: each model call and tool call, with the model, tokens, cost, time, errors and (where allowed) the content. OpenTelemetry has standard GenAI fields for this, so any tracing tool can read it.
- Cut cost with the levers from Module 04, applied automatically: route easy requests to a smaller model, cache the stable start of prompts, batch anything that can wait, and ask for shorter outputs.
- Cut latency where users feel it: stream the answer so the first words appear quickly, run independent tool calls in parallel, use a faster model or less reasoning effort for simple steps.
And set budgets (turn caps, token limits, per-user and per-feature spend limits) so one bad input can't burn a month's budget overnight.
2. How it works
One model-call span, with the standard OpenTelemetry GenAI attribute names (simplified):
{
"name": "chat claude-sonnet-5-5",
"duration_ms": 2410,
"attributes": {
"gen_ai.request.model": "claude-sonnet-5-5",
"gen_ai.usage.input_tokens": 3120,
"gen_ai.usage.output_tokens": 412,
"gen_ai.response.finish_reasons": ["end_turn"],
"app.feature": "support-answer",
"app.cost_usd": 0.0104
}
}
The gen_ai.* names come from the OpenTelemetry GenAI semantic conventions, which are still evolving. The app.* fields are your own: tag every span with the feature and customer so you can slice cost by them.
3. Try it yourself
Trim the bill
A support feature handles 20,000 requests a day on Claude Sonnet 5.5: 3,000 input tokens and 400 output tokens each. Switch on the levers and watch the monthly cost.
Make it feel fast
One agent request: a planning call, two tool calls, then the answer. Change how it runs and watch the total time and the time until the user sees the first words.
4. Why it matters at work
| Lever | What it saves | How |
|---|---|---|
| Model routing | Cost, latency | A cheap model handles most requests; hard ones (or ones it's unsure about) go to a stronger model. Prove it with evals (Module 17) |
| Prompt caching | Cost, latency | Keep instructions, tool definitions and documents identical and first. Cached input costs 2.5–10% of the normal price (Module 04) |
| Batch API | Half the cost | For anything that can wait hours: nightly reports, backfills, evals |
| Shorter outputs | Cost, latency | Output tokens cost several times more than input and are generated one by one. Ask for JSON or a fixed length; set max_tokens |
| Lower reasoning effort | Cost, latency | Only spend thinking tokens on steps that need them |
| Streaming | Felt latency | Users see words after the time to first token, not after the whole answer |
| Parallel tool calls | Latency | Independent lookups run at the same time |
| Budgets | Runaway spend | Turn caps (Module 16), per-user and per-feature limits, alerts at 50/80/100% |
Measure what matters: cost per successful task (not per request), p95 latency and time to first token (not just averages), error and retry rates, and turns per agent run. Track cost per feature and per customer, so a price change is a decision, not a surprise.
5. In your five tools
Coding tools need the same discipline: know what a session and a month cost you. Checked against vendor documentation, October 2026.
| Tool | See cost and usage | Export and control |
|---|---|---|
| Claude Code | /cost: the current session's cost and tokens | OpenTelemetry export with CLAUDE_CODE_ENABLE_TELEMETRY=1: metrics such as claude_code.cost.usage and claude_code.token.usage, plus events for API calls and tool decisions |
| Antigravity CLI | /usage (alias /quota): model quota used; /credits: remaining credits | Settings decide whether paid credits are used once plan quotas run out |
| GitHub Copilot | Usage-based billing with GitHub AI Credits since 1 June 2026; your usage page shows credits used | Budgets and spending limits; for organisations, the Copilot usage metrics dashboard and REST API |
| Cursor | Dashboard: usage and the Spending tab | Spend limits (soft or hard, with alerts); for teams, the Admin API returns usage events with tokens and cost |
| Codex CLI | /status in a session | OpenTelemetry export: an [otel] section in your user-level ~/.codex/config.toml (project config ignores it); prompts are redacted unless you opt in |
6. Remember it
How this hook works: what “Trace it, price it, trim it” means
What the slogan means, phrase by phrase
- “Trace it”
- A span for every model and tool call (model, tokens, time, errors), tagged with feature and customer. OpenTelemetry makes it portable.
- “price it”
- Turn tokens into money per feature, per customer and per successful task, and latency into p95 and time to first token. Now you know where the money and the waiting go.
- “trim it”
- Route, cache, batch, shorten, stream, parallelise, cap. Check each change with your evals so quality doesn't drop.
Why this picture fits: it stops you optimising blind. The expensive part is rarely where you'd guess: often a few runaway agent runs, or one feature with an uncached 20,000-token prompt.
The story → the concept
| The delivery company | Your AI feature |
|---|---|
| A tracker in every van | A trace for every request |
| Fuel per route | Cost per feature and per customer |
| Small parcels in a small van | Model routing |
| Loading the van the same way every morning | Prompt caching |
| Overnight freight | Batch API |
| Several drops on one street at once | Parallel tool calls |
| "Your parcel is on its way" message | Streaming |
| A fuel card limit | Budgets and turn caps |
Watch it on an example
- Trace: costs jumped 40% this week.
- Price: one customer's agent runs average 38 turns instead of 6; their documents make the search tool return nothing useful.
- Trim: a turn cap of 12, a better "not found" message from the tool, and an alert at 3× normal cost per customer.
The trap it saves you from
Switching everything to the cheapest model to save money, then losing users because quality dropped and no eval caught it.
It still works when…
You manage your own use of coding agents: check /cost or your usage page weekly, notice which tasks burn tokens, and adjust models, effort and context.
7. Common mistakes
8. Hands-on lab (roadmap week 24)
- Trace your feature from Modules 14–16: one span per model and tool call with model, tokens, duration and a feature tag. Send it to any OpenTelemetry-compatible tool, or start with a log file.
- Price it: compute cost per request and per successful task from the token counts and current prices.
- Add caching: reorder the prompt so the stable part comes first, and confirm cache reads in the API's usage numbers.
- Try routing: run your eval set on a smaller model. For which cases is it good enough? Estimate the saving.
- Estimate cost per 1,000 users, and set a budget and alert. Turn on telemetry or check usage in your own coding tool for a week.
9. Self-check quiz
Costs jumped and nobody knows why. What should already have been in place?
Your cache hit rate is zero. The most likely cause?
Answers take 8 seconds and users say it "feels broken". The quickest win for felt latency?
Before routing easy requests to a cheaper model, what must you check?
10. Go deeper
| Resource | Time | Why |
|---|---|---|
| Inside the LLM call: GenAI observability with OpenTelemetry | 20 min | How the standard GenAI spans and attributes work. |
| Prompt caching (Claude docs) | 20 min | How cache breakpoints, lifetimes and pricing work. |
| Batch APIs: Claude, OpenAI, Gemini | 30 min | Half-price processing for work that can wait. |
| Monitoring usage (Claude Code docs) | 15 min | OpenTelemetry metrics and events from a coding agent. |