The Cost Challenge
LLM costs can explode in production. A chatbot that costs 5,000/month once real users show up — and that is before you factor in retries, context stuffing, and the developer who accidentally leftgpt-4o hardcoded in the logging pipeline. The strategies in this chapter are not premature optimization; they are the difference between a sustainable product and one that bleeds money.
Token Counting and Tracking
Understanding Token Costs
The single most important cost insight: output tokens cost 3-5x more than input tokens. This means a chatty system prompt that causes longer responses costs you far more than the prompt itself. If you can get a concise 50-token answer instead of a 200-token one, you save 4x on the expensive side of the bill.Model Routing
Model routing is the highest-leverage cost optimization you can make. The idea is simple: not every question needs GPT-4o. “What’s your return policy?” can be answered by GPT-4o-mini for 1/15th the cost, while “Analyze this contract for liability risks” genuinely needs the bigger model. Routing is the 80/20 rule in action — 80% of requests are simple enough for the cheap model, saving you 80% of that traffic’s cost. Route requests to the cheapest capable model:Rule-Based Routing
For lower overhead, use rules instead of LLM classification. The irony of LLM-based routing is that you are spending tokens to decide how to save tokens. For high-throughput systems (over 1000 requests/minute), the classification call itself becomes a meaningful cost. Rule-based routing is free, instant, and surprisingly effective — simple regex patterns catch 70-80% of cases correctly.Caching Strategies
Caching is the closest thing to free money in AI engineering. If 100 users ask “What’s your refund policy?” today, you should call the LLM exactly once and serve the cached response 99 times. The two approaches below handle different scenarios: exact caching for deterministic queries (same input always means same output), and semantic caching for the real world where “refund policy,” “how do I get my money back,” and “return policy details” should all hit the same cache entry.Semantic Caching
Cache responses for semantically similar queries:Exact Match Caching
For deterministic queries (temperature=0, same system prompt, same user input), the output is always identical. There is zero reason to call the API twice. This pattern is especially powerful for classification, extraction, and structured output tasks where you control the full prompt and the user input has low variance. Pitfall: Do not use exact caching with temperature > 0. The whole point of temperature is to introduce randomness — caching defeats that purpose and gives every user the same “creative” response.Prompt Optimization
Prompt optimization is the low-hanging fruit that most teams skip. A system prompt full of filler words like “Please provide me with a detailed analysis” can be trimmed to “Analyze this” with no loss in quality. Over millions of requests, those extra 15 tokens per call add up to real money. The function below is a starting point — in practice, A/B test your shortened prompts to verify quality holds.Reduce Prompt Length
Context Compression
Batching and Async
Batching is about amortizing overhead. If 10 classification requests arrive within 100ms of each other, sending them as 10 separate API calls means 10x the HTTP overhead, 10x the rate-limit consumption, and often 10x the latency (serial requests). Batching them into a single prompt or parallel async calls is dramatically more efficient. The pattern below collects requests into a batch, waits briefly for stragglers, then fires them all at once.Batch Similar Requests
Cost Monitoring Dashboard
Cost Optimization Checklist
Use Cheaper Models
Implement Caching
Compress Context
Set Budgets
Quick Wins
Cost Optimization Decision Framework
The order matters. Most teams jump straight to complex solutions (fine-tuning, custom models) when the cheapest wins are sitting right in front of them. Follow this sequence.- If your total LLM spend is under $100/month, your engineering time costs more than the savings. Focus on product, not cost.
- If you have no monitoring, you are optimizing blind. Instrument first (track cost per request, per user, per endpoint), then optimize.
- If quality is not measured, you cannot tell whether your “optimization” degraded the product. Set up an evaluation suite before cutting costs.
Edge Cases in Cost Management
Retry storms after API outages. Your retry logic fires 3 attempts per failed request. During an OpenAI outage affecting 1000 requests/minute, that becomes 3000 retries/minute — tripling your cost on the recovery spike and potentially hitting rate limits. Add circuit breakers (see the Deployment and Scaling chapter) and cap total retries per time window, not just per request. Streaming responses that get cancelled. A user starts a chat, gets impatient after 2 seconds, and navigates away. The backend keeps generating tokens until completion. Those output tokens are billed even though nobody reads them. Implement cancellation propagation: when the SSE connection drops, abort the API call. Embedding costs hiding in plain sight. Each RAG query embeds the user’s question. Each document upload embeds every chunk. At 1000 queries/day with 5 re-uploads, that is 1000+ embedding calls that don’t show up in your chat cost tracking. Track embedding costs separately — they can be 10-30% of total spend for RAG-heavy applications. Development and testing costs. Your test suite makes real API calls. Your developers run ad-hoc experiments. Without a separate budget tracker for non-production usage, these costs blend into production metrics and distort your per-user economics. Use separate API keys for dev/staging/prod.What’s Next
Multi-Agent Design Patterns
Interview Deep-Dive
Your AI chatbot costs $5,000/month on GPT-4o. The CEO wants it under $1,000 without users noticing quality degradation. Walk me through your cost reduction strategy in priority order.
Your AI chatbot costs $5,000/month on GPT-4o. The CEO wants it under $1,000 without users noticing quality degradation. Walk me through your cost reduction strategy in priority order.
- The highest-leverage move is model routing. Analyze traffic logs and you will find 60-80% of queries are simple: greetings, FAQ lookups, status checks. Route those to GPT-4o-mini at 1/15th the cost. Reserve GPT-4o for complex reasoning and analysis. A rule-based router (regex patterns) costs zero and catches 70% of cases. This alone cuts costs by 50-70%, bringing 1,500-2,500.
- Second: response caching. In most chatbot deployments, 20-30% of queries are near-duplicates. A semantic cache with a 0.92 similarity threshold eliminates redundant calls. The embedding cost for cache lookup is negligible compared to the GPT-4o call it replaces. This saves another 15-25%.
- Third: optimize prompts. Output tokens cost 4x more than input tokens. If your system prompt encourages verbose responses, you are paying a premium for wordiness. Shorten system prompts, add “be concise” instructions, set max_tokens appropriately. Trimming average response length from 200 to 80 tokens saves 60% on output costs.
- Fourth: compress conversation context. Sending full history on every turn means paying for the same messages repeatedly. Summarize older turns and keep only the last 4-5 verbatim. A 20-turn conversation that sends all history uses 10x more input tokens than one that summarizes after turn 5.
- Combined, these achieve 70-90% reduction. 500-1,000 without perceptible quality loss.
You are implementing semantic caching for an LLM application. How do you choose the similarity threshold, and what goes wrong if you set it too high or too low?
You are implementing semantic caching for an LLM application. How do you choose the similarity threshold, and what goes wrong if you set it too high or too low?
- The similarity threshold is a precision-recall trade-off for your cache. Too high (0.98+) and the cache barely hits — only near-identical queries match, defeating the purpose. Too low (0.85) and you serve wrong answers for queries that are similar but not similar enough. The sweet spot is 0.92-0.95 for most applications.
- The right way to choose: collect 500+ real queries, compute pairwise similarity, and have humans label whether the same response is appropriate for both. Find the threshold where precision exceeds 95% (almost never serve a wrong cached response) while recall is reasonable (catch 20-30% of cache-eligible queries).
- Too-high failure mode: you spend on embedding lookups but almost never hit. A cache with a 2% hit rate might increase costs.
- Too-low failure mode: “What is your refund policy?” and “What is your privacy policy?” might score 0.88 similarity because they share structure, but they need completely different answers. Serving the wrong cached answer is a trust-destroying silent bug.
- Domain matters enormously. In customer service, similar-sounding questions often need different answers (“cancel my order” vs “cancel my account”). In technical documentation, similar questions often have similar answers. Tune per-domain.
Your team debates LLM-based model routing (GPT-4o-mini classifies complexity) versus rule-based routing (regex and keywords). Make the case for each and tell me which you ship first.
Your team debates LLM-based model routing (GPT-4o-mini classifies complexity) versus rule-based routing (regex and keywords). Make the case for each and tell me which you ship first.
- Rule-based routing is free, instant (microseconds), and deterministic. Write 20 regex patterns for simple queries and 15 for complex ones. It catches 70-80% correctly with zero API cost and zero latency. The downside: it misclassifies the 20-30% that match no pattern, and maintaining rules as the product evolves is tedious.
- LLM-based routing is more accurate (90%+) and handles novel query types without rule updates. The downside: every routing decision costs an API call. At GPT-4o-mini rates, the cost is small, but at 1,000 requests per minute the routing calls alone cost $200/month. More importantly, they add 100-200ms latency to every request.
- Ship rule-based first, for three reasons. First, immediate savings with zero spend. Second, it generates data — log every query with its classification and actual model, then review misclassifications. Third, after two weeks you have 50,000+ labeled examples to train a tiny local classifier that is more accurate than the LLM router and runs in 1ms.
- The production answer is a hybrid: rules for the easy 70%, a local classifier for the next 20%, LLM classification for the ambiguous 10%. This gives 95%+ accuracy at near-zero cost.
Output tokens cost 4x more than input tokens. What concrete techniques control output length without degrading quality?
Output tokens cost 4x more than input tokens. What concrete techniques control output length without degrading quality?
- Explicit length constraints in the system prompt are most effective. “Respond in 1-2 sentences” or “Maximum 50 words” dramatically reduces output. But crude limits hurt quality — “explain quantum computing in 10 words” produces garbage. Match the constraint to the task: classification needs 1 token, yes/no needs 1 sentence, explanations need a paragraph, code needs as long as necessary.
- The max_tokens parameter is a hard ceiling, not quality control. Setting max_tokens=100 stops mid-sentence, which looks broken. Use it as a safety net (2x expected length), not the primary control. System prompt instructions let the model self-regulate.
- Structured output eliminates prose overhead. Instead of “The sentiment is positive with 92% confidence because the user expressed satisfaction,” return JSON:
{'"sentiment": "positive", "confidence": 0.92'}. JSON responses are 30-60% shorter for extraction tasks. - Response streaming with early termination is advanced but powerful. Stream the response, and if the first 50 tokens already contain the answer, cancel the stream. This requires careful UX but cuts output costs significantly for factual queries.
- The meta-insight: output optimization and model routing are multiplicative. A simple query on GPT-4o with 200-token response costs 0.0001 — a 100x reduction.