LLM API Cost Optimization: A Practical Guide to Token Budgets, Caching, and Model Routing

    As LLM API prices rise, engineering teams need a structured approach to inference cost control. This guide breaks down the request cost model, then walks through four optimization paths—token budget governance, cache strategy design, model routing with tiered fallback, and observability with cost attribution—along with common pitfalls and a rollout checklist.

    1. Why a Price Change Affects the Whole Stack

    A model provider recently announced a price increase for its next-generation LLM API: $10 per million input tokens and $50 per million output tokens, up from $5 and $30 for the previous generation. Cache reads and writes are now billed separately.

    Setting the exact numbers aside, three things matter to developers: a clear price gap between input and output, cache operations priced independently, and higher unit prices with each generation.

    Together they point to one conclusion: calling an LLM is no longer a coarse “pay per call” model, but a capability that requires fine-grained cost engineering. The provider sets the unit price, but the caller controls token volume, cache hit rate, and model selection. Governing these three levers is usually more effective than waiting for prices to drop.

    2. Cost Model Breakdown: Where the Money Goes

    The bill for a single request can be abstracted as:

    1. total cost = input tokens × input price
    2. + output tokens × output price
    3. + cache write tokens × write price
    4. + cache read tokens × read price

    Four basic observations follow:

    1. Output costs more than input, often several times more. In generative tasks, output length is the most sensitive cost variable, so max_tokens must match actual business needs rather than a “safe” large value.
    2. Input cost is driven by context. System prompts, conversation history, retrieved passages, and tool definitions all add up on the input side, making long context the main amplifier of the bill.
    3. A cache write is a one-time investment; a cache read is a repeated return. Caching only pays off when the same prefix is reused; a one-off long prompt that writes to cache increases spend.
    4. Caches have lifecycle and capacity limits. A hit requires an exact prefix match, so injecting a timestamp, random ID, or username early will invalidate the cache.

    3. Optimization Path 1: Token Budget Governance

    Treat tokens as a resource that needs budgeting, not a free environment variable.

    • Establish a budget baseline: track daily input/output tokens per business line to build a comparable baseline curve, and locate anomalies before optimizing.
    • Slim down prompts: remove repeated phrasing and redundant examples, and replace few-shot examples with dynamically retrieved injection that carries only the necessary samples.
    • Trim context: summarize and compress conversation history, rerank and truncate retrieval results, and keep only passages relevant to the current question.
    • Constrain output: define a structured output format, use field constraints instead of free-form long text, and set length limits for summarization tasks.
    • Validate up front: decide before each call whether an LLM is actually needed, and keep rule-solvable problems out of the model pipeline.

    Illustrative code (pseudocode, conveying the idea only):

    1. def build_messages(query, history, retrieved):
    2. system = SYSTEM_PROMPT.strip() # keep it verbatim stable to help cache hits
    3. ctx = rerank_and_truncate(retrieved, budget=1500)
    4. hist = summarize(history, keep_turns=3)
    5. return [{"role": "system", "content": system}] + hist + \
    6. [{"role": "user", "content": ctx + "\n" + query}]

    4. Optimization Path 2: Designing Caching as Architecture

    Since caching is billed separately, design it as a first-class concern rather than a switch you turn on as an afterthought.

    • Stabilize the prefix: put invariant content (system instructions, tool descriptions, long documents) first, and variable content (user input, timestamps) last.
    • Layer the caches: a semantic cache intercepts repeated questions; a prefix cache reuses long context; a result cache stores responses by key on the business side to avoid duplicate calls.
    • Make hit rate observable: track cache hit rate, write volume, and read volume as metrics, and when the hit rate falls short, inspect prompt structure before scaling capacity.
    • Define invalidation: version cached content and bump the version whenever prompts or the knowledge base change, avoiding a “half-new, half-old” state that sharply drops the hit rate.

    5. Optimization Path 3: Model Routing and Tiered Fallback

    Tasks differ widely in the capability they require, and sending all traffic to a single model tier is the most common waste.

    1. request -> complexity check -> high-capability model (complex reasoning / long-form generation)
    2. -> mid-tier model (standard Q&A / summarization)
    3. -> lightweight model (classification / extraction / rewriting)
    4. -> rules or templates (deterministic work)

    You also need timeout and failure fallback paths: switch to a backup model when the primary is unavailable, or return a cached result or templated reply to keep the business available. The routing decision itself should stay lightweight, so you do not introduce a more expensive check just to save cost.

    6. Optimization Path 4: Observability and Cost Attribution

    No measurement, no optimization. Build at least four capabilities:

    • Call logs: record input/output tokens, cache read/write volume, latency, and model tier, stored in structured fields for aggregation.
    • Cost dashboard: break down spend by business, tenant, and API to locate the biggest consumers.
    • Alerts: set thresholds for token growth rate per unit time, cost per request, and hit-rate fluctuation.
    • Regression evaluation: compare quality before and after optimization on a fixed evaluation set to prevent cost cuts from causing quality regressions.

    On the cloud, you can combine general-purpose services such as log services, monitoring and alerting, message queues, and object storage to build the data pipeline and archive cold data, while a unified model gateway on the model-serving side handles routing and rate limiting. Baidu AI Cloud’s general approach in these scenarios is similar: combining model services, a container platform, and observability components to bring inference cost into routine operations.

    7. Common Pitfalls

    1. Chasing long context blindly: stuffing in all material at once raises input cost linearly without necessarily improving results.
    2. Cache misuse: writing one-off prompts to cache only adds spend.
    3. Watching unit price but not usage: the unit price is set externally; usage is what you control.
    4. Ignoring the output side: output is priced higher, yet often lacks length and structure constraints.
    5. No evaluation loop: skipping quality regression after cost cuts pushes the risk into production.

    8. Rollout Checklist

    • Within one week: wire up token and cost logging, and draw the baseline curve.
    • Within two weeks: slim down prompts and tighten max_tokens, and establish a cache prefix convention.
    • Within one month: ship model routing and fallback, and stand up the cost dashboard and alerts.
    • Ongoing: run monthly regression on a fixed evaluation set, and track cost per request as a technical-debt metric.

    Price changes are an external variable; architecture is the internal one. Get token budgets, cache design, model routing, and observability solid, and even under a $10 input / $50 output pricing environment, unit business cost still has room to move down.