Introduction
Running LLM applications in production reveals a stark reality: inference costs scale non-linearly with usage, and teams often discover their budget projections were optimistic by orders of magnitude. A system that costs $50/day during development can reach $5,000/day under production load without architectural changes. This post outlines practical strategies for containing costs while maintaining output quality, drawing on patterns observed across production deployments.
The key insight is that cost optimization is not a single technique but a layered approach. Each layer addresses a different cost driver, and their effects compound. Teams that implement multiple layers typically achieve 70-90% cost reduction compared to naive single-model deployments.
Layer 1: Model Selection and Routing
Right-Sizing Model Choice
The most impactful decision is matching model capability to task requirements. Using a flagship model for every query is the single largest source of waste. Production systems should classify queries by complexity and route them appropriately:
Simple classification and extraction (sentiment, intent, entity extraction): Use smallest available models. These tasks rarely benefit from advanced reasoning and smaller models achieve 95%+ accuracy at 1-5% of the cost.
Structured output generation (JSON, SQL, code): Use mid-tier models optimized for instruction following. These models handle formatting constraints reliably without flagship-level reasoning.
Complex reasoning and synthesis (debugging, analysis, creative writing): Reserve flagship models for tasks that genuinely require them. These typically represent 10-20% of total query volume.
Implementation Pattern: The Router
Implement a lightweight classifier (often a small model or rule-based system) that inspects incoming queries and assigns a complexity tier. The router adds minimal latency (1-5ms) and cost (<$0.0001 per query) while directing traffic efficiently.
def route_query(query: str) -> ModelTier:
# Fast heuristic: check for complexity indicators
if has_complex_reasoning_keywords(query):
return ModelTier.FLAGSHIP
elif requires_structured_output(query):
return ModelTier.MID_TIER
else:
return ModelTier.EFFICIENT
Layer 2: Prompt Optimization
Token Budget Management
Every token in your prompt costs money twice: once for input, once for output (which is typically more expensive). Reducing prompt size directly lowers per-query cost.
Remove conversational filler: Phrases like "Please," "Thank you," "I would appreciate if you could" add tokens without improving output quality. Direct instructions work better: "You are a classifier. Output JSON only."
Compress few-shot examples: Two well-chosen examples often outperform ten mediocre ones. Select examples that cover the decision boundaries in your task, not just common cases.
Use structured templates: Replace verbose natural language instructions with structured formats. "Classify as: POSITIVE, NEGATIVE, NEUTRAL" is shorter and more reliable than "Please classify the sentiment of the text as either positive, negative, or neutral."
Dynamic Prompt Assembly
Build prompts from modular components assembled per query rather than using a monolithic prompt. Include only the instructions, examples, and context relevant to the specific query type. This prevents paying for irrelevant content on every request.
Layer 3: Caching Strategies
Response Caching
Cache LLM responses for identical or semantically similar queries. This is most effective for:
- Repetitive customer queries (FAQs, status checks)
- Deterministic transformations (formatting, extraction)
- Batch processing with duplicate inputs
A 60% cache hit rate on repetitive workloads reduces effective cost by 60% for those queries. Implement semantic caching using embeddings to catch near-duplicate queries that exact matching misses.
Prompt Caching (Provider-Level)
Many providers (Anthropic, OpenAI) offer prompt caching where common prompt prefixes are cached at the provider level. Structure your prompts with stable prefixes (system instructions, few-shot examples) and variable suffixes (user query, retrieved context) to maximize this benefit.
Layer 4: Architectural Patterns
Retrieval-Augmented Generation (RAG) Over Long Context
Feeding large documents into context windows is expensive. A 100K token context at $0.003/1K tokens costs $0.30 per query just for input. RAG retrieves only relevant passages (typically 2-5K tokens), reducing input costs by 95% while often improving accuracy by reducing noise.
Model Cascading
Implement a cascading pipeline where queries flow through progressively more capable models until one produces a confident result. Start with the cheapest model, validate its output, and escalate only when confidence is low. This achieves near-flagship quality at a fraction of the cost because most queries resolve at lower tiers.
Batch Processing for Non-Real-Time Workloads
For workloads without strict latency requirements (report generation, data enrichment, content moderation), batch requests to maximize throughput efficiency. Providers often offer batch APIs at 50% lower cost. Even without batch APIs, batching reduces infrastructure overhead.
Layer 5: Operational Practices
Continuous Cost Monitoring
Implement per-query cost tracking with query-type breakdown. Alert on cost anomalies and track cost trends per model tier. Cost per query should decrease over time as optimizations compound; increases signal problems.
Regular Model Evaluation
New model releases often provide better price/performance. Evaluate new models against your production workload quarterly. A 20% quality improvement at 50% lower cost justifies migration effort.
A/B Testing Framework
Test optimizations (prompt changes, model swaps, routing rules) against held-out evaluation sets before deploying. Measure both quality metrics and cost impact. Reject changes that degrade quality beyond acceptable thresholds regardless of cost savings.
Worked Example: Customer Support System
A hypothetical support system handling 50,000 queries/day:
| Tier | Query % | Model | Cost/Query | Daily Cost |
|---|---|---|---|---|
| Simple (classification) | 45% | Efficient | $0.0005 | $11.25 |
| Moderate (extraction) | 35% | Mid-tier | $0.003 | $52.50 |
| Complex (reasoning) | 20% | Flagship | $0.03 | $300.00 |
Before optimization: All queries to flagship = $1,500/day After routing: $363.75/day (76% reduction) With 40% cache hit rate on simple/moderate: $262.50/day (83% reduction) With RAG replacing long context on complex: $180/day (88% reduction)
Common Pitfalls
Over-Optimizing Simple Queries
Spending engineering effort optimizing queries that already cost <$0.001 is rarely worthwhile. Focus on the expensive tail: the 20% of queries that represent 80% of costs.
Sacrificing Quality Without Measurement
Cost reductions that degrade user-facing quality often cost more in support burden and churn than they save. Always measure quality impact before deploying cost optimizations.
Ignoring Infrastructure Costs
Model inference is not the only cost. API gateway, logging, monitoring, and caching infrastructure add overhead. Include these in total cost calculations.
Conclusion
Cost optimization in LLM applications is an ongoing practice, not a one-time project. Start with model routing—it typically delivers the largest single improvement with the least complexity. Layer on caching, prompt optimization, and architectural patterns as needed. Measure continuously, test rigorously, and treat cost as a first-class metric alongside latency and quality.
Related: Fine-Tuning vs RAG: A Decision Framework for LLM Customization