Skip to content
Prefix caching saves the first token, not the generation length

Prefix caching saves on the first token, not on generation length

The customer service assistant needs to cut first-token latency from 1.5 seconds to 500 milliseconds. At the review meeting, someone added: let’s turn on prefix caching and halve inference costs while we’re at it. The latency half largely holds up; the cost half needs a hefty discount. These two things often get bundled together, and once bundled, it’s easy to get the budget wrong.

A request is split into two phases, and caching only touches the first

Prefill computes the entire input in parallel and produces the KV cache for every position; it is compute-intensive. Decode emits tokens one at a time, and each emission requires reading the entire historical KV; it is memory-bandwidth-intensive. The bottleneck resources of the two phases are not the same at all.

What prefix caching does is very narrow: it stores the KV computed during prefill keyed by a hash of the prefix, and if the next request starts with a token-for-token identical prefix, that segment of computation is skipped. Only prefill is skipped.

Generation cannot be precomputed. The 500th output token depends on the 499th, and its own KV does not exist until it is generated. Decode takes exactly the same number of steps, and each step reads exactly the same amount of memory. What a cache hit saves is the computation at admission, not the cost of every second after.

Total latency is roughly the sum of three terms: queueing time, time to first token (TTFT), and output token count times time per output token (TPOT). Caching only compresses the prefill term within TTFT, and only on a hit. Even after a hit, TTFT does not go to zero: the KV still has to be read, attention still has to run, and the first token still has to be sampled. Going from 1.5 seconds to 400 milliseconds is a reasonable order of magnitude; going to 50 milliseconds is not realistic.

The longer the output, the less this latency math is worth

Take a set of assumptions: an 8k-token fixed prefix, prefill a bit over one second, TPOT 25 milliseconds.

With 800 output tokens, total time is about 1.2 + 20 = 21.2 seconds, and about 0.3 + 20 = 20.3 seconds after a hit—total wait drops only around 4%. First token going from 1.2 seconds to 0.3 seconds feels very different, but that’s because for that second-plus, nothing was happening on screen.

With 80 output tokens, 3.2 seconds becomes 2.3 seconds, a drop of about 28%.

For a quick estimate on the spot, use this ratio: T_prefill / (T_prefill + N_out × TPOT). If output time exceeds prefill by five times, total latency improves by less than 17%; beyond twenty times, by less than 5%. These two numbers can be taken straight into the review meeting to push back on requirements.

Longer contexts make the denominator look worse. Every decode step reads the entire KV, and TPOT for a 100k-token context may be several times higher than for 10k tokens, depending on hardware and attention implementation. Prefix caching does not change this read. So in long-document QA, caching saves the admission fee, not the monthly rent.

This difference directly determines product shape. For streaming output, render-as-you-generate, and interactions where the user can interrupt mid-generation, first token is the experience bottleneck and caching is well worth it. For scenarios that return a long document all at once and the user can only use it after everything finishes, total duration is the bottleneck, and caching won’t save you.

Only input gets discounted on the bill

For APIs priced per token, a cache hit usually discounts only the input portion; the output unit price does not move at all. The common discount range is one-tenth to one-half of list price; check each vendor’s documentation.

Using a set of relative unit prices (input 1, cached input 0.1, output 4; order of magnitude only, not any vendor’s actual pricing):

Input / Output (tokens) Miss cost Hit cost Reduction
8k / 200 8.8 1.6 82%
8k / 2k 16 8.8 45%
8k / 8k 40 32.8 18%

The same caching mechanism produces financial effects that differ by more than four times across these three businesses. The higher the input share, the more caching looks like a price cut; the higher the output share, the more it looks like a speedup. These are not the same thing on a budget sheet, and writing them together in an OKR will eventually fail to reconcile.

Self-hosted inference is a different set of books. What caching saves is GPU prefill time, and whether that turns into money depends on whether other work fills that time. If the cluster wasn’t fully utilized to begin with, the saved compute just leaves cards idle while depreciation and electricity keep being paid. Only when prefill is the bottleneck, queues are piling up, and batch size can’t be raised does saved compute turn into throughput. Teams buying APIs and teams running their own clusters need to look at completely different metrics when evaluating the same technology.

Common patterns that zero out the hit rate

Prefix matching is token by token, and most implementations hash in blocks of a dozen to a few dozen tokens. One wrong token at the start invalidates the entire rest; there is no partial hit.

One class of rework I’ve seen: to “let the model know what time it is,” the prompt template prepends the current time and request id to the very front of the system prompt. The first token differs on every request, so the hit rate is permanently zero, but monitoring only shows “caching enabled, no effect,” and the team starts suspecting the framework.

There are several other variants of the same problem: tool definitions generated by iterating a map, with unstable serialization order; retrieved snippets reordered by similarity, so the same document comes out in a different order twice; a system reminder saying “please answer in Chinese” inserted before the history in a multi-turn conversation. Each of these looks reasonable on its own; stacked together, they kill the cache.

One rule covers most cases: static content first, dynamic content last. System prompts, tool schemas, few-shot examples, and long document bodies go first; the user’s current question, timestamps, retrieval results, and conversation summaries go last. Putting the conversation summary first is a high-frequency anti-pattern: it changes every turn, and every change invalidates the prefix of the entire history.

Another easily overlooked variable is interaction cadence. Caches have a time to live, mostly minutes to hours. When a human types in a customer service conversation, the gap between turns is minutes to tens of minutes, so the second turn has likely expired and the hit rate stays low. When an agent loops through tool calls on its own, the gap between turns is tens of milliseconds, so it almost always hits. Same model, same code: the cache benefit in agent scenarios will be markedly higher than in human conversation scenarios, and the reason is cadence, not technology.

The hit rate metric itself is misleading

The first trap is computing hit rate by token. A 20k shared system prompt can push overall token hit rate to 90%, but if those requests are only a tenth of traffic and each has a long output, the bill barely moves. At minimum, look at three numbers together: request-level hit rate, token-level hit rate, and the share of total cost saved by hits. The third is the one the boss cares about.

The second pitfall is multiple replicas. Requests are randomly load-balanced across N replicas, so each replica sees only 1/N of the traffic, and the hit-rate ceiling is roughly 1/N. With four replicas and no prefix routing, the theoretical ceiling is 25%, and the real number is lower. Add prefix-hash routing and the hit rate goes up, but then you hit hotspots: all requests share the same 20k prefix, the replica holding it gets hammered while the rest sit idle.

Each mitigation has a cost: pre-warming the shared prefix on every replica costs a copy of GPU memory per replica; sharding by tenant instead of prefix hash flattens the hotspot but drops the hit rate back toward 1/N; shortening the shared prefix itself is a separate engineering effort. There are no free options here—you pick one based on your traffic distribution.

The third pitfall is on the self-hosted side. Cache blocks occupy KV memory, and when the hit rate is low, those blocks squeeze out space for concurrent batches, so throughput actually drops. If cache occupancy stays high over time while the request hit rate is only 20–30%, turn it off or cap it first, then talk about optimization.

When is it worth changing the architecture for caching

Walk through the following chain first, then decide whether to touch the architecture.

flowchart TD
    A[请求进入] --> B{前缀逐token一致}
    B -- 否 --> C[先修提示词布局]
    B -- 是 --> D{同前缀复用三次以上}
    D -- 否 --> E[命中率接近零]
    D -- 是 --> F{输出token占比小}
    F -- 是 --> G[缓存收益明显]
    F -- 否 --> H[只省首token]
    H --> I[去优化生成侧]

Break it into criteria you can check off one by one:

  1. The same prefix is reused at least three times within a single session. For a one-off summary reused only once, caching is pointless.
  2. Output tokens × TPOT does not exceed three times the prefill time. Beyond that magnitude, the gain from changing the architecture is mainly in experience, not cost.
  3. The prefix contains nothing that changes over time or per request—no timestamps, random ids, or dynamic ordering.
  4. In a multi-replica deployment, prefix routing or a pre-warming scheme is already in place; otherwise the hit-rate ceiling is 1/N.
  5. Monitoring records cached_tokens, prefill latency, TTFT, and output token count separately. A gain you can’t measure is a gain that didn’t happen.

The boundaries on the other side are just as clear. In multi-tenant knowledge-base Q&A, the retrieved snippets differ each time and are placed at the front, so the hit rate is inherently low—what needs fixing there is prompt layout, not more cache machines. For one-off long-document analysis, one document and one question, the reuse count is one, and caching saves nothing. In both scenarios, prefix caching is a “just know it exists” technology.

The real levers for output cost are on the generation side: capping max_tokens, using structured output to cut redundancy, routing by difficulty to smaller models, speculative decoding, and batching. These don’t conflict with prefix caching, but they solve completely different problems. Mix the two up and you’ll end up in a retrospective meeting saying “we turned on caching and costs still didn’t drop.”

Next time someone in review says “let’s add caching and cut costs along the way,” make them answer one question first: in this pipeline, what share of the bill is output tokens. If they can’t answer, the proposal isn’t ready to be signed off.

About this Post

This post is written by Lu's Blog, licensed under CC BY-NC 4.0.

#Inference Costs #Latency #Prefix Caching

Comments