Cost Optimization Practices for LLM APIs in the Midst of Falling Prices
This article explains why large language model API costs are driven by multiple dimensions rather than a single per-token number, and how engineering teams can control them. It breaks down a general cost model covering cache-hit and cache-miss input pricing, output pricing, and time-of-day rate multipliers, then walks through practical measures: building cache-friendly prompts with stable prefixes, shifting deferrable workloads to off-peak windows, compressing context and output through summarization, structured JSON responses, and tiered model routing, and establishing observability with token usage, cache hit rate, and cost metrics. The guidance is platform-neutral and applies to any LLM API where these pricing dimensions exist.
1. Reading the Signal: The Cost Logic Behind a Price Cut
A cloud provider’s LLM platform recently announced a price reduction for its lightweight inference model series. The adjustment covers three items: the price for cache-hit input, the price for cache-miss input, and the output price. It also defines two separate rate schedules for peak and off-peak hours, with peak pricing set at twice the off-peak rate.
The move itself is not surprising, but it brings a long-overlooked fact into the open: the cost of an LLM call is not a single number, but a function determined by several dimensions.
When many teams evaluate whether to adopt an LLM, they look at one rough figure—“dollars per thousand tokens”—and then discover the actual bill is several times the estimate. There are usually three reasons:
- Input and output are treated as one thing, while the output unit price is often significantly higher than the input side.
- The caching mechanism is ignored, so repeated long contexts are billed at full price again and again.
- The time dimension is ignored, so batch jobs that could run off-peak are placed in peak windows.
So instead of focusing on how large a single price cut is, it is more useful to focus on decomposing the cost structure. Prices will keep changing, but the methodology for cost governance is stable.
2. Breaking Down the Cost Model: What You Are Actually Paying For
General LLM billing can be abstracted as follows:
Cost per request =cache-miss input tokens × miss unit price+ cache-hit input tokens × hit unit price+ output tokens × output unit price+ optional add-on fees such as retrieval/tool callsFinal bill = Σ (cost per request × time-window multiplier)
Here, the time-window multiplier takes a larger value during peak hours and a smaller value during off-peak hours. This formula reveals three optimization points:
- Hit rate is the highest-leverage item. The cache-hit unit price is typically only a fraction of the miss price. If fixed prefixes such as system prompts, knowledge base snippets, and tool definitions can be reused reliably, cost reduction is multiplicative rather than linear.
- Output is the most expensive segment. The output unit price is often several times the input price. Controlling output length, preventing the model from being verbose, and replacing long text with structured output all pay off directly.
- The time-window multiplier is purely a scheduling problem. The same request moved to an off-peak window can cost half as much, with no change to any business logic.
3. A Cache-Friendly Architecture: Keep Fixed Prefixes Stably Reused
A cache hit requires the request prefix to be identical at the byte level. In practice, many cases of “we clearly have a fixed prompt but almost never hit the cache” come from the prefix being changed unintentionally. The following conventions are recommended:
- Fixed ordering: concatenate system instructions, tool/function definitions, few-shot examples, knowledge base context, and user input in a fixed order. Never put variable content first.
- No timestamps or random values in the prefix: debug information, request IDs, and the current time should go at the end or be moved out of the prompt.
- Version prompts: treat a prompt change as a “cache invalidation event” and roll it out gradually, so the hit rate does not drop to zero across the board at once.
- Stable knowledge base chunking: once a chunking strategy for retrieved snippets is chosen, do not change it frequently; changes to chunk boundaries change the prefix hash.
Illustrative code:
def build_prompt(system, tools, retrieved, user_input):# The prefix must be stable: same content means same bytesprefix = f"[SYSTEM]{system}\n[TOOLS]{tools}\n[KB]{retrieved}"# Put variable content last so it does not pollute the cached prefixreturn prefix + f"\n[USER]{user_input}\n[META]{trace_id}"
4. Request Scheduling: Move Deferrable Workloads to the Trough
Peak hours usually correspond to the core working hours of the local business day—morning and afternoon on weekdays—and the rest of the time is off-peak. The price gap between the two can reach a factor of two. Cost-sensitive businesses should establish a “load tiering” mechanism:
| Workload type | Latency requirement | Recommended strategy |
|---|---|---|
| Online interaction, customer support Q&A | Seconds | Run during peak hours; focus on output length and cache optimization |
| Offline batch processing, data cleaning, batch summarization | Minutes to hours | Buffer in a queue and schedule to off-peak windows |
| Training data synthesis, evaluation regression | No strict deadline | Fully shift off-peak, with checkpoint resume |
A minimal workable off-peak scheduling skeleton:
import queue, timedef in_peak(now=None):t = now or time.localtime()# Mon-Fri 9-12 and 14-18 are treated as peak (illustrative logic)return t.tm_wday < 5 and (9 <= t.tm_hour < 12 or 14 <= t.tm_hour < 18)def submit(job, q: queue.Queue):q.put(job) # enqueue first, do not call directlydef worker(q: queue.Queue, call):while True:job = q.get()while in_peak() and not job.urgent:time.sleep(60) # non-urgent jobs wait for off-peakcall(job)q.task_done()
It is worth stressing that off-peak scheduling is not a sacrifice of user experience; it moves the portion of traffic whose users are insensitive to latency out of the expensive window. Combined with queue backlog monitoring and alerting, you can secure a predictable cost discount while still meeting SLAs.
5. Context and Output Governance: Compress Every Token
- Context trimming: for long conversations, use a sliding window plus summary compression and keep only the fragments the task requires; in retrieval scenarios, rerank before truncating, rather than following the “fill it up to be safe” habit.
- Structured output: ask the model to return short JSON that conforms to a strict schema instead of long natural language, then render it into a user-readable form in code. Output tokens often drop by more than half.
- Tiered model routing: route simple tasks such as intent recognition and format validation to lightweight models, and escalate to higher-capability models only for complex reasoning. This is a key lever for balancing cost and quality.
- Streaming and early termination: for tasks where convergence can be judged, stop generation once a confidence threshold is met, avoiding payment for a redundant suffix.
6. Observability: No Measurement, No Optimization
Cost governance must land on metrics. At minimum, collect token usage by business line/tenant, cache hit rate, input-to-output ratio, average output length, share of requests during peak hours, and cost per task. Feed these metrics into your logging service and monitoring/alerting system, and set day-over-day and budget-threshold alerts so you can intervene before an anomaly amplifies.
At the same time, build a habit of “regression evaluation”: for any change to prompts, retrieval strategy, or model routing, compare both the quality and cost curves on a fixed evaluation set, so quality is not quietly lost in the name of saving money.
7. Closing
Price adjustments are the norm, and the overall trend is downward. What really separates teams is treating cost as an engineering variable that can be designed. Optimize along four main lines—cache hit rate, output length, time-window scheduling, and observability—and any price cut will automatically translate into real savings. To implement the above on Baidu AI Cloud, you can use its general capabilities such as model services, message queues, logging services, and monitoring/alerting to build an off-peak pipeline and a cost dashboard, without binding to any proprietary interface.
