Guide / AI engineering Fundamentals
LLM cost and capacity math
How to price an LLM feature: tokens per request, input/output price asymmetry, caching and batch discounts, a worked monthly bill, routing and cascading, and build vs buy break-even.
“What will this cost at 1M users?” is a standard senior question. Use formulas and state the price assumptions (prices change; the values below are illustrative, not quotes).
Fundamentals#
K.1 Token basics#
- 1 token ≈ 4 characters ≈ 0.75 English words (code and non-Latin scripts use more tokens per word; measure with the model’s tokenizer).
- Cost =
input_tokens × input_price + output_tokens × output_price. Output tokens usually cost 3–5× more than input and are also slower (sequential decode), so shorten outputs first. - Hidden tokens: system prompt, few-shot examples, tool definitions, retrieved chunks, conversation history, and reasoning/“thinking” tokens all count as input or output on every call.
- Multi-turn growth: without trimming, each turn resends the whole history, so total input tokens over a conversation grow quadratically with turns.
- Images, audio and video convert to tokens too (image tiles; audio per second).
K.2 Worked example: support chatbot#
Assumptions (illustrative): input price $3 per 1M tokens, output price $15 per 1M tokens, cached input read at 10% of input price.
Per request: system prompt 800 tokens + 4 retrieved chunks of 300 = 1,200 + history 500 + question 100 = 2,600 input; answer 250 output.
- Input cost: 2,600 × $3 / 1M = $0.0078
- Output cost: 250 × $15 / 1M = $0.00375
- ≈ $0.0116 per request
Volume: 200K conversations/month × 5 turns = 1M requests → ≈ $11.6K/month.
Optimisations and effect:
| Change | Effect on this example |
|---|---|
| Prompt caching the stable 800-token system prompt + tool defs (read at 10%) | Saves ~0.9 × 800 × $3/1M ≈ $0.0022 per request (≈ 19%); more when prefixes are long |
| Trim history (summarise after 3 turns, keep 200 tokens) | Saves 300 × $3/1M ≈ $0.0009 |
| Fewer chunks (4 → 3 after reranking) | Saves 300 × $3/1M ≈ $0.0009 |
| Cap output (250 → 150 with a concise style) | Saves 100 × $15/1M = $0.0015 (≈ 13%) |
| Model routing: 70% of requests go to a small model at ~1/10 the price | Cuts the bill by about 60% on those requests |
| Semantic/answer cache at 20% hit rate | Removes 20% of calls |
| Batch API for non-interactive work (typically ~50% discount) | Half price for reports, enrichment, evals |
K.3 Cost levers in priority order#
- Do not call the LLM when a rule, cache, search or small classifier suffices.
- Right-size the model: route by difficulty (small model first, escalate on low confidence or failed validation: a cascade), or by task type.
- Shorten prompts: remove unused instructions, compress retrieved context (rerank and cut), summarise history, fewer examples (or move to fine-tuning).
- Prompt/prefix caching and keep stable content first.
- Limit output: max tokens, concise instructions, structured output instead of prose, stop sequences.
- Batch and async for anything not user-facing.
- Cache exact and semantic answers carefully (scope by tenant, validate freshness).
- Self-host or fine-tune a small model when volume is high and stable (Model adaptation, LLM serving).
- Guardrails on usage: per-user and per-tenant token budgets, rate limits, loop caps for agents.
K.4 Agents and RAG multiply cost#
An agent making 8 LLM calls per task, each with growing context, can cost 10–50× a single call. Track cost per successful task, not per call. RAG adds embedding cost (cheap), vector DB cost, and many input tokens from chunks; reranking adds a model call but usually reduces generation cost by sending fewer, better chunks.
K.5 Self-hosting break-even#
cost per 1M tokens (self-hosted) = GPU $/hour ÷ (tokens per second × 3600) × 1,000,000.
Example: one GPU at $3/hour sustaining 3,000 output tokens/s at 60% average utilisation → effective 1,800 tokens/s × 3600 = 6.48M tokens/hour → $3 / 6.48 ≈ $0.46 per 1M output tokens, versus API output prices of several dollars per million for large models. But: you pay for idle capacity (utilisation drives everything), engineers, on-call, N+1 redundancy, and the open model must meet your quality bar. Break-even typically needs sustained, predictable volume and a task a smaller model handles well. Always run the numbers with measured throughput and real utilisation.
K.6 Capacity: rate limits and quotas#
Provider limits are in requests per minute and tokens per minute. Capacity planning: peak requests/s × tokens per request ≤ TPM quota; request quota increases early, spread across regions or accounts where allowed, add a gateway with retries, fallbacks and queueing (LLM gateway), and apply backpressure to users.
K.7 Reporting#
Dashboards for cost per request, per feature, per tenant, per model; token breakdown (system, context, history, output); cache hit rates; anomaly alerts on spend; budgets with automatic degradation (switch to cheaper model, shorten context) before cut-off.
Most asked questions#
1. How do you estimate the cost of an LLM feature? Tokens per request (input + output) × prices × volume, plus retrieval and infrastructure; then apply caching, routing and batching assumptions; present best/expected/worst.
2. Why is output more expensive than input? Decoding is sequential and memory-bound, so each output token takes much more GPU time than a prefilled input token.
3. How do you cut LLM costs without hurting quality? Route by difficulty, cache prefixes and answers, trim context, cap output, batch offline work, and validate with evals.
4. When does self-hosting pay off? High, steady volume with high GPU utilisation and a workload a smaller or fine-tuned model handles well, once ops cost is included.
5. How do agents affect cost? Many calls with growing contexts; set step and budget limits and track cost per completed task.
Senior-level questions#
1. “Your bill tripled but traffic only grew 20%.” Check tokens per request (prompt bloat, history growth, bigger retrieved context), model changes, agent loops or retries, cache hit rate drop, new feature using long documents or images, and missing output caps; add per-feature cost dashboards and alerts.
2. “Design a cascading model strategy.” Cheap model first with a confidence/validation check (schema valid, self-consistency, verifier or judge), escalate to the strong model on failure; measure escalation rate and overall quality and cost; avoid cascades where the cheap model is confidently wrong without a good signal.
3. “How would you price this feature for customers?” Per-seat or usage-based credits tied to tokens, include fair-use limits, protect margin with per-tenant budgets, and model the cost of heavy users separately (power users can cost 100× the average).
4. “Latency and cost conflict: what do you do?” Different requests have different needs: route interactive to fast/small models with streaming, batch the rest; speculative decoding and caching help both; measure cost per SLO-compliant request.
5. “Will costs fall on their own?” Per-token prices have fallen over time, but usage tends to grow faster (agents, longer contexts); plan on cost per task and keep the optimisation levers rather than betting on price cuts.
Quiz#
1. A request has 3,000 input and 500 output tokens at $2/M input and $10/M output. Cost?
3,000 × 2/1M = $0.006; 500 × 10/1M = $0.005; total $0.011 per request.
2. Why does a long chat get expensive?
Each turn resends the growing history as input, so total input tokens grow roughly quadratically; trim or summarise.
3. First lever to try for cost reduction?
Avoid unnecessary LLM calls (rules, caches, search, small classifiers), then route to smaller models and shorten prompts.
4. Self-hosted cost per 1M tokens formula?
GPU hourly cost ÷ (effective tokens per second × 3600) × 1,000,000, where effective throughput includes utilisation.
5. What should an agent's cost metric be?
Cost per successful task, not per call.