KV Caching and Speculative Decoding: Understanding Long-Conversation Inference Costs
LLM inference costs depend on more than token counts. This article explains how prefill, decoding, and GPU memory contribute to costs, how KV caching and speculative decoding improve efficiency, and why subscription fees cannot be compared directly with API-equivalent spending. It also provides Python examples and practical steps for estimating and optimizing long-conversation costs.
1. Why Similar Token Counts Can Produce Very Different Bills
A comparison circulating on social media takes a user’s actual usage over a period, prices it at pay-as-you-go API rates, and arrives at an amount far above the monthly subscription fee. Such comparisons are often interpreted as evidence that providers are selling below cost or that compute costs are becoming unsustainable.
That interpretation overlooks two points.
First, published API prices are retail rates offered to users. They account for provider margins, research and development, operating expenses, and risk—not just the underlying compute cost.
Second, subscription pricing is based on usage across a population of users, rather than the extreme consumption of one heavy user. Dividing an individual user’s API-equivalent spending by a subscription fee does not reveal the provider’s actual gross margin or profitability.
To understand these figures, we first need to examine where inference costs come from and which techniques can materially change the marginal cost per token.
2. What Makes Up LLM Inference Costs?
LLM inference generally has two stages.
Prefill: The model processes the input context and computes the intermediate states needed for attention for each input token. This stage is computationally intensive but supports parallel execution, allowing relatively efficient use of compute.
Decode: The model generates output tokens one at a time. Each step accesses the intermediate states associated with the preceding context. This stage is often more constrained by GPU memory bandwidth: each step involves relatively little computation but repeatedly accesses large amounts of data.
Inference costs therefore include at least three components:
- Processing the input.
- Generating the output.
- Keeping context states in GPU memory.
Memory capacity limits how many sessions an accelerator can serve concurrently. Higher memory usage can increase the share of hardware cost allocated to each request.
A simplified expression for marginal cost per token is:
Marginal cost per token ≈ Hourly cost per device ÷ Effective tokens produced per device per hour
Here, “effective” refers to billable throughput after batching, cache reuse, and scheduling optimizations. Changes in this denominator can affect costs more than changes in hardware prices.
3. KV Caching: Avoiding Repeated Computation for Shared Context
In attention mechanisms, each input token produces key and value vectors. These vectors are reused during subsequent token generation. Recomputing them for an entire context on every request would duplicate substantial work.
A KV cache stores previously computed key and value vectors. When a new request shares a prefix with an earlier request, the system can reuse the cached states and process only the newly added content. This cross-request reuse is commonly called prefix caching.
Repeated prefixes are common in multi-turn conversations and coding workflows. System prompts, tool definitions, file contents, and conversation history often remain unchanged between requests, with only a small amount of new content appended. A high cache hit rate can substantially reduce input-side computation.
The following example estimates input costs based on the cache hit ratio. All prices are illustrative relative units, not the actual prices of any service.
def estimate_cost(input_tokens: int,cache_hit_ratio: float,price_fresh: float,price_cached: float,price_output: float,output_tokens: int,) -> float:"""Estimate per-request cost using the cache hit ratio, in relative units."""cached_tokens = input_tokens * cache_hit_ratiofresh_tokens = input_tokens - cached_tokensreturn (fresh_tokens * price_fresh+ cached_tokens * price_cached+ output_tokens * price_output)if __name__ == "__main__":# Assume 100k input tokens and 2k output tokens.# Relative prices: fresh input 1.0, cached input 0.1, output 5.0.for ratio in (0.0, 0.5, 0.9):cost = estimate_cost(100_000, ratio, 1.0, 0.1, 5.0, 2_000)print(f"Cache hit ratio {ratio:.0%}: relative cost {cost:,.0f}")
With the same input size, increasing the cache hit ratio from 0% to 90% substantially reduces the estimated cost. Cache efficiency is therefore a key variable in long-conversation economics.
Cache reuse does not eliminate all costs, however. Cached states occupy memory, capacity is limited, and those states still need to be accessed during decoding. Servers typically evict older entries using policies such as least recently used (LRU). Changes within a previously shared prefix can also invalidate reuse from that point onward, reducing the cache hit rate.
4. Speculative Decoding: Improving Output Efficiency
Standard decoding generates tokens sequentially, with each step depending on the previous one. Speculative decoding introduces a smaller draft model that quickly proposes several candidate tokens. The target model then verifies those candidates in a single parallel pass.
The basic workflow is:
- The draft model generates
kcandidate tokens sequentially. - The target model evaluates the candidates in one forward pass, producing probability distributions for the relevant positions.
- The system checks candidates in order according to an acceptance rule. If a token is rejected, it samples from a corrected distribution and discards the remaining candidates.
If each candidate has an approximately independent acceptance probability of α, the expected number of output tokens per verification round is:
E = (1 − α^(k+1)) ÷ (1 − α)
This includes the additional token that can be generated when all candidates are accepted.
For α = 0.8 and k = 4, E ≈ 3.36. In terms of target-model calls, a round can produce output that would otherwise require roughly 3.4 sequential forward passes, using one verification pass plus the draft model’s overhead. This is not a guarantee of a 3.4× wall-clock speedup: the work required for drafting and verification still matters.
The benefit depends on how closely the draft model’s distribution matches the target model’s distribution, which affects acceptance rate, and how efficiently the verification work runs in parallel.
Structured outputs such as code can be easier for a draft model to predict. Long conversations may benefit as well, but context length alone does not guarantee a high acceptance rate.
The following simplified pseudocode illustrates the core process:
def speculative_step(draft_model, target_model, context, k):"""Simplified illustration of one speculative decoding step."""draft_tokens, draft_probs = [], []ctx = list(context)# 1. The draft model proposes k candidates sequentially.for _ in range(k):token, prob = draft_model.sample(ctx)draft_tokens.append(token)draft_probs.append(prob)ctx.append(token)# 2. One target-model pass produces distributions for k+1 positions.target_probs = target_model.score(context, draft_tokens)# 3. Verify candidates in order and stop at the first rejection.accepted = []for i, token in enumerate(draft_tokens):if accept(target_probs[i], draft_probs[i], token):accepted.append(token)else:accepted.append(resample_residual(target_probs[i], draft_probs[i]))return accepted# If all candidates are accepted, generate an additional bonus token.accepted.append(sample(target_probs[k]))return accepted
Production inference frameworks must also handle batch scheduling, memory management, and distributed execution. The central idea remains the same: reducing sequential target-model calls can increase output throughput per device.
5. Why Coding Workflows Can Benefit from Both Techniques
Coding assistance is a typical long-context, multi-turn workload. A workflow might involve inspecting a project, loading relevant files, running tests, reading errors, modifying code, and running tests again. Each request carries forward much of the preceding context.
Two characteristics make this workload a useful fit for these optimizations.
Inputs are often much larger than outputs. Most of each request consists of existing code and logs, while the newly generated output may be a patch or a short explanation. Large shared prefixes can be reused through KV caching, concentrating new computation on the appended content.
Outputs are highly structured. Indentation, keywords, and matching brackets follow recurring patterns that a draft model may predict effectively. This can support higher speculative decoding acceptance rates.
Together, the two techniques can make coding workflows more computationally efficient than open-ended chat. That does not mean every coding interaction is inexpensive. Frequent prefix changes, context switching, or long and difficult-to-predict outputs can substantially reduce the benefits.
6. Subscription Pricing vs. Pay-as-You-Go Billing
The main distinction between subscription and usage-based pricing is how usage risk is distributed.
With pay-as-you-go billing, charges track metered usage. Users bear the cost of each call, while provider revenue scales with that usage. The billed amount is still a retail charge, not a direct measurement of the provider’s infrastructure expense.
Subscriptions spread usage costs across a user population. Providers estimate average consumption, set a fixed fee and usage limits, and manage heavy usage through queue priorities, rate limits, or service downgrades. Many users consume less than the allowance, helping offset the consumption of heavier users.
Comparing one heavy user’s API-equivalent spending with the subscription fee therefore shows only one side of the ledger. A meaningful financial assessment needs to consider:
- Usage distribution: The consumption of typical users is necessary to determine whether a plan is broadly loss-making.
- Fixed costs: Model training, research and development, infrastructure investment, and depreciation are not captured simply by looking at one request.
- Operating expenses: Electricity, facilities, networking, monitoring, security compliance, and customer support all contribute.
- Gross margin vs. net profit: Positive margins on inference do not establish that the overall business is profitable. Research and customer acquisition expenses may exceed inference costs.
- Measurement assumptions: Estimates of “equivalent usage” can use different cache hit rates, input-to-output ratios, and hardware utilization assumptions. Changing these assumptions can materially change the result.
Before drawing conclusions from a widely circulated spending multiple, check how it was calculated and whether those assumptions support the claim being made. A single number cannot establish a provider’s profitability.
7. Estimating Your Costs with a Reproducible Method
For developers and businesses, the more actionable question is: What does a completed task cost in this workload, and which variables have the greatest effect?
Use the following steps:
- Measure request structure. Record input tokens, output tokens, and request frequency.
- Measure cache hits. Obtain the number of cached prefix tokens from server or gateway logs. If no direct metric is available, the common prefix length between adjacent requests can provide an approximation of potential reuse, though it does not establish an actual cache hit.
- Define the pricing model. Use the service’s billing rules to set separate rates for fresh input, cached input, and output.
- Run sensitivity analysis. Vary cache hit ratio, conversation length, and output length to see how estimated costs change.
The following example aggregates costs across session records and compares a baseline with an assumed improvement in cache hit ratio:
from dataclasses import dataclass@dataclassclass Session:input_tokens: intoutput_tokens: intcache_hit_ratio: floatdef session_cost(s: Session, price_fresh, price_cached, price_output) -> float:cached = s.input_tokens * s.cache_hit_ratiofresh = s.input_tokens - cachedreturn fresh * price_fresh + cached * price_cached + s.output_tokens * price_outputdef compare_strategies(sessions, prices):baseline = sum(session_cost(s, *prices) for s in sessions)# Strategy B: stabilize system prompts and tool definitions in the prefix.# Assume the cache hit ratio increases to at least 0.85.improved = [Session(s.input_tokens, s.output_tokens, max(s.cache_hit_ratio, 0.85))for s in sessions]optimized = sum(session_cost(s, *prices) for s in improved)return baseline, optimized, 1 - optimized / baselinesessions = [Session(input_tokens=80_000, output_tokens=3_000, cache_hit_ratio=0.4),Session(input_tokens=120_000, output_tokens=5_000, cache_hit_ratio=0.6),]base, opt, saving = compare_strategies(sessions, prices=(1.0, 0.1, 5.0))print(f"Baseline relative cost: {base:,.0f}, "f"optimized: {opt:,.0f}, savings: {saving:.1%}")
These prices are again relative units. For an actual estimate, replace them with the service’s current rates and use measured usage data from logs. The improved cache hit ratio is a scenario assumption, not a guaranteed outcome of rearranging a prompt.
8. Practical Engineering Recommendations
Applications can improve cache reuse and make costs more predictable through a few straightforward measures.
Keep prefixes stable. Place system prompts, tool definitions, and relatively static background information at the beginning of requests. Put changing user input, timestamps, and random identifiers later. Dynamic content inserted into a shared prefix can prevent reuse of everything after that point.
Remove unnecessary prefix variation. Check whether template rendering introduces fields that change on every request, such as request IDs or timestamps with second-level precision. Move them outside the reusable prefix or omit them when they are unnecessary.
Control conversation length. As a conversation grows, its history consumes more memory and can increase input costs. At appropriate points, summarize the history while preserving key decisions and constraints and removing lengthy intermediate steps.
Split independent tasks. Handle separable subtasks in fresh, shorter conversations and return only the necessary conclusions to the main conversation. This limits context growth and makes individual tasks easier to measure and optimize.
The central lesson is that token counts alone do not explain inference economics. Cache reuse, decoding efficiency, memory pressure, and aggregate usage patterns all matter. Measuring those factors provides a more useful basis for cost decisions than comparing one heavy user’s retail API-equivalent spending with a flat subscription fee.
