9.1 Per-Query Cost Modeling
Total Cost = Input Token Cost + Output Token Cost + Retrieval Cost + Compute Overhead
Example (RAG with a GPT-4o-class model):
System prompt: ~500 tokens × $2.50/1M = $0.00125
Retrieved context: ~2000 tokens × $2.50/1M = $0.005
User query: ~100 tokens × $2.50/1M = $0.00025
Output: ~500 tokens × $10.0/1M = $0.005
─────────────────────────────────────────────
Total per query: ~$0.012
At 10K queries/day = $120/day = $3,600/month
At 100K queries/day = $1,200/day = $36,000/month
9.2 Model Routing Strategy
flowchart TD
Query["Incoming User Query"] --> Classifier["Fast Query Classifier\n(Rule Engine / Cheap Small Model)"]
Classifier -->|Simple (~70% Traffic)\nFAQs, Intent Match, Basic Extraction| Tier1["Flash / Cheap Tier\n(GPT-4o-mini / Haiku / 8B SLM)\n~$0.001 - $0.003 / query"]
Classifier -->|Medium (~25% Traffic)\nStandard RAG, Code Explanation| Tier2["Mid-Tier Model\n(Llama 3.1 70B / Claude 3.5 Sonnet)\n~$0.01 - $0.02 / query"]
Classifier -->|Complex (~5% Traffic)\nMulti-Step Reasoning, Deep Synthesis| Tier3["Frontier / Reasoning Tier\n(GPT-4o / o1 / Claude Opus)\n~$0.05 - $0.15 / query"]
Classification breakdown (typical enterprise distribution):
- Simple (~70% of queries): FAQ, simple extraction, classification → cheapest model
- Medium (~25%): Standard RAG, summarization, code explanation → mid-tier
- Complex (~5%): Multi-step reasoning, complex analysis, creative work → best model
Cost impact example (1M queries/month):
| Strategy | Approx. Cost | Quality |
|---|---|---|
| All frontier model | ~$5,000 | Highest, wasteful |
| All cheap model | ~$500 | Good but risks quality gaps on hard queries |
| Smart routing | ~$445 | Targeted high quality where it matters |
9.3 Token Optimization Techniques
- Prompt compression: Remove redundant instructions, use concise system prompts
- Context window optimization: Only include the most relevant chunks (not max-K)
- Output length control: Set
max_tokensbased on expected response length - Caching: Semantic caching of identical/similar queries (~30% cost savings)
- Batching: Use batch APIs where available (often ~50% cost reduction)
- Streaming: Lets users stop reading early, reducing wasted generated-but-unread output tokens
9.4 Cost Optimization Strategy Summary Table
| Strategy | Typical Savings | Complexity |
|---|---|---|
| Semantic caching | 30-40% for repetitive queries | Medium |
| Model routing (small→large) | 40-70% | Medium |
| Prompt optimization (reduce tokens) | 10-30% | Low |
| Batch processing (off-peak) | 50% with batch APIs | Low |
| Fine-tune smaller model | 60-80% (replaces large model) | High |
| Self-host open-source | Variable; breaks even at ~5K+ queries/day | High |
| Quantization (self-hosted) | 50-75% memory reduction | Medium |
9.5 Cost Governance for Enterprise
- Budget alerts per project/team
- Token tracking dashboard (input, output, cached)
- Model usage policies (which models are approved for which use cases)
- Cost allocation to business units (chargeback/showback)
- Monthly cost reviews with optimization recommendations
- Model version pinning — never point at “latest”; pin exact versions and re-evaluate before migrating
Section 9 — Interview Q&A
Q: How would you reduce costs of a GenAI system spending $50K/month on LLM API calls? A: First, analyze current spend — categorize queries by type/complexity and measure token usage per category to find the top cost drivers. Then implement quick wins (1-2 weeks): semantic caching for repeat/similar queries (30-40% reduction), prompt compression (10-20%), and output-length control (5-15%). Next, implement model routing (2-4 weeks): classify queries by complexity and route ~70% of simple queries to the cheapest capable model, reserving expensive models for the ~5% that truly need them — typically 60-70% savings on its own. Finally, architecture-level optimization (1-2 months): pre-compute answers for top FAQ patterns, use batch APIs for non-real-time work, and consider self-hosting an open-source model for high-volume simple tasks. Combined, this realistically takes $50K/month down to $12-15K/month (roughly 70% reduction) while maintaining or improving quality on the queries that matter most.
Q: Present a build vs. buy cost analysis for an enterprise AI chatbot platform. A: Three paths over a 3-year horizon. Build custom: ~$800K total (heavy Year 1 engineering investment, ongoing maintenance) — full customization and data control but slow time-to-market and engineering risk. Buy SaaS: ~$450K total — fast deployment (4-6 weeks) and vendor-managed reliability, but limited customization and data leaves your environment. Build on open-source + managed services: ~$550K total — moderate customization, faster than full build, retains data control, but still needs in-house AI engineering expertise. Recommendation depends on strategic fit: if the chatbot is core to competitive differentiation, build on open-source; if it’s a supporting feature with standard needs, buy SaaS; if regulatory/compliance demands full control, build custom despite the cost.
Q: What is speculative decoding’s role in cost optimization vs. its role in latency optimization? A: Speculative decoding is primarily a latency optimization — the draft model proposes tokens that the large model verifies in a single parallel pass, cutting wall-clock generation time 2-3x for interactive, latency-sensitive workloads. It’s a secondary cost lever only insofar as lower latency can reduce the number of concurrent in-flight requests needed to hit a given SLA, indirectly reducing GPU fleet size. It’s not a direct token-cost reducer the way caching or model routing are — those remain the primary cost-optimization levers, while speculative decoding, quantization, and continuous batching are primarily throughput/latency levers that show up as cost savings only through infrastructure right-sizing.