Engineering Practices for LLM API Cost Optimization
This article breaks down LLM API billing into its main cost drivers and shows why switching to cheaper models often misses the point. It covers off-peak scheduling, input-side context reduction, output control and model routing, and observability, with practical Python examples for each. Readers will learn a measurable, repeatable workflow for lowering per-task API costs.
I recently ran a very simple calculation: a task of moderate complexity triggered about thirty web retrievals, accumulated just over 200,000 input tokens and more than 40,000 output tokens, all priced at the lightweight model tier during weekday peak hours. Before adjusting the billing and scheduling strategy, the cost per task was about 0.93 yuan; afterward it dropped to about 0.77 yuan, of which retrieval-related add-on fees accounted for roughly 17% of total spending, or about 0.166 USD. Staring at that number for a while, I honestly almost laughed: five days of engineering work saved less than the price of a bottle of water.
What is actually worth writing down is not those few cents, but a common misconception it exposed: when most teams optimize model costs, their first instinct is to switch to a cheaper model or cut output length, while the largest slice of the bill—the per-token price tier—stays untouched. The optimization happens at the margin, while the cost structure remains unchanged.
1. Break Down the Bill First: What Actually Drives Cost
The first step to reducing cost is not writing code, but splitting the bill into items that can be optimized independently. Under the mainstream pay-as-you-go model, a bill usually stacks four components:
- Input token cost: includes system prompts, conversation history, and retrieved reference material, often the largest item in long tasks;
- Output token cost: the unit price is typically several times that of input, and it scales quickly in long-text generation tasks;
- Add-on capability cost: web retrieval, content moderation, embedding, speech, and other multimodal capabilities, usually billed separately by call count or data volume;
- Time-of-day and tier differences: the same model has different unit prices across load periods and capability tiers.
Take a common general pricing structure as an example: the lightweight tier costs about 1.2 USD per million output tokens at peak, a more capable tier about 3.96 USD, and off-peak usually comes with a 50% discount. Peak generally means 9:00 a.m. to 12:00 p.m. and 2:00 p.m. to 6:00 p.m. Beijing time on weekdays; weekends and public holidays fall into off-peak.
The conclusion is direct: the largest share of total spending is the price tier and time window, not minor add-ons like retrieval fees. If you want to save money, first look at what time your workloads are running.
2. Off-Peak Scheduling: A Discount You Get Without Changing a Single Prompt
The 50% off-peak discount is the easiest saving on the bill and the most easily overlooked. Its essence is moving deferrable workloads out of crowded periods—trading time for price.
Three criteria help decide which tasks can be shifted off-peak: whether a user is waiting in real time; whether there is a firm delivery deadline; and whether retry cost on failure is manageable. Offline batch processing, log and document summarization, bulk code repository scanning, data cleaning and labeling, nightly regression tests, and offline evaluation usually qualify; while online chat, real-time completion, and payment risk control must stay at peak.
In practice, you do not need a complex scheduling system—an executable decision function is enough:
from datetime import datetime, timezone, timedeltaCST = timezone(timedelta(hours=8))PEAK = [(9, 12), (14, 18)]def is_peak(now: datetime | None = None) -> bool:"""Return True during peak hours; weekends and public holidays are off-peak."""now = now or datetime.now(CST)if now.weekday() >= 5:return Falsehour = now.hour + now.minute / 60return any(start <= hour < end for start, end in PEAK)def submit(task, queue_peak, queue_offpeak):"""Deferrable tasks go to the off-peak queue during peak hours; others use the regular queue."""if task.deferrable and is_peak():queue_offpeak.put(task) # runs off-peak, usually at a discounted unit priceelse:queue_peak.put(task)
Three engineering points to watch: first, holidays need a maintained calendar dataset rather than relying on weekends alone; second, the off-peak queue needs a maximum delay cap so tasks do not pile up indefinitely; third, an “urgent task jump-the-queue” channel must be preserved, otherwise off-peak scheduling will wreck timeliness.
3. Input-Side Optimization: Long Context Is the Most Expensive Baggage
Input tokens are often underestimated. Stuffing tens of thousands of tokens of retrieved material into every request makes cost grow linearly with call count. The available techniques, ranked by cost-effectiveness:
- Context compression: apply extractive summarization to retrieved snippets first, keeping only paragraphs relevant to the question before sending them to the model;
- Prefix stability and cache reuse: place the system prompt, tool descriptions, and long-term unchanged reference material at the very front of the request and keep it byte-level stable, so the server-side context cache has a chance to hit and can significantly cut billing for repeated input (the exact discount ratio depends on your platform’s current rules);
- History trimming: compress multi-turn conversations into a structure of “keep the first-turn setup + the most recent few turns + a summary of key conclusions” instead of concatenating everything;
- Retrieval count convergence: run a small-model relevance check first, and only expand into full retrieval for genuinely relevant queries, cutting thirty calls to under ten.
Illustrative context assembly logic:
def build_messages(system_block, retrieved, history, question,max_context=12000):"""Stable prefix first, retrieved snippets truncated by relevance, history reduced to a summary plus the last two turns."""parts = [system_block] # stable prefix, helps cache hitsbudget = max_context - count_tokens(system_block)for chunk in sorted(retrieved, key=lambda c: c.score, reverse=True):cost = count_tokens(chunk.text)if cost > budget:breakparts.append(chunk.text)budget -= costparts.append(summarize(history)) # compress history into a summaryparts.append(history[-2:])parts.append(question)return parts
4. Output Side and Model Routing: Spend Capability Where It Counts
Output unit prices are high, so “making the model write less” saves more money than “making it write better.” Structured output (fixed fields, enumerated values, short conclusions) is usually an order of magnitude cheaper than free-form long text; when long text is needed, generate in segments and confirm section by section, avoiding a single generation followed by a full rewrite.
Tiered routing is another lever: hand intent recognition, format validation, and simple classification to the lightweight tier; escalate only complex reasoning, code generation, and long-form writing to the high-capability tier. A minimal implementation:
def route(task):if task.kind in {"classify", "extract", "format"}:return "light" # lightweight tier, lowest unit priceif task.kind in {"reason", "code", "longform"}:return "strong" # high-capability tier, upgraded on demandreturn "light"
Combined with a cache layer (reuse results directly for identical request fingerprints) and batch interfaces (on supporting platforms, asynchronous batch is usually cheaper than real-time calls), per-task cost can drop another notch.
5. Observability: No Measurement, No Optimization
Cost optimization must close the loop. Instrument three dimensions: track tokens and cost by business line, model tier, and time window; record cache hit rate and retrieval call count; set threshold alerts on per-task cost. With this table, you can answer “how much did this change actually save” instead of guessing. If you use general cloud capabilities, you can combine monitoring and alerting, logging services, and object storage to archive billing details into a traceable cost ledger.
6. Conclusion
The money saved over those five days was indeed small, but it bought three more valuable things: a clearly decomposed cost structure, a reusable off-peak and routing strategy, and a continuously measurable optimization loop. Cost governance for LLM usage has never been about finding a cheaper model, but about running each type of task at the right time, with the right tier, and with the least context. Measure first, then shift off-peak, then compress input, control output, and route by tier—get the order right, and the bill will actually go down.
