LLM API Pricing Explained: Input, Output, and Cache Billing, Cost Estimation, and Optimization Practices

    Large language model (LLM) API prices have moved in opposite directions over the past two years: some next-generation models cut per-token prices while doubling parameter counts, and others raised prices after improving quality. This article breaks down the technical logic behind those differences. It explains the three billing dimensions used by mainstream LLM APIs — input tokens, output tokens, and cache hits — why cache hits can cut costs by an order of magnitude through prefix caching, and why parameter count alone does not determine price. It then compares pay-as-you-go API billing with subscription plans, shows how to estimate per-call and monthly costs in Python, and covers practical optimization techniques: maximizing cache hits, controlling prompt and output length, tiered model routing, batch and asynchronous inference, and observability. It closes with a selection framework for balancing performance against budget.

    1. Introduction: The Technical Logic Behind Pricing Differences

    Over the past two years, LLM parameter counts have grown from hundreds of billions toward the trillions. Yet API pricing across platforms has moved in sharply different directions: some vendors cut unit prices substantially while doubling parameter counts, while others raised per-call prices after improving model quality. This apparent contradiction is the result of several forces acting together — R&D cost, compute supply, inference efficiency, and market positioning.

    For developers and enterprise users, understanding pricing cannot stop at the headline “price per 1,000 tokens” number. It requires going deeper into how billing dimensions are composed, how model size relates to inference cost, and what different billing models actually cost in real workloads. Only with a complete cost model can you make technical choices that balance performance and cost rationally. This article focuses on the underlying logic of API billing, cost estimation methods, and practical optimization techniques.

    2. The Three Dimensions of API Pricing

    Mainstream LLM APIs generally use a three-dimensional billing model. Understanding these three dimensions is the foundation of cost estimation.

    2.1 Input Token Billing

    Input tokens are all the context you send to the model: the system prompt, the user input, and conversation history. This portion is usually billed at a comparatively low unit price. Note that input length directly consumes context window space, so in scenarios such as long-document summarization or code repository analysis, input tokens are often one of the largest cost drivers.

    2.2 Output Token Billing

    Output tokens are what the model generates. Because generation is autoregressive — tokens are computed one at a time — it consumes significantly more compute than input processing (which can be parallelized). Output unit prices are therefore typically several times the input price. A structure such as 20 for input and 100 for output per million tokens reflects the general rule that generating is more expensive than understanding. This is also why, when the budget is tight, constraining generation length and output format is often more effective than simply trimming the input.

    2.3 Cache Hit Billing

    Cache hits are an important billing dimension that emerged in recent years. When multiple requests share an identical context prefix — a fixed system prompt, long background material, or few-shot examples — the platform can cache and reuse the computed result for that prefix. Tokens served from cache are billed at a unit price far below normal input pricing (on the order of 1 per million tokens).

    The technical basis is prefix caching: during Transformer inference, the Key/Value tensors of an identical prefix can be reused, skipping the repeated prefill computation. For workloads where the system prompt repeats heavily — chat systems, agent loops, structured extraction — cache hits can reduce cost by an order of magnitude.

    Key takeaway: whether a request hits the cache depends on the prefix being exactly identical and in the same order. If you place dynamic content (timestamps, random IDs) at the very front of the prompt, the prefix changes constantly, the cache is invalidated, and costs actually go up.

    3. Model Size and Pricing: The Cost Trade-Off Under Scaling

    A common question: why do prices fall even as parameter counts rise? Several interacting factors explain this.

    • Inference efficiency gains. More mature inference engines, quantization techniques (FP8, INT4), and sparsification (such as MoE architectures, where the activated parameter count is far smaller than the total) all substantially reduce the actual compute cost per token. A model with trillions of total parameters does not activate all of them on every inference.
    • Hardware and cluster utilization. Faster accelerators, higher batching utilization, and better scheduling all dilute per-token inference cost.
    • Scale effects and competition. As volumes grow and competition intensifies, marginal cost declines, giving vendors room to lower unit prices in exchange for higher call volume.
    • Capability-based pricing. Some vendors raise prices after improving capability. This is essentially a performance premium: stronger output quality supports a higher unit price, tying pricing to product positioning and target customers.

    Parameter count is therefore only one input to cost and cannot be equated with final price. When evaluating cost, focus on the product of actual token consumption for an equivalent task and the unit price, not on model size alone.

    4. Pay-as-You-Go vs. Subscription Pricing

    Beyond metered API billing, developer-facing scenarios such as coding assistance and code generation also widely use subscription plans (Coding Plan and similar). The two models feel very different in terms of cost, so selection requires weighing several factors:

    Dimension Pay-as-you-go (API) Subscription (Coding Plan)
    Billing basis Actual input/output tokens consumed Fixed fee per billing period
    Cost predictability Low; fluctuates with usage High; fixed fee
    Suitable scenarios Unpredictable or bursty traffic Teams or individuals with high, steady usage
    Quota limits No hard quota (subject to rate limits) Usually a per-period quota cap
    Quota pools Single resource pool May be split into multiple independent pools

    A few easily overlooked “perception traps” deserve attention:

    1. Subscription quotas are not automatically better value. If the per-period quota is limited, and once you exceed it or the reset cadence works against you, the usable volume may fall short of expectations. In that case, the hidden cost per task can exceed pay-as-you-go pricing.
    2. Split quota pools. Some plans split different features (chat, code completion) into independent quota pools that are counted and capped separately. This easily leads to a situation where the total quota looks large, but a single use case exhausts its allocation quickly.
    3. Rate limits and availability fluctuations. Throttling under high call frequency and quota reset cycles both affect the actual experience. These non-price factors should be included in any evaluation.

    5. How to Estimate API Costs Accurately

    Without real invoices, building an estimation model helps a team forecast budget. Using per-million-token pricing as an example:

    1. def estimate_cost(input_tokens, output_tokens, cached_tokens,
    2. in_price=20.0, out_price=100.0, cache_price=1.0,
    3. unit=1_000_000):
    4. """
    5. Estimate the cost of a single call (all unit prices per million tokens)
    6. input_tokens: total input tokens
    7. output_tokens: output tokens
    8. cached_tokens: input tokens served from cache (<= input_tokens)
    9. """
    10. fresh_input = max(input_tokens - cached_tokens, 0)
    11. cost = (
    12. fresh_input * in_price
    13. + cached_tokens * cache_price
    14. + output_tokens * out_price
    15. ) / unit
    16. return cost
    17. # Example: 8k-token system prompt, 500-token user question, 1.5k output tokens
    18. # where the 8k system prompt hits the cache
    19. cost = estimate_cost(
    20. input_tokens=8_500,
    21. output_tokens=1_500,
    22. cached_tokens=8_000,
    23. )
    24. print(f"Cost per call (billing units): {cost:.5f}")

    Practical points when estimating:

    • Break down the input composition. Separate the fixed prefix (cacheable) from dynamic content (not cacheable); only the former benefits from the lower cached rate.
    • Measure typical output length. Output pricing is high, so always set upper and lower bounds on generation length to avoid runaway costs.
    • Multiply by call volume. Multiply per-call cost by average daily requests and active days per month to get the real monthly budget.
    • Reserve a variance buffer. Account for amplification factors such as retries, multi-turn agent calls, and context accumulation. A buffer of 30%–100% is common.

    6. Cost Optimization Practices

    Once the billing mechanics are clear, you can systematically reduce LLM application costs along several directions.

    6.1 Maximize Cache Hits

    • Put fixed content (system prompt, tool descriptions, examples) at the very front of the prompt, and keep its content and order stable.
    • Avoid inserting dynamic variables such as timestamps or random values into the prefix.
    • For multi-turn conversations and agent loops, reuse the same session context so the history portion keeps hitting the cache.

    6.2 Prompt and Output Length Governance

    • Replace verbose descriptions with clear instructions to shrink the system prompt.
    • For structured output (JSON, fixed formats), constrain it with a schema and cap the maximum generation length.
    • For long documents, do retrieval or summarization preprocessing first and feed only the relevant passages to the model, reducing input tokens.

    6.3 Tiered Model Routing

    Not every task needs the strongest model. Build a tiered strategy: route simple classification and format conversion to small models, and complex reasoning and code generation to large models.

    1. def route_model(task_complexity, token_estimate):
    2. # simple task + long context -> small / lower-priced model
    3. if task_complexity == "simple" or token_estimate > 100_000:
    4. return "light_model"
    5. # complex reasoning -> high-performance model
    6. return "flagship_model"

    6.4 Batching and Asynchronous Processing

    • For offline workloads (data cleaning, bulk extraction), use batch inference endpoints; they typically cost less per token than real-time endpoints.
    • Merge requests and raise concurrent batch utilization to dilute unit cost.

    6.5 Architect Around Platform Capabilities

    When building LLM applications on a cloud platform, general-purpose capabilities can help reduce cost and improve efficiency: object storage for persisting datasets and prefix resources, caching services for reusing inference results, logging and monitoring/alerting to track token consumption and cost trends, and message queues for asynchronous load leveling. Platforms such as Baidu AI Cloud typically offer supporting capabilities around these general categories (model services, caching, monitoring, storage, and so on), making it easier for teams to build observable, cost-controlled application architectures.

    7. Selection Guidelines and Best Practices

    Bringing the discussion together, here is a practical selection framework:

    1. Define the cost structure before comparing options. Align the three billing dimensions (input/output/cache) with your business’s token distribution and calculate the real spend, rather than ranking by unit price alone.
    2. Distinguish pay-as-you-go from subscription. Prefer metered billing when usage is unpredictable or cost control must be precise; evaluate subscriptions for high-frequency steady workloads, but always account for quota pools and reset rules.
    3. Enable cache reuse by default. For workloads with highly repetitive system prompts, cache hits are usually the single largest saving.
    4. Establish cost observability. Connect monitoring and alerting to track token consumption and cost in real time, and set budget thresholds and anomaly alerts.
    5. Route dynamically and roll out gradually. Route different model tiers by task complexity, and continuously evaluate the performance/cost balance with small-traffic canary tests.

    Overall, LLM API pricing may look like nothing more than a few numbers, but behind it lies a combination of compute, architecture, inference efficiency, and market strategy. Only by fully understanding billing dimensions, caching mechanics, subscription versus metered differences, and cost estimation methods can developers find the optimal balance between performance and budget and build applications that are both effective and economical.