AI costs in production: tokens, caching, and model routing
How to control LLM spend in production: tokens, prompt caching, model routing, and metrics that prevent surprises.
Table of Contents
Imagine you hire a taxi for everything. Every trip is charged per kilometer, and every kilometer costs the same whether you are going to an important meeting or to buy bread. At the end of the month, the bill is enormous, and you do not know where the money went: useful trips or unnecessary detours.
LLMs in production are that taxi. Every input and output token is charged. An agent that reads 20 files to answer a simple question burns tokens like a taxi circling downtown to find an address two blocks away. The model is not expensive. Uncontrolled usage is expensive.
The problem: cost hides in usage
In development, LLM cost is invisible. You use the most powerful model, pass it all the context you can think of, and the monthly bill is a few dollars. In production, with thousands of users and agents calling tools in loops, the bill can multiply by 100 without changing a line of code.
The problem is not the price per token. It is that nobody measures how many tokens each flow consumes, or which ones are necessary. A chatbot that replies “hi” with a 4000-token system prompt and a 20-message history burns 5000 input tokens per greeting. At scale, that is money thrown away.
Anatomy of cost
Before optimizing, understand what you pay for.
Input vs output tokens
Input tokens (prompt, context, history) and output tokens (generated response) are charged separately, and output usually costs 2 to 5 times more per token. A model that generates long answers is more expensive than one that generates short answers, even when they read the same context.
Prompt caching
Providers (Anthropic, OpenAI) offer prompt caching: if you send the same prompt prefix (system prompt, documents, tools) across multiple requests, the prefix is cached and charged at a fraction of the normal price (typically 10% of normal cost). This is the highest-impact optimization and the most ignored.
Batch processing
For tasks that do not need an immediate response (mass classification, embedding generation, document analysis), providers offer batch APIs with 50% discounts. The trade-off is latency: the response arrives in minutes or hours, not seconds.
Context window
A model with a 200K-token window does not mean you should use 200K. Every context token is charged on every request. A 50K-token context in 10,000 requests per day is 500 million tokens. Cost scales linearly with context.
Caching: the highest-impact optimization
There are three caching levels, and most teams use only the first (or none).
Level 1: provider prompt caching
If your system prompt and documents are the same on every request, the provider caches them automatically. You only need to structure the prompt so the stable prefix goes first and the variable content (the user’s question) goes last.
messages = [
{"role": "system", "content": LONG_SYSTEM_PROMPT}, # cached
{"role": "user", "content": user_question}, # variable
]
Typical impact: 50-90% reduction in input cost for repetitive requests.
Level 2: exact caching (your application)
If the same question (or a very similar one) is asked frequently, cache the full response. A Redis cache with a TTL of minutes or hours eliminates redundant requests to the model.
import hashlib, redis
cache = redis.Redis()
def cached_completion(prompt: str, model: str) -> str:
key = hashlib.sha256(f"{model}:{prompt}".encode()).hexdigest()
cached = cache.get(key)
if cached:
return cached.decode()
response = call_llm(prompt, model)
cache.setex(key, 3600, response) # TTL 1 hour
return response
Typical impact: 30-70% reduction in request volume for applications with repetitive questions.
Level 3: semantic caching
Instead of comparing exact strings, you compare embeddings of the question. If a new question is semantically similar to one already answered, you reuse the answer. Requires a vector store and a high similarity threshold (0.95+).
Typical impact: an additional 20-40% on top of exact caching, but with risk of wrong answers if the threshold is too low.
The risk of caching
A stale cache returns wrong answers. If your data changes, the cache must be invalidated. Use short TTLs for volatile data and long ones for static data. And never cache responses that depend on user permissions without including the user in the key.
Model routing: the right model for each task
Not every task needs the most powerful model. An intent classifier does not need GPT-4; a one-paragraph summary does not need Claude Opus. Routing sends each task to the cheapest model that can handle it well.
Routing strategy
- Classify the task: is it simple (classification, extraction, formatting) or complex (reasoning, code, analysis)?
- Send to cheap model (GPT-4o-mini, Claude Haiku, Llama 3) for simple tasks.
- Send to powerful model (GPT-4o, Claude Sonnet/Opus) for complex tasks.
- Fallback: if the cheap model fails or has low confidence, escalate to the powerful one.
def route_and_call(task: str, prompt: str) -> str:
if is_simple_task(task):
try:
result = call_llm(prompt, model="gpt-4o-mini")
if confidence(result) > 0.8:
return result
except Exception:
pass
return call_llm(prompt, model="gpt-4o")
Typical impact: 60-80% cost reduction if 70%+ of tasks are simple.
Specialized models
For specific tasks, cheaper and faster models exist: embedding models for search, classification models for routing, code models for generation. Using a generalist model for a specialized task is like using a truck to buy bread.
The routing mistake
Routing by perceived complexity, not real complexity. “This prompt is long, use the powerful model” is a mistake: a long prompt with a simple task (extracting a field) does not need a powerful model. Classify by task, not by input size.
Context optimization
Context is the biggest token consumer. Reducing it without losing information is the hardest and most profitable optimization.
Intelligent truncation
Do not pass full documents. Extract the relevant sections before sending to the model. If the user asks about vacation policy, do not send the 200-page manual; send the vacation section.
Incremental summarization
For long conversations, summarize older turns instead of sending them in full. Keep the last N turns complete and a summary of the earlier ones.
RAG instead of full context
Instead of passing 50 documents to the model, use RAG to retrieve the 3-5 most relevant. The cost of retrieval (embeddings + vector search) is orders of magnitude lower than sending 50 documents to the model.
Prompt compression
Remove redundancy from the system prompt. Every word of the system prompt is charged on every request. A 2000-token system prompt that can be reduced to 800 without losing information saves 1200 tokens per request.
Measurement: what is not measured is spent
Without metrics, optimization is blind. The minimum metrics:
- Cost per request: input + output tokens × model price.
- Cost per user: aggregated per user, to detect users generating disproportionate cost.
- Cost per flow: which functionality (chat, summary, classification) consumes more.
- Cache hit rate: what percentage of requests are resolved from cache.
- Model distribution: what percentage uses cheap vs powerful model.
Alerts
Set alerts when daily cost exceeds a threshold, when a single user generates more than X% of total cost, or when cache hit rate drops below a minimum. The end-of-month bill is too late to discover a problem.
Minimum dashboard
A dashboard with daily cost, cost per flow, and cache hit rate is enough to start. You do not need a full observability platform to control costs; you need visibility.
When NOT to optimize
- Do not optimize before measuring. If you do not know what consumes, you optimize the wrong thing.
- Do not use a cheap model for tasks requiring quality. A classifier that fails 20% of the time costs more in corrections than it saves in tokens.
- Do not cache responses that must be fresh. A stale cache in a support chatbot gives wrong information.
- Do not compress the system prompt until it becomes incomprehensible. A confusing prompt generates worse answers, which cost more tokens to fix.
- Do not optimize the last 5%. 80% of savings come from caching and routing. The remaining 20% (prompt compression, fine truncation) has diminishing returns.
Checklist before putting an LLM in production
- Cost per request, per user, and per flow is measured.
- Cost alerts exist for daily and per-user spend.
- The system prompt is structured for prompt caching (stable prefix first).
- Exact caching exists for repetitive questions.
- Routing sends simple tasks to cheap models.
- Context is truncated or summarized, not sent in full.
- RAG is used instead of passing full documents to the model.
- Non-urgent tasks use batch processing.
- Cache hit rate is monitored.
- The quality vs cost trade-off has been evaluated for each flow.
Optimizing AI costs is not making the model cheaper. It is stopping payment for tokens that add nothing. The taxi does not charge less per kilometer: you decide how many kilometers to travel.
Related articles
By relevance
Guardrails and LLM security: prompt injection, jailbreaks, and defenses
Prompt injection, jailbreaks, and LLM defenses: why guardrails fail and how to design systems that resist manipulation.
Streaming and AI UX: responses that don't bore
How to implement LLM streaming with SSE, improve UX, and stop users from leaving while waiting for an answer.
Software Architect Part 2: FinOps, DevOps Culture & Business Logic
Advanced guide on communicating with FinOps teams, understanding business culture, and aligning technical decisions with business logic. From cost optimization to cultural transformation.
Building Automation Services with Go: Practical Tools & Real-World Solutions
Master building useful automation services and tools with Go. Learn to create production-ready services that solve real problems: log processors, API monitors, deployment tools, data pipelines, and more.