Inference Costs in AI Coding: Understanding KV Caching and Speculative Decoding
This article explains why token usage in AI coding agents can far exceed the actual cost of inference, covering how tokens are metered, why coding workloads consume so many of them, and how techniques like prefix caching (KV cache reuse) and speculative decoding dramatically reduce compute costs. It also examines the gap between subscription pricing and pay-as-you-go billing, and offers practical advice for developers and inference service builders on reducing token consumption and improving cache efficiency.
1. It Started with a Billing Question
A senior developer recently published a record of his AI tool usage over a year. He found that, when converted at the publicly listed pay-as-you-go rates, the value of tokens he had actually consumed was far higher than the subscription fee he paid. This kind of comparison sparked considerable discussion in developer communities: are flat-rate services losing money, and what does a vendor’s cost structure actually look like?
The core question behind these discussions is quite clear: when calling the same large language model, why can there be an order-of-magnitude gap between “nominal usage” and “actual cost”? Answering this requires first understanding how tokens are metered, and then understanding the engineering behind inference services.
2. Token Metering: Input, Output, and Repeated Context
A token is the basic unit of text processed by a model, roughly corresponding to a word fragment. Most inference services bill for two types of tokens: input tokens (the prompt, conversation history, file contents) and output tokens (what the model generates). Output tokens are usually priced higher than input tokens because the generation phase computes tokens serially, one at a time.
There is an easily overlooked fact here: billing counts all tokens actually sent to the model in each request, not just the few sentences the user newly typed. In conversational scenarios, every request carries the previous conversation history. As a result, the total token count grows roughly linearly with the number of conversation turns—or even faster.
3. Why Coding Scenarios Consume So Many Tokens
Coding agents differ significantly from ordinary Q&A. A typical workflow looks like this:
- Read the project directory structure and relevant source files;
- Plan the modification steps based on the task;
- Call tools to compile, test, or search;
- Feed the tool-returned logs back into the model;
- Repeat the process until the task is complete.
Each step resubmits a long context to the model. A single task may involve dozens or even hundreds of model calls, and most of each call’s input is identical to the previous one, with only a small amount of new content appended. Therefore, token statistics in coding scenarios are often far larger than the “amount of text the user actually produced.”
This leads to a key corollary: a high total token count does not mean the model generated a large amount of new content. A large share of tokens may simply be the same context being re-read repeatedly. This is exactly the entry point for understanding the cost question.
4. KV Caching: Reuse Is Much Cheaper Than Recomputation
When processing input, a Transformer model computes Key and Value vectors in the attention mechanism for each token; these vectors are collectively known as the KV cache. The input phase (prefill) is computationally expensive, but its result is deterministic: as long as the prefix content is identical, the computed KV vectors are exactly the same.
Therefore, an inference service can save the KV cache of prefixes it has already computed. When a new request begins with content matching the cache, the service only needs to compute the newly added portion. This mechanism is commonly called prefix caching.
In agent loops, prefix reuse is very high. System prompts, tool definitions, project descriptions, and conversation history mostly remain unchanged; only the content appended at the end needs to be computed. Tokens that hit the cache cost far less to process than cache misses, and some services even price cache-hit input tokens separately.
The following pseudocode illustrates the basic idea of cost estimation. The unit price parameters are placeholders only; actual figures should be based on each service’s official pricing:
function estimateCost(inputTokens, outputTokens, cachedTokens, inputPrice, cachedPrice, outputPrice):uncachedTokens = inputTokens - cachedTokenscost = uncachedTokens * inputPrice+ cachedTokens * cachedPrice+ outputTokens * outputPricereturn cost / 1000000
As this formula shows, the cache hit rate is the key variable affecting cost. For the same total token count, the actual compute cost can differ by several times between low and high hit rates.
5. Speculative Decoding: More Efficient Output in Long Sessions
The output phase (decode) has a different bottleneck. The model can only generate one token at a time, and each token depends on the result of the previous one, so hardware utilization is often low.
Speculative decoding mitigates this through a “draft-and-verify” approach. A smaller, faster draft model first proposes several candidate tokens in sequence, and then the large model verifies these candidates in parallel in a single pass. Verified tokens are accepted directly; at the first position where a mismatch occurs, generation restarts from there.
Under a standard rejection sampling implementation, the probability distribution of the final output remains identical to what the large model would produce token by token, so output quality is not affected. The benefit depends on the draft model’s acceptance rate. Programming code tends to be highly structured and predictable—indentation, bracket pairing, common API calls, and so on—so acceptance rates are often high. This is why coding scenarios benefit noticeably from this technique.
6. Subscription Pricing vs. Pay-as-You-Go Billing
Understanding subscription pricing requires distinguishing three things: listed usage prices, actual costs, and the distribution of user behavior.
First, pay-as-you-go list prices are the unit prices a provider charges externally, covering hardware, electricity, operations, and a certain profit margin. Second, actual costs depend on cache hit rates, batching efficiency, hardware utilization, and model size. Third, subscription users vary widely in usage intensity: a small number of heavy users may consume resources far above average, while most light users consume very little.
Subscription products are typically priced to balance average usage and peak usage across the user base. Therefore, a single high-intensity user’s case can illustrate cost differences in certain scenarios, but it cannot directly represent overall profitability.
7. Practical Advice for Developers
The following practices can reduce token consumption and improve cache hit rates without changing functionality.
- Keep prefixes stable. Place unchanging content—system prompts, tool definitions, project background—at the very front of the request, and dynamic content at the end. Frequently modifying the prefix invalidates the entire cache.
- Control context size. Only send files and logs relevant to the current task to the model. Large blocks of irrelevant logs can be filtered and summarized before submission.
- Split long tasks. Divide large tasks into well-bounded subtasks, each with its own independent, shorter context, to avoid unbounded growth of history.
- Limit tool output. Tool responses are often verbose; truncate to key lines or extract error information before returning them.
- Monitor usage metrics. Record the input, output, and cache-hit token counts of each call, aggregate by task type, and identify links with abnormal consumption.
8. Engineering Implications for Service Providers
For builders of inference services, cost optimization focuses mainly on the following directions.
First, cache management. Cache capacity is limited, so reasonable eviction policies must be designed, and cache retention duration determined based on request patterns. Second, scheduling and batching. Merging multiple requests for computation improves hardware utilization but increases latency for individual requests, requiring a trade-off between throughput and latency. Third, tuning speculative decoding parameters. The draft model’s size, candidate length, and acceptance rate jointly determine the speedup, and need to be measured against actual workloads.
All of these directions depend on observability. Service providers need to continuously track metrics such as cache hit rate, GPU memory usage, and per-token compute time in order to judge whether optimizations are effective.
9. How to Think Rationally About Cost Narratives
Discussions about whether a given service is “wildly profitable” often get stuck on isolated cases. A more sound approach is to consider the following factors together: the actual distribution of user usage, resource occupancy during peak hours, the proportion of overall workload covered by caching and speculative decoding, and how model training and R&D investment is amortized.
For developers, the more valuable questions are: How many tokens will my task generate? How many of them are repeated context? How can I design my calling patterns so the same results consume fewer resources? Understanding the composition of inference costs helps make more reasonable tool choices and usage plans.
