LLM API Cost Optimization: A Practical Guide to Cutting Token Spend

    As major LLM providers cut API prices, engineering teams still need a structural cost model rather than a fixed price sheet. This guide explains how input, cached-input, and output pricing shape real spend, and walks through a practical optimization path: instrument usage and cost telemetry to build a baseline, stabilize prompt prefixes to raise cache hit rates, route requests across model tiers with quality guardrails, and compress both outputs and context. It also covers quota, circuit-breaker, and budget safeguards, plus a staged rollout that keeps quality intact while scaling call volume.

    1. What Falling Per-Token Prices Actually Mean

    A notable pattern has emerged in the industry: a cloud provider launched a new generation of general-purpose LLM and cut API prices at the same time. For the flagship tier, input and output unit prices dropped by roughly 20% compared with the previous generation. Cached input saw a much steeper decline of about 60%. The lightweight tier kept the previous generation’s pricing, with input, cached input, and output in the range of a few dollars, a fraction of a dollar, and around ten dollars per million tokens, respectively.

    The specific numbers will change with vendor strategy and over time. What engineering teams should actually fix in place is not a price list from a single day, but the structure of the cost model. Three general rules can be abstracted from the public pricing structure:

    1. Input and output are priced separately, and output is usually significantly more expensive than input. Making the model “say less” is therefore a direct way to save money.
    2. Cached input is priced separately and is the cheapest, which means repeated prefixes (system prompts, tool definitions, long documents) have economic value in being reused.
    3. Tiering is stable, with a several-fold price gap between the flagship and lightweight tiers, leaving room for tiered routing.

    In other words, the savings from price cuts do not arrive automatically. If calls still rely on “concatenating the full context every time and using a single tier for everything,” the benefit of lower prices will be eaten up by ever-expanding context and redundant calls.

    2. Do the Math First: Build an Observable Cost Baseline

    Optimization starts with measurement. The first step is to turn cost from something you “check on the bill at month-end” into a metric you can query at any time.

    The minimum set of fields to collect:

    • Request level: model tier, task type, tenant/business line identifier;
    • Token level: input tokens, cached-input tokens, output tokens;
    • Result level: success or failure, whether a retry was triggered, end-to-end latency;
    • Cost level: amount converted using current unit prices, with unit prices as configuration rather than hard-coded values.

    A simplified conversion function:

    1. def cost_of(usage, price):
    2. # price is the per-million-token unit price, configured from the current price list
    3. return (
    4. usage.input * price.input
    5. + usage.cached_input * price.cached_input
    6. + usage.output * price.output
    7. ) / 1_000_000

    With a baseline in place, you can typically observe three common problems: output tokens make up too high a share, cache hit rate is extremely low, and the lightweight tier is underused. These three map directly to the three optimization tracks below.

    3. Optimization Track 1: Raise the Cache Hit Rate

    Cached input is cheapest because it strips “reusable prefix computation” out of every request. In engineering terms, you need to keep the prefix byte-for-byte stable, including system prompts, tool/function definitions, examples, and long document fragments.

    Common patterns that break caching:

    1. # Bad example: timestamp and random ID at the front make the prefix change every time
    2. messages = [
    3. {"role": "system", "content": f"Current time {now()} Request ID {uuid4()}"},
    4. {"role": "system", "content": SYSTEM_PROMPT},
    5. {"role": "user", "content": question},
    6. ]

    The fix is to move volatile content to the end:

    1. messages = [
    2. {"role": "system", "content": SYSTEM_PROMPT}, # stable prefix, cache hit first
    3. {"role": "user", "content": question},
    4. {"role": "system", "content": f"Additional context: {now()}"}, # volatile info goes last
    5. ]

    Supporting practices include: avoid implicit whitespace and newline changes during template rendering; split long documents into stable chunks with a fixed order; keep the history prefix unchanged across multi-turn conversations and only append at the tail; set an alert threshold for cache hit rate in monitoring, since a sudden drop often means a template was modified by mistake.

    4. Optimization Track 2: Model Tiering and Routing

    The several-fold price gap between the flagship and lightweight tiers makes sending every request to the flagship tier the most common waste. A workable approach is to build a routing layer that splits traffic by task difficulty.

    1. def route(task):
    2. if task.kind in {"classify", "extract", "rewrite_short"}:
    3. return "light" # lightweight tier, lowest cost
    4. if task.kind in {"summarize", "sql_gen", "rag_answer"}:
    5. return "mid"
    6. return "flagship" # complex reasoning, long-chain planning

    Routing must be paired with quality guardrails: validate lightweight-tier outputs with rules or a second-pass check, and escalate to a higher tier if validation fails. This preserves the cost advantage while avoiding rework caused by “unusable output from a cheap tier.” Rework is itself a cost; a single failed retry can wipe out the savings from dozens of successful calls.

    5. Optimization Track 3: Compress Output and Context

    Output has the highest unit price, so controlling output length gives the most direct payoff. Tactics include: state explicit length and structure constraints in the prompt; require structured output (such as strict JSON) instead of free-form long text; separate “reasoning process” from “final answer,” returning the former only in debug mode.

    On the context side, follow “enough is enough”: in retrieval-augmented scenarios, rerank before truncating rather than stuffing in an entire document; use rolling summaries for conversation history instead of keeping everything; preprocess large tables and logs into conclusions with rules or a lightweight model before handing them to the main model.

    6. Stability and Budget Guardrails

    Low prices do not mean unlimited calls. Three layers of guardrails are recommended:

    • Quota layer: set per-minute request limits and daily token caps per tenant/business line;
    • Circuit-breaker layer: automatically downgrade to the lightweight tier or queue when cost per task or error rate exceeds a threshold;
    • Budget layer: trigger an alert when budget consumption reaches a set percentage and switch to sampled calls.

    Also keep idempotency keys and retry limits to prevent retry storms from network jitter from multiplying the bill several times over.

    7. Rollout Path and Summary

    The recommended order is: first wire up usage and cost instrumentation to get a baseline; then restructure prefixes to improve cache hits; next roll out tiered routing with quality guardrails; finally add quota, circuit-breaker, and budget guardrails. At each step, run the same offline evaluation set to regression-test quality, ensuring cost reduction does not come at the expense of degraded results.

    Back to the initial judgment: falling prices are an industry trend, but the slope of the cost curve is determined by your call architecture. Understand the billing structure clearly, and do the three things—caching, routing, and output compression—solidly, so that when call volume doubles, the bill does not double with it. For more complete engineering support, you can combine general-purpose capabilities from Baidu AI Cloud (such as object storage, message queues, container platforms, log services, and monitoring/alerting) to build an observable and elastic-scaling pipeline.