← All lessons

Inference & the KV cache

~8 min read

Serving has two phases with wildly different economics. Understanding them explains half of LLM pricing — including ours.

Prefill vs decode

The KV cache — never recompute what you already read

During prefill, attention computes keys and values for every prompt token. Decoding token N+1 needs those same keys and values — so the server keeps them in GPU memory instead of recomputing. That stored state is the KV cache.

Two consequences run the whole industry:

turn 1:  [system + history] → prefill 60K tokens (full price)
turn 2:  [system + history] (identical bytes → cache HIT)
         + new message      → prefill only the new tail ( ~90% off )

Why session shape matters

The cache matches on exact prefix bytes. Timestamps, reordered tool schemas, or reshuffled history in the middle invalidate everything after them — the server re-prefills from the first changed byte. Stable system prompt first, append-only history after: that discipline is worth more than most model upgrades.

How our gateway plays this

Our proxy assembles every request canonically (fixed order, deterministic serialization, no volatile tokens in the prefix) for exactly this reason — so your repeated context keeps hitting cache instead of rebilling. The next lesson shows how to read the proof in your own usage rows.

Check your understanding

Progress saves on this device only

  1. 1.Why is generating 1000 tokens slower than processing a 1000-token prompt?

  2. 2.What does the KV cache store?

  3. 3.A timestamp injected mid-conversation busts the cache from that point on. Why?