LLM API Cost Control: From Token Billing to Cache Optimization
This article explains how to control LLM API costs. It covers building a cost baseline from token usage, judging whether prompt caching is worth its write costs, shortening prompts and outputs, using batch processing and tiered model routing, and tracking spend with monitoring and billing reconciliation.
1. Start With the Billing Model
The cost of a single request can be written as:
Cost per request = input tokens × input price + output tokens × output price + cache-related fees
Input tokens include system instructions, conversation history, retrieved documents, and the user’s current question. Output tokens cover everything the model generates. Most providers charge more per output token than per input token, but the multiple varies by model, so check the provider’s pricing page.
Token counts cannot be estimated from character counts. Chinese and English text are split into tokens differently, and the same sentence can produce noticeably different token counts across models. Read actual values from the usage field in API responses. Before launch, verify typical requests with the provider’s token counting endpoint or a tokenizer tool.
Calculation steps:
- Pull call logs from the past 7 days and calculate the average input and output tokens for each endpoint.
- Multiply those averages by the corresponding unit prices to get the cost per request.
- Multiply the cost per request by the average daily call volume to get each endpoint’s monthly cost.
- Rank endpoints by monthly cost, and optimize the top three first.
2. When Caching Pays Off
Prompt caching benefits depend on each provider’s rules. Common rules include:
- Cache hits are usually determined by exact prefix matching. Similar content does not count as a hit.
- The prefix must reach a provider-defined minimum length before it is cached.
- Cache entries have a time to live (TTL). After they expire, the content must be written again.
- The first write may be billed at the regular input price or at a higher price. Confirm whether cache writes carry a separate charge.
- Cached tokens are billed at the cache hit price. Uncached tokens are still billed at the regular input price.
Use this formula to estimate net benefit:
Net benefit = cached tokens × (regular input price − cache hit price) − extra write cost
The following example uses hypothetical numbers. They do not reflect any provider’s actual prices. Assume the regular input price is CNY 10 per million tokens and the cache hit price is CNY 1 per million tokens. An endpoint receives 1 million input tokens per day. Of these, 800,000 tokens are a fixed system prompt and reference documents, and they hit the cache once per day. The cached portion saves about CNY 7.2 per day (0.8 × (10 − 1)). If the write cost is CNY 5 per day, the net benefit is about CNY 2.2 per day. At low traffic, caching saves little, so measure actual data before committing to it.
Practical guidelines:
- Place stable content, such as system instructions, fixed examples, and reference documents, at the start of the prompt. Place variable user input at the end. This raises the prefix hit rate.
- Track the cache hit rate, calculated as cached tokens divided by total input tokens. If the hit rate stays low, first check whether the prefix changes often. Adjust the caching strategy only after that.
- Cached content may contain business data. Confirm the provider’s data isolation and retention policies.
3. Prompt and Context Optimization
The goal is to reduce wasted tokens while keeping output quality. Use this checklist:
- Organize prompts with a fixed structure. Separate the role, task, constraints, and output format into distinct sections.
- Limit few-shot examples to 2 or 3. Keep only the fields that determine the output format.
- Set
max_tokensas an output cap. For list-style outputs, configure stop sequences. - In multi-turn conversations, keep the most recent few turns in full and compress earlier content into a summary. Set a threshold, for example, triggering compression when the history exceeds about 4,000 tokens.
- Estimate token counts before sending each request. Trim or reject requests that exceed the budget. Do not wait for the bill to reveal the problem.
Before and after example:
Before:
“Please act as a highly professional customer service expert with extensive experience. Carefully read the customer message below, analyze the customer’s emotions and problem in detail, and then reply in a very polite and as comprehensive a way as possible. The reply should include a greeting, problem analysis, a solution, and a closing.”
After:
“Role: customer service assistant.
Task: Classify the emotion of the message (positive/neutral/negative) and write one reply of no more than 60 characters.
Output JSON: {“emotion”: “”, “reply”: “”}”
Both prompts make the same requests, but the optimized version is shorter. A fixed output format lets the program parse results directly, which reduces retries caused by malformed output.
4. Batch Processing and Tiered Calls
Batch processing suits tasks that do not need real-time responses, such as offline labeling or nightly report generation. If a provider offers an asynchronous batch interface, its prices are usually lower than real-time pricing, but results take longer to return. Check the relevant API documentation for specifics. Before using batch processing, confirm the following:
- The task can tolerate delay, and its results do not affect real-time user interactions.
- Each request is independent. Do not combine unrelated requests in one prompt, because they can interfere with the model’s output and make results hard to split.
- Each request has a unique ID. Match results back to requests by ID to prevent misalignment.
- On failure, retry only the failed items. Set a maximum number of retries (for example, 3) and use exponential backoff to avoid rate limits.
- Deduplicate inputs before submission so that each unique input is submitted once.
Tiered calling depends on routing rules. Use these three criteria:
- Task type: Route tasks with clear rules, such as classification, extraction, and format conversion, to a small model first.
- Confidence: Small model outputs should include a confidence score or pass validation rules. Escalate outputs below the threshold to a large model.
- Cost budget: If the estimated cost of a request exceeds the limit, route it to manual review or a lower-cost fallback.
Before a small model takes production traffic, test it on at least 200 manually labeled samples. Measure three metrics: accuracy, format compliance rate, and average latency. Connect traffic to the model only after all three meet the business acceptance thresholds. Escalate to a large model when format validation fails, when confidence falls below the threshold, or when a user disputes the result.
5. Monitoring and Auditing
Without monitoring, you cannot tell whether optimization works. Track at least the following metrics:
- Daily input and output tokens, broken down by endpoint and model.
- Average tokens per request, to detect prompts that grow over time.
- Cache hit rate for each endpoint.
- Cost share and ranking change for each endpoint.
- Failure rate, retry count, and P95 latency.
Alert rule examples: Notify the owner when an endpoint’s daily cost exceeds 1.5 times its 7-day average. When an endpoint’s cache hit rate drops noticeably for 3 consecutive days, check whether its prefix has changed.
Logs should record the request ID, endpoint name, model name, token breakdown, cache hit status, and business tag. If raw content contains personal information, anonymize it before storage. Set log retention periods according to compliance requirements, and restrict access to logs.
Encrypt cached content at rest and set a TTL. Include a tenant identifier in cache keys so that content cannot be reused across different users. Each week, reconcile the bill against business volume, such as request counts and active sessions. When the deviation exceeds expectations, investigate line by line.
Recommended rollout order:
- Calculate the current baseline cost using the formulas above.
- Pilot caching on one high-frequency endpoint. Record its hit rate and net benefit.
- Compress prompts and set output limits.
- Enable batch processing for offline tasks, and route simple tasks to a small model.
- Set up monitoring and weekly reconciliation. Review the results once a month.
