LLM API Cost Control: A Guide to Model Selection and Optimization
Learn how to evaluate new LLMs against business requirements, calculate token-based API costs, and reduce spending through prompt optimization, caching, model routing, and batch processing. The guide also covers architecture, data isolation, and operational safeguards for production applications.
New large language models are arriving at an increasing pace, bringing both new capabilities and new pricing structures. For developers and businesses, two questions matter most: Can the new model solve the business problem, and can the business afford to use it?
Answering those questions requires more than comparing benchmark scores or headline prices. Teams need to understand model limitations, calculate costs for realistic workloads, and build cost controls into their application architecture.
1. What Model Upgrades Change—and What They Do Not
Over the past two years, model sizes have grown from tens of billions to hundreds of billions of parameters. Some open-source models now approach or match early proprietary flagship models on benchmarks involving mathematical problem-solving and multistep reasoning.
These developments indicate broader improvements in foundation-model capabilities. However, parameter count is not the only factor that determines performance. The quality and diversity of pretraining data, along with post-training instruction alignment methods such as RLHF or DPO, also affect instruction following and hallucination control.
Long-context capabilities are improving as well. Newer models can maintain information consistency more effectively across long documents, making them useful for tasks such as legal document analysis and navigating large codebases. But longer contexts also mean more input tokens, higher costs, and greater time to first token. Teams should establish how much context a task actually requires rather than defaulting to the maximum supported length.
Benchmarks measure performance on standardized test sets. Customer support, coding assistance, and document extraction each have different requirements for latency, accuracy, and output-format consistency. Validate models against your own data before making a selection.
2. How LLM API Pricing Works
Most providers charge separately for input and output tokens. Output tokens typically cost more than input tokens.
The basic formulas are:
Cost per request = Input tokens × Input price per token + Output tokens × Output price per token
Daily cost = Cost per request × Daily request volume
When prices are quoted per million tokens, divide token counts by 1,000,000 before multiplying by the listed rate.
Example: A Knowledge-Base Q&A Application
Assume hypothetical prices of CNY 2 per million input tokens and CNY 8 per million output tokens. These figures illustrate the calculation only; consult the provider’s official pricing page for current rates.
Suppose a knowledge-base Q&A application processes 100,000 requests per day, with each request using 6,000 input tokens and generating 500 output tokens:
- Input cost per request: 6,000 ÷ 1,000,000 × CNY 2 = CNY 0.012
- Output cost per request: 500 ÷ 1,000,000 × CNY 8 = CNY 0.004
- Total cost per request: CNY 0.016
- Daily cost: CNY 0.016 × 100,000 = CNY 1,600
If retrieval optimization reduces the input to 2,000 tokens while everything else remains unchanged, the cost falls to CNY 0.008 per request, or CNY 800 per day.
This example shows why input tokens can dominate costs in retrieval-augmented generation (RAG) systems. Reducing retrieved context can have a larger impact than shortening the output.
Additional Pricing Factors
Two details deserve particular attention.
First, tokenization varies across models. The same Chinese text, for example, may consume different numbers of tokens depending on the tokenizer. Measure usage with the provider’s token-counting tools rather than estimating it from character counts.
Second, providers may apply different rates to cached inputs, batch requests, or long-context workloads. Model these pricing conditions separately when estimating costs.
3. Four Ways to Reduce API Costs
3.1 Streamline Prompts and Constrain Output
System prompts often accumulate duplicate rules and outdated instructions. Review them line by line and remove content that is no longer relevant to the task. This directly reduces input tokens on every request.
Output length can also be controlled. Requesting a fixed JSON structure and using a schema to constrain fields can reduce unnecessary explanatory text. Set a max_tokens limit as well to prevent unusually long responses from causing unexpected charges.
3.2 Use Context Caching
Prefix-based context caching depends on matching content at the beginning of a prompt. Place stable system instructions, role definitions, and examples first, followed by user input that changes with each request.
Before using caching, confirm three points:
- Expiration and pricing: Cache time-to-live (TTL) and cache-hit discounts vary considerably by provider. Check the official documentation.
- Data isolation: Cached content may contain user data. Isolate it by tenant or user to prevent cross-user data reuse.
- Misses and failures: Requests that miss the cache or use expired content are charged at the normal rate. Build a fallback path so that a cache-service failure triggers a direct model call rather than an application error.
3.3 Route Requests and Escalate Selectively
Not every request needs a flagship model. A smaller model can first classify requests and handle tasks such as intent recognition, simple Q&A, and format conversion. Requests with confidence below a threshold—for example, 0.8—can then be escalated to a more capable model.
Routing itself adds latency and computational cost, so measure its overhead before deployment. Choose confidence thresholds using offline evaluation results rather than intuition.
Track the share of requests handled by each routing branch and its average cost. These measurements provide the basis for later adjustments.
3.4 Batch Non-Real-Time Workloads
Document archiving, offline annotation, and data cleaning are generally less sensitive to latency. These workloads can use provider-supported batch APIs. Many providers offer discounted batch pricing, but the applicable rates should be verified in the official documentation.
For asynchronous jobs, set concurrency limits to avoid exceeding request quotas during traffic spikes. Include retry handling and checkpoint-based resumption so failed jobs can continue without restarting all completed work.
4. Architecture and Compliance Considerations
A production LLM application typically needs several supporting layers to control usage, protect data, and maintain availability.
Gateway Layer
The gateway handles authentication, rate limiting, usage accounting, and routing across models.
Store API keys in a secrets-management service, not in source code or logs. Apply rate limits by tenant, such as a maximum number of requests per minute.
For billing reconciliation, record the input-token count, output-token count, and model name for every request. If the primary model’s error rate exceeds a defined threshold, the gateway should automatically switch to a backup model.
Data Layer
Store original documents in object storage and write embeddings for document chunks to a vector database.
Configure retrieval with both a Top-K limit and a similarity threshold. For example, a system might include only chunks with similarity scores above 0.75 in the model context.
Irrelevant chunks do more than increase input-token costs: they can also interfere with the model’s judgment.
Task Layer
Use a container platform to run inference services and asynchronous processing tasks, with autoscaling based on message-queue depth.
The message queue buffers traffic spikes. Messages that cannot be processed should move to a dead-letter queue for manual review or scheduled handling.
