LLM API Cost Calculation and Optimization: A Practical Guide

    This guide explains how to calculate large language model API costs across input, output, and cache-read tokens, why a discount on unit prices does not necessarily halve your bill, and four reusable ways to cut spending. It includes a full cost breakdown for a mid-sized codebase analysis task, a reusable estimation function, and advice on using limited-time discounts as a validation window to build a measurable budget model.

    1. Why a Discounted Unit Price Does Not Mean a Halved Bill

    Whenever a model service launches a limited-time discount, the most common conclusion in developer communities is that costs have been cut in half. That conclusion is arithmetically correct but often wrong in engineering practice. The reason is simple: the cost of a real request consists of three parts—input tokens, output tokens, and cache reads—each with a different unit price, a different share of the total, and often a different discount. Seeing the input unit price drop by half and inferring that the overall bill drops by half treats a variable as a constant.

    A more hidden bias comes from the business volume itself. Discount periods usually come with concentrated trials, load tests, and demo launches, so call volume can grow several times over. A 50% drop in unit price combined with a 300% rise in call volume still means total spending goes up. So the correct order for cost governance is: first establish a measurable accounting basis, then assess the impact of the discount, and only then discuss optimization.

    2. Breaking the Billing Model into Three Variables

    Mainstream LLM services generally meter by token and quote prices per million tokens. Ignoring vendor-specific differences, this can be abstracted into three variables:

    • Input unit price P_in: covers prompts, system instructions, retrieved snippets, and conversation history;
    • Output unit price P_out: usually significantly higher than the input price, because the generation stage cannot be parallelized;
    • Cache-read unit price P_cache: the hit portion of a repeated prefix is priced separately, generally far below the first-time input price.

    The cost of a single request is:

    1. Cost = (T_in - T_hit) * P_in + T_hit * P_cache + T_out * P_out

    where T_hit is the number of input tokens that hit the cache. This formula reveals two often-overlooked facts: output has fewer tokens but may be the main cost item; and every 10% increase in cache hit rate saves the most expensive part of the input cost.

    3. A Full Calculation for a Mid-Sized Codebase Analysis Task

    Take a typical scenario: submit about 500,000 tokens of code context to the model and ask for about 20,000 tokens of change suggestions and sample code. Assume that before the discount, input is 0.8, output is 2.8, and cache read is 0.23 (per million tokens), and after the discount each is halved.

    • Before discount: 0.5 × 0.8 + 0.02 × 2.8 = 0.456 per request
    • After discount: 0.5 × 0.4 + 0.02 × 1.4 = 0.228 per request

    With an additional 40% cache hit rate, the post-discount cost drops further to about 0.174 per request. As you can see, the output portion accounts for only about 12% both before and after the discount; the real leverage is on the input side and the hit rate. The difference only becomes budget-relevant when you plug in monthly call volumes in the thousands; if you only run a few dozen times, the savings are not enough to justify any architectural change.

    4. Four Reusable Ways to Cut Costs

    1. Prefix stabilization. Keep system instructions, tool descriptions, and few-shot examples fixed at the very front of the request, byte-for-byte identical, and keep timestamps and random IDs out of the prefix. This is the cheapest way to improve cache hit rate.
    2. Context compression. Do symbol retrieval and dependency pruning first, and feed in only relevant files and function signatures, compressing 500,000 tokens to under 80,000. This is usually more effective than any discount.
    3. Output constraints. Use an explicit schema to limit generation length and reduce redundant explanation; output tokens have the highest unit price, so compressing output pays off directly.
    4. Tiered routing. Split tasks by difficulty across model tiers of different parameter sizes or price points: send simple classification and format conversion to a lightweight tier, and keep complex reasoning on a high-capability tier.

    Example implementation:

    1. def estimate(in_tok, out_tok, hit_ratio=0.0, price=(0.4, 1.4, 0.115)):
    2. p_in, p_out, p_cache = price
    3. hit = in_tok * hit_ratio
    4. return ((in_tok - hit) * p_in + hit * p_cache + out_tok * p_out) / 1e6

    5. How to Use a Discount Window Correctly

    A limited-time discount should be treated as a validation window, not a saving window. During this period, it is recommended to do three things: use real traffic to measure the cache hit rate and the average input/output distribution; connect the estimation function to monitoring and alerting to form a cost dashboard by business line; and load-test rate limiting and fallback paths. After the discount ends, what remains should be a measurable budget model and a leaner context, not waste masked by temporary low prices.

    If you need to elastically handle sudden traffic spikes, you can combine container platforms to scale stateless services, use message queues to smooth peaks, use object storage to hold long-text corpora, and use logging and monitoring with alerting for cost attribution. These general capabilities, together with the calculation method above, keep the cost curve linearly controllable as business volume grows, instead of suddenly rebounding when the discount expires.