LLM Pricing and Caching for Million-Token Contexts: A Practical Guide

    This guide breaks down how modern LLM APIs bill input, output, cache writes, and cache reads, and why caching becomes a first-class architectural concern once context windows reach the million-token scale. It covers the two billing dimensions and four token types, the latency and output-limit constraints of long contexts, the main causes of low cache hit rates and how to fix them with prefix stabilization, a parameterized monthly cost model for sensitivity analysis, and the operational guardrails needed to avoid throttling and timeouts. Readers will find code snippets, a cost formula, and a deployment checklist they can adapt without hardcoding any vendor price.

    1. Why Long Context Became a New Cost Center

    Over the past two years, the central tension in LLM applications has shifted from “is the model capable enough” to “is the cost per task under control.” Once context windows expanded from tens of thousands of tokens to the million-token range, a single request could hold an entire contract, a full code repository, or a day’s worth of logs. The bill, however, went from negligible to a line item that has to be modeled.

    Pricing strategies for the new generation of flagship models generally show two trends: base unit prices are lower than the previous generation, and cache read prices are pushed far below normal input prices. Together they point to one conclusion: the optimization focus for long-context workloads has moved from “feed fewer tokens” to “make repeated tokens go through the cache whenever possible.”

    One caveat matters for engineering: specific prices are operational parameters that any provider may change at any time. Never hardcode unconfirmed numbers into code or a financial model. The correct approach is to treat billing as configuration and drive cost estimation and budget alerts through parameters.

    2. Billing Model: Two Dimensions, Four Token Types

    Mainstream LLM API billing can be abstracted into two dimensions and four token types:

    • Dimension 1, usage-based billing: input tokens and output tokens are priced separately, with output typically costing several times more than input.
    • Dimension 2, cache-based billing: cache writes (writing a prefix into the cache for the first time, priced close to or slightly above normal input) and cache reads (settled at a very low price once there is a hit).

    This yields the cost formula:

    1. total cost = input tokens × P_in
    2. + output tokens × P_out
    3. + cache write tokens × P_cache_write
    4. + cache read tokens × P_cache_read

    P_cache_read is often only one tenth of P_in, or even lower. A 10,000-token system prompt billed in full on every request can therefore cost an order of magnitude more than the same prompt served from cache. Caching is not a nice-to-have optimization; it is a first-class citizen of long-context architecture.

    3. What Million-Token Windows and Output Limits Mean Architecturally

    A million-token context window introduces two direct constraints.

    The first is memory and latency. Attention computation and the key-value cache grow with sequence length, so time to first token (TTFT) rises noticeably. “It fits” does not mean “it should be stuffed in.” A more sensible engineering approach is layering: stable content in the prefix, frequently retrieved fragments in the middle, and the user’s current turn at the end.

    The second is the output limit. Normal output caps sit in the tens-of-thousands-of-tokens range, which is not symmetric with a million-token input window. Long-document tasks therefore need a map-then-reduce split rather than an expectation that the model will emit one very long report in a single pass:

    1. # Example: chunked summarization plus a merge step to cap output size
    2. def summarize_long_doc(chunks, model):
    3. partials = [model.summarize(c, max_output=4096) for c in chunks]
    4. return model.merge(partials, max_output=8192)

    4. Cache Hit Rate: The Core Metric for Long-Context Applications

    Whether a request hits the cache depends on the prefix being byte-for-byte stable. In practice, hit rates collapse for a small, highly concentrated set of reasons:

    1. Timestamps, request IDs, or randomly ordered results placed at the very front of the prompt.
    2. Rewriting the system prompt every turn, even to change a single punctuation mark.
    3. Unstable retrieval ordering, so the same question returns results in a different order twice.
    4. Dynamic fields leaking into tool definitions or structured output templates.

    The countermeasure is prefix stabilization: move invariant content to the front and version it, push dynamic content to the back, sort retrieved results by a fixed key before concatenation, and render templates with deterministic serialization. The following pseudocode shows the constraint:

    1. def build_prompt(system_v1, retrieved, user_input):
    2. # Keep the prefix fully stable so it can hit the cache
    3. prefix = system_v1
    4. # Sort the middle section by document ID for a deterministic order
    5. middle = "\n".join(sorted(retrieved, key=lambda d: d.doc_id))
    6. return f"{prefix}\n{middle}\nUser input: {user_input}"

    5. Cost Estimation: Turning the Bill into a Computable Model

    Teams should build a minimal viable cost model whose inputs are daily request volume, average input and output tokens, and cache hit rate, and whose outputs are monthly spend and cost per task:

    1. def monthly_cost(reqs, in_t, out_t, hit, p):
    2. write = in_t * (1 - hit)
    3. read = in_t * hit
    4. per = write * p["cw"] + read * p["cr"] + out_t * p["out"]
    5. return reqs * per * 30

    The key is to treat hit as a tunable variable for sensitivity analysis. When the hit rate climbs from 0.2 to 0.8, total cost for a long-context application often drops by more than half, and that gain requires no model change at all.

    6. Stability and Governance: Avoiding Throttling and Timeouts

    Long-context requests take a long time and consume heavy resources, so they need engineering guardrails: request timeouts and a retry budget, exponential backoff with jitter, queueing and concurrency caps for oversized tasks, large objects in object storage, task state in a message queue, stateless inference gateways on a container platform, and logging plus monitoring and alerting to observe hit rate, TTFT, and failure rate. If you use the relevant general-purpose capabilities from Baidu AI Cloud, the same three principles apply: configuration externalized, metrics observable, capacity elastic.

    7. Implementation Checklist

    • Externalize all billing parameters; never hardcode a unit price.
    • Version the prompt prefix and push dynamic content to the back.
    • Sort retrieved results deterministically and render templates deterministically.
    • Use chunked summarization for long documents to cap output size per call.
    • Maintain three dashboards: hit rate, cost per task, and failure rate.
    • Revisit the model and caching strategy every quarter and reallocate budget per business scenario.

    The bottom line: competitiveness in the million-token era does not come from how long a window you use, but from whether you can convert repeated prefixes into cheap cache reads, split long tasks into controllable output segments, and keep calibrating with an observable cost model. Get those three right, and long-context capability turns into business value instead of bill pressure.