LLM API Cost Optimization with Prompt Caching and Peak/Off-Peak Scheduling
LLM API bills are usually calculated from uncached input, cached input, output, and time-of-day multipliers rather than from conversation turns. This article explains how to turn those factors into a practical cost model, design stable prompt prefixes for cache hits, move deferrable workloads outside peak windows, route tasks by value, and use queues, retry controls, and dimensional observability to keep spending predictable. The goal is to treat pricing as part of capacity planning, so future price changes become parameter updates rather than architectural rewrites.
Bills for large language model (LLM) APIs are usually not settled by conversation turn. They are split by input, output, and whether cache was hit. When the business gets busy, contexts grow longer, retries increase, and peak-hour limits stack up. Costs can drift away from budget within days. Cost governance starts by treating pricing rules as part of capacity planning rather than as a post-launch surprise.
Start by Decomposing the Bill into Calculable Factors
Common billing dimensions can be abstracted into four categories. Specific values depend on each platform’s published pricing. The numbers below only illustrate the method.
- Input that misses cache: the entire new context is charged at the higher input price.
- Input that hits cache: repeated prefixes, system prompts, or stable knowledge fragments are charged at a lower input price.
- Output: generated length is priced separately and is often the most elastic part of total cost.
- Time-of-day multiplier: peak windows such as weekday daytime may be several times the price of idle windows. Idle windows may cover nighttime, midday, and weekends.
For an illustrative example, assume relative prices for off-peak periods are 0.02 for cached input, 1 for uncached input, and 4 for output per million-token scale, with peak prices at twice those values. Suppose a call has 8,000 input tokens, including 6,000 cached tokens, and 1,000 output tokens. The off-peak cost is the sum of the cached portion at the lower input price, the uncached portion at the higher input price, and output at the output price. At peak, multiply the total by the time-of-day factor.
At this order of magnitude, raising the cache hit rate from 0 to 75% reduces input-side cost by a clear step. Moving deferrable work out of the peak window can then halve the time-of-day factor again. Combined, these levers are often more controllable than switching to a smaller model, because they do not reduce the upper bound of answer quality.
Pay attention to units. Some prices are listed per thousand tokens and others per million tokens. Peak definitions may also be split by calendar day. Before launch, encode one conversion method in the cost table so the dashboard and the invoice do not diverge.
Why Caching Reduces Cost and When It Stops Working
Prompt caching works by having the service recognize a prefix that is the same as one in recent requests and reuse the completed prefill computation. This lowers the price for the caller and saves compute for the platform. It does not return a previous answer verbatim. The generation stage is still calculated for the new question, so the output price usually does not disappear because of caching.
To keep hit rates stable, the prefix must be stable:
- Put system instructions, tool descriptions, and output-format constraints first, and version them. Do not prepend random introductions each time.
- Place long documents, policy clauses, codebase summaries, and other rarely changing context immediately after that. Put user questions, timestamps, and request IDs at the end.
- In multi-turn conversations, confirmed history that will not be rewritten can keep its original order. Frequently rewriting earlier text can invalidate the entire prefix.
- Do not insert dynamic fields such as the current time, user nickname, or one-time trace ID into the middle of a long prefix.
Caching also has a time to live. Repeated questions separated by long intervals may become cache misses again. If a batch process spreads jobs with the same prefix across the whole day, the hit rate will be lower than if those jobs are sent together in a short period. From an engineering perspective, schedule jobs that share a prefix as consecutive batches rather than distributing them evenly across 24 hours.
Nor should you lengthen the prefix without limit just to achieve cache hits. On a miss, an extremely long input is expensive by itself. On a hit, if the output still has to read through all constraints, latency also rises. The principle is this: only stable content that will be reused multiple times belongs in the cache region. One-off material belongs directly with the question, and total length should be controlled.
Peaks and Off-Peak Windows Are Capacity Signals, Not Coupons
Higher prices during peak periods reflect tighter concurrency and compute capacity. For the caller, this means three types of tasks should be separated:
- Interactive latency-sensitive tasks: online customer support, coding assistants, and approval assistance. Users are waiting, so these can remain during business peaks, but context and output limits should be constrained to avoid an extremely long generation from one click.
- Deferrable tasks: daily report summaries, knowledge-base rebuilds, evaluation-set runs, and offline quality checks. Put these into queues and process them during idle windows.
- Elastic tasks: internal experiments and prompt regression tests. By default, run these only during idle periods. During peaks, require manual approval.
Off-peak scheduling does not mean that models are allowed to be used only at midnight. If the business itself happens during the day, forcing everything out of daytime harms the user experience. A better approach is to split requests: during the day, perform short-context decisions or retrieval-based answers; send long-document summarization, multiple-candidate generation, and self-verification rounds to queues and write results back asynchronously. Users perceive “conclusion first, details later,” not “the API is unavailable.”
Also prevent retry storms. Retrying immediately after a timeout can charge the same input again as a cache miss during peak, or pay for output again. Use exponential backoff, idempotency keys, and a maximum number of attempts. Save truncated partial generation so the entire run does not have to be repeated.
Align Unit Price and Quality with a Tiered Strategy
If cost optimization relies only on off-peak scheduling, quality may be sacrificed during peaks. A more reliable approach is to choose paths by task value rather than binding the entire application to a single model specification.
- Routing: classification, extraction, and format validation can use faster, lower-unit-price specifications. Open-ended writing and complex reasoning can use more capable specifications. Routing rules should use input features such as length, whether code is present, and whether multi-step tools are required, rather than guesswork.
- Output budget: set a maximum generation length for each task type. Much cost comes from models writing answers as tutorials. Structured fields, early stopping conditions, and requiring key points first with expansion only on demand can all reduce output.
- Context budget: inject only retrieval fragments relevant to the question, not the entire knowledge base. If retrieval fails, degrade explicitly; do not repeatedly ask follow-up questions with empty context.
- Tool calls: every additional model round trip re-bills input and output. Filtering, ranking, and numerical calculation that can be done in the application should not be sent back to the model.
As an illustrative comparison, consider 1,000 policy question-answering requests. If each request inserts a 20,000-token full policy text with no cache, input cost will dominate the bill. If retrieval first narrows this to 1,500 tokens and the system prompt is stable enough to achieve a high hit rate, input cost falls and output length becomes the next optimization target. The optimization order should follow the structure of the bill, not intuition.
Scheduling, Queues, and Failure Handling
Deferrable traffic is better expressed through queues than through synchronous calls inside business threads.
Suggested job fields:task_type interactive / deferrable / experimentalpriority order only within idle windowsnot_before earliest allowed start time aligned with idle windowsprefix_version shared-prefix version for same-batch sendingmax_output generation limitidempotency_key prevent duplicate charges
The scheduler should stop pulling deferrable jobs before peak begins. After the idle window starts, it should group jobs by prefix_version so that identical prefixes execute consecutively. The grouping window does not need to be long; a few minutes of clustering is often better for cache hits than random ordering.
Failures should be classified. Parameter errors and non-compliant content should fail directly and raise alerts. Do not retry them. Rate limits and brief timeouts can be retried with backoff, but they should count against a budget of attempts times estimated tokens. After a threshold is reached, switch to manual handling or a degraded answer. Degradation can mean a shorter context, a lower output limit, or returning retrieved snippets for a human to read, rather than unlimited model switching and rerunning.
Observability: You Cannot Optimize Without Dimensional Metrics
At a minimum, record the following by application, task type, and time window: request count, input tokens, cache-hit tokens, output tokens, retry count, end-to-end latency, and estimated cost. Estimate cost locally using published prices, then reconcile against the billing cycle. If the deviation exceeds a threshold, check whether the peak multiplier or unit conversion was missed.
Useful derived metrics include:
- Cache hit rate = cached input / total input. Review it by prefix version, not only as a global average.
- Peak cost share. If deferrable tasks still account for most peak-period cost, the queue strategy is not working.
- Effective output cost per successful result = cost / business-accepted results. Rejected results, retries, and unread long outputs show up here.
- Output/input ratio. An abnormal increase is often related to prompts that encourage verbosity or to missing stopping conditions.
Do not focus alerts only on the total amount. Earlier signals are a sharp drop in hit rate, often caused by a prompt revision that scatters the prefix, and a rising retry rate, often caused by a timeout threshold below actual latency.
Governance and Common Pitfalls
Write pricing, peak definitions, and cache rules into a one-page internal document, and tie it to application quotas: each application has a daily budget, a peak budget, and a default task type. Experimental traffic should use a separate quota so it does not crowd out online budgets.
Common pitfalls include the following. First, treating illustrative prices or old screenshots as long-term contract prices; when the platform changes its pricing, the entire cost model becomes wrong. Second, placing user privacy data or one-time keys into a stable prefix to obtain cache hits; this harms security, and small differences prevent reuse anyway. Third, cutting costs during peak by shutting down online capabilities; the business loss can exceed the model fees. Fourth, optimizing only input while leaving output uncontrolled; summarization tasks will still overrun.
The launch checklist can be short: stable and versioned prefixes; dynamic fields placed at the end; interactive and offline traffic separated; queues that respect idle windows; bounded retries with idempotency; dashboards that include hit rate and time-window cost; and budget recalculation when prices change. Once these are in place, a price cut or price increase becomes a parameter update rather than an architecture rework.
