The economics of LLM inference at scale

Token billing, prefix caching, KV memory, batching, and cost per accepted task under explicit quality and latency constraints.


A cheap token can produce an expensive result. The first answer fails, the agent calls another tool, and a repair loop buys the same context again. Training and adaptation have their own costs. Serving repeats across every request, tool loop, retry, and evaluation. The useful number is cost per accepted task at the quality and latency the product needs.

An API bill exposes token charges. A self-hosted deployment exposes GPU time, memory, utilization, and operational overhead. Both need a workload model: input length, generated length, shared prefixes, request arrival rate, and the fraction of outputs that users can actually use.

A zero-based bar chart compares uncached cost of 0.032 dollars, cached cost of 0.020 dollars, fallback cost of 0.02375 dollars, and repair cost of 0.02875 dollars per accepted result.

These are worked-example prices and acceptance rates, not a current price comparison. Failed work and repair or fallback cost belong in the numerator; accepted results belong in the denominator.

Open full size Scroll horizontally to read the diagram on a small screen.

Tokens are the unit of cost

For a token-priced API, count uncached input, cached input, and generated output separately at the selected model’s rates. Some providers expose additional charges or different treatment for reasoning and other modalities. For self-hosted inference, token throughput helps explain capacity, but the bill comes from provisioned resources and their utilization.

That makes context selection a measurable engineering decision. Compare shorter retrieved context against the full task context on a fixed evaluation set. Dropping irrelevant files can save money; dropping a migration constraint can create an expensive wrong answer. There is no general tenfold saving attached to handing an agent three files.

Cache the prefix or pay for it twice

A reusable prefix can reduce repeated prefill work. Attention key/value state for eligible prefix tokens may be reused when the selected serving system supports it. Provider routing, model compatibility, minimum eligible lengths, retention, and eviction determine whether an apparently repeated prompt actually hits.

The prefix must produce the matching token sequence and compatible model inputs. Put stable instructions and shared context first, then request-specific material. A timestamp near the beginning breaks reuse beyond that point. Images and tool definitions can also participate in the input identity, depending on the API.

# early variable content limits reusable prefix length
prompt = f"User {user_id} at {now()}\n\n{HUGE_SYSTEM_PROMPT}\n{question}"

# cache-friendly: stable prefix first, variable suffix last
prompt = f"{HUGE_SYSTEM_PROMPT}\n\nUser context: {user_id}\n{question}"
#         ^^^^^^^^^^^^^^^^^^^^ stable prefix eligible for reuse

The second layout improves the opportunity for a hit; it does not guarantee one. Cached input usually remains billable at a discounted rate, and eviction can force later recomputation. Prefix caching also does not cache the answer or remove the cost of generating output. The provider’s reported cached-input usage tells you which repeated input actually received the discount.

Batch size changes the latency budget

At the serving layer, prefill processes the input context and decode generates tokens incrementally. Their resource profiles differ. Continuous batching can admit and retire sequences as they progress, while KV memory grows with active sequence lengths. Longer contexts can constrain concurrency even when the model weights already fit.

Increasing a batch can improve hardware utilization up to a workload-dependent point. It can also add queueing, exceed the KV-memory budget, or worsen time between generated tokens. Time to first token, inter-token delay, completion latency, and accepted throughput measure different parts of the experience. A nightly job and an interactive coding session have different budgets.

Separate admission and scheduling policies keep deferred work from consuming the memory or decode slots reserved for interactive traffic. Capacity is the throughput achieved while those latency limits hold, rather than the largest tokens-per-second number from a saturated benchmark.

Put numbers on one hypothetical workload

Assume a request contains 12,000 input tokens, of which 8,000 are reusable, and produces 1,000 output tokens. For arithmetic only, assume rates of $2 per million uncached input tokens, $0.50 per million cached input tokens, and $8 per million output tokens. These are invented rates, not a price quotation.

Input pathInput chargeOutput chargeTotal per attempt
Entire input uncached$0.024$0.008$0.032
8,000-token prefix hits$0.012$0.008$0.020

With a 75% hit rate for that eligible prefix, expected attempt cost is 0.75 × $0.020 + 0.25 × $0.032 = $0.023. If 80% of attempts are independently acceptable and unsuccessful attempts are retried under the same assumptions, expected attempts per accepted result is 1 / 0.8 = 1.25. Expected token cost per accepted result becomes $0.02875. Real agent retries are often correlated, so the full trajectory needs measurement before that estimate becomes a budget.

Tool calls, retrieval, sandbox time, and review can add to this amount. A cheaper model that needs several repair loops may cost more per completed task than a more expensive model that succeeds on the first pass. Model comparisons need the same acceptance criteria. Input-token price alone misses the repair bill.

KV memory is a capacity budget

For a simple transformer cache, approximate KV bytes per active sequence as 2 × layers × KV heads × head dimension × stored tokens × bytes per element. The factor of two represents keys and values. The architecture may change this formula; grouped-query attention uses fewer KV heads than query heads, and cache quantization changes element width.

As an invented example, 32 layers, 8 KV heads, head dimension 128, and two-byte elements use 128 KiB per stored token. An 8,192-token sequence occupies about 1 GiB of raw KV payload. That excludes model weights, temporary activations, allocator slack, and serving metadata. Reusing prefix blocks can reduce duplicate storage in implementations that support it, but admission must still account for the suffix and future generated tokens.

An API’s discounted cached-input billing and a serving engine’s reuse of prefill KV state describe different cost boundaries. Prefix reuse saves prefill work; generating new tokens still requires decoding. Deployment sizing has to account for both.