AI engineering and inferenceLoading progress…

Limits and isolation

Identify reusable prompt prefixes, calculate saved prefill work and distinguish token savings from hit rates.

What caching does not do, and who may share

Prefix caching removes repeated prefill work. It does not shorten decoding: a cached prompt still has to generate every output token one by one. In the toy numbers, reusing 500 of 800 prompt tokens saves 50 ms of a 1480 ms request (3.4%); long outputs dominate.

Reuse also needs boundaries. Cache identity must include who may use an entry: one user's private prompt must not be served to another user just because the text matches, unless that content was deliberately made shareable. Reuse can also leave timing differences that reveal that a prompt was cached, which is another reason to scope the cache.

prompt tokens800reused tokens500generated tokens100
no cache
1480 ms
with cache
1430 ms
saved 50 ms = 3.4% of this request prefill 30 ms + decode 1400 ms (a cache hit does not shorten decoding)
reuse refused: a private block belongs to another tenant; the cache identity includes the boundary
Change the prompt, reuse and output length. Then toggle the tenant condition.

Predict first. Does a cached prompt make generating a long new response free?

Chapter context

Prefix caching reuses compatible KV state for a repeated beginning of a prompt. A repeated suffix alone is not enough, because causal hidden states depend on the preceding context.

Chapter reference: math, worked example & code

This section belongs to the whole chapter, so it is the same on every lesson in it and may cover a different lesson's topic. The code for the experiment you just ran is inside the experiment itself.

Math and notation

A simple saved-token estimate is

S=H P,S=H\,P,

where H is the number of hits reusing P prefix tokens. If all R requests contain P prefix and U unique tokens, the baseline prompt work is R(P+U)R(P+U) and the nominal fraction saved is HP/[R(P+U)]HP/[R(P+U)]. This models token work, not directly wall-clock speed.

Worked example

One hundred requests each contain a 500-token common prefix and a 300-token unique suffix. Eighty hits reuse the entire prefix. Saved prefill tokens are 80×500=40,000 out of 100×800=80,000 baseline tokens: 50% token work saved despite an 80% request hit rate. Cache lookup and new-output generation still take work.

Reference code

The following example uses the Python standard library and does not call a remote service.

requests,hits,prefix,unique=100,80,500,300
saved=hits*prefix
baseline=requests*(prefix+unique)
assert saved == 40000 and baseline == 80000
assert saved/baseline == .5
assert hits/requests == .8

Python examples are provided for study and local execution; this page does not execute Python.

Common mistakes

Textual similarity is not cache identity. A common suffix is not a common causal prefix. Hit rates need definitions and do not directly translate into end-to-end speedups.