LLM API Token Pricing and Cost Optimization: A Practical Guide

    A practical guide to token-based billing for large language model APIs. It explains why tokens rather than requests or character counts are the billing unit, breaks down the three billing dimensions (input, output, and cached input), and shows why output tokens are priced significantly higher than input tokens and why prompt caching can cut the cost of a shared prefix by an order of magnitude. The article includes a reusable cost-estimation function, guidance on modeling input/output ratios and cache-hit scenarios, and concrete optimization tactics: compressing context, arranging prompts to maximize cache reuse, constraining output length, routing requests by task difficulty, and instrumenting cost observability. It closes with advice on matching monthly token consumption to quota plans and subscription tiers.

    1. Why token billing comes first

    Large language models are not billed per request or per character. The billing unit is the token. One token roughly corresponds to a word, a subword, or a few characters; in Chinese-language workloads, a single character typically maps to one or two tokens. Billing is token-based because the model’s compute cost, memory footprint, and inference latency are all driven directly by the total number of input and output tokens. Once you internalize that, it becomes obvious why a conversation that “looks short” can still produce a surprisingly large bill.

    Real-world API pricing usually splits cost into three independent dimensions. Developers integrating a model for the first time often overlook this split, and that is where budgets start to slip:

    • Input: tokens consumed by the prompt, system instructions, and any conversation history you send.
    • Output: tokens in the response the model generates.
    • Cached input: tokens whose prefix matches recent requests and is therefore served from cache at a lower rate.

    2. The logic behind the three dimensions

    Input and output are not symmetric

    Nearly every mainstream LLM service follows the same pattern: output tokens cost significantly more per token than input tokens. The reason is autoregressive decoding. Each output token requires a full forward pass, and generation cannot be parallelized the way prefill of the input can, so the compute cost per token is inherently higher.

    Some illustrative numbers help build intuition (these only demonstrate the ratio and do not represent any specific service): assume input at 8 units per million tokens and output at 28 units per million tokens. Output is then about 3.5x more expensive per unit than input. The practical consequence: for “long document in, short answer out” workloads, cost pressure comes mostly from input; for “short question in, long generation out,” output dominates. Before estimating cost, identify your own input-to-output ratio.

    Cache hits: the underrated lever

    Prompt caching is built on prefix reuse. When several requests share the same opening — a fixed system prompt, few-shot examples, a long document — the server can reuse the computation already done for that prefix, and cached tokens are often billed at a very low rate, sometimes a tenth of the input rate or less.

    This is particularly valuable for:

    • Q&A bots with a fixed system prompt and a high volume of user questions;
    • scenarios where a long document is uploaded once and then queried repeatedly;
    • batch extraction or classification jobs that share a common template.

    3. Estimating cost properly

    Don’t guess. Use a reusable formula. The pseudocode below shows the general calculation for a single call:

    1. def estimate_cost(
    2. input_tokens, # number of input tokens
    3. output_tokens, # number of output tokens
    4. cached_tokens, # input tokens served from cache (default 0)
    5. price_input, # input price per 1M tokens
    6. price_output, # output price per 1M tokens
    7. price_cached, # cached-input price per 1M tokens
    8. ):
    9. # input tokens that are not served from cache
    10. normal_input = max(input_tokens - cached_tokens, 0)
    11. cost_input = normal_input * price_input / 1_000_000
    12. cost_output = output_tokens * price_output / 1_000_000
    13. cost_cached = cached_tokens * price_cached / 1_000_000
    14. return cost_input + cost_output + cost_cached

    A few principles for estimating:

    1. Measure token counts with your real corpus, not by counting characters. Most services expose a token-counting endpoint; check the official documentation and measure before you extrapolate.
    2. Model input and output separately instead of relying on a single blended “average price.”
    3. Account for cache-hit uncertainty by running pessimistic, neutral, and optimistic scenarios.

    4. Cost optimization in practice

    Compress the context to remove redundant tokens

    Context is where usage inflates fastest. Passing the entire conversation history back each turn, using an overlong system prompt, and repeating source text all pile up input tokens quickly. Options:

    • Keep tiered system prompts (a compact version and a full version);
    • Apply a sliding window or summarization to conversation history, retaining only key turns;
    • Retrieve relevant passages from long documents first and send only those excerpts to the model.

    Exploit cache reuse deliberately

    Put stable, reusable content — system prompts, few-shot examples, shared background knowledge — at the very front of the prompt, and dynamic content after it. This maximizes cache hit rate. It is an optimization with zero algorithmic cost and purely engineering benefit, and the effect is usually immediate.

    Control output length

    Because output is priced higher, constrain response length with explicit instructions, for example “answer in no more than 200 words” or “return JSON only, no explanation.” In structured-output scenarios, forcing the model into a compact format saves money and is easier for downstream parsers to consume.

    Tier your routing by task difficulty

    Simple tasks (intent classification, format conversion, keyword extraction) and complex ones (long-document reasoning, code generation) require different capability levels. Design tiered routing: let lighter models handle easy requests and reserve expensive heavyweight calls for tasks that genuinely need them.

    Use observability to hold the cost line

    Cost monitoring is essential for long-term operation. At minimum, log input_tokens, output_tokens, cached token counts, and actual cost for every request, then aggregate the data through your logging and monitoring stack and set budget-threshold alerts so anomalous calls can’t run the bill out of control.

    5. Using quotas and plans sensibly

    Many platforms offer monthly subscription plans or resource packs, and their value depends on how well your call pattern matches the plan structure:

    • Measure your average monthly token consumption before comparing it against the plan’s allowance and the headroom it leaves.
    • Check whether the input/output ratio is covered by the plan, so you avoid structural waste like “not enough output, too much input.”
    • Separate development and production volumes — a low-tier plan is fine for debugging, and upgrades can be assessed once production traffic is known.

    Keep in mind that actual unit prices, plan allowances, and billing details are defined by your provider’s latest official documentation. Don’t base budget decisions on numbers circulating online.

    6. Conclusion

    Token billing is simply compute consumption quantified and allocated by usage. Controlling cost requires working on three levels at once: understanding the mechanism (the asymmetry between input, output, and cached input, and how reuse works), quantifying it (modeling with a formula and real token counts instead of intuition), and engineering around it (compressing context, exploiting the cache deliberately, constraining output, tiered routing, and observability). Chain these together into one continuous cost-governance loop and you can find a sustainable balance between quality and spend, so every token you pay for delivers its intended value.