Prompt caching with llama.cpp: cutting TTFT on long system prompts
My coding assistant prompt has grown to the point where every new chat session spent 4 seconds "thinking" before the first token. It wasn't thinking — it was re-processing 2,000 tokens of unchanged system prompt. Prompt caching fixed it.
The flags
./llama-server -m Qwen2.5-32B-Q4_K_M.gguf \
--prompt-cache cache/session.cache \
--prompt-cache-all \
-c 32768 -fa on --cache-type-k q8_0
--prompt-cache— file to save the KV state of the processed prompt into.--prompt-cache-all— keep the full context cached, not just up to the last user turn. Essential for a fixed system prompt.
Before / after
workload system tokens TTFT (cold) TTFT (cached)
coding assistant 2,140 3.9 s 210 ms
RAG pipeline 5,860 11.2 s 480 ms
long agent scaffold 11,400 21.7 s 910 ms
Hardware for the record: RTX 4090, Ryzen 7950X, llama.cpp b4602, CUDA. The cached TTFT is essentially the time to process only the new user turn.
Gotchas
- The cache file is tied to the exact model file and build — change either and it silently invalidates (or worse, errors). I version the cache filenames with the model hash.
- Changing
-cinvalidates the cache too. Decide your context length before you warm it. - Don't cache per-user state with
--prompt-cache-allon a shared server — the KV state is one conversation's, not a public good.
Can confirm the numbers are in the right ballpark — I use the same trick for a 6k-token RAG prompt and went from 9s to about half a second on the 3090s.
One more gotcha for the list: the cache is prefix-ordered. If your system prompt has anything volatile in it (a timestamp, a random few-shot pick), put it at the end of the prompt, after all the static content. One changing token in the middle and you're re-processing everything after it, which is the same as no cache at all.
Also worth knowing: llama-server does this automatically for identical prefixes within a running session — the file-based cache is for persisting across restarts.
The prefix-ordering point deserves to be shouted from the rooftops — I've debugged three "my cache isn't working" reports this month and all three had a date stamp in the middle of the system prompt.
Small note on the interplay with KV quantisation: caching works fine with --cache-type-k q8_0, but if you quantise V as well, double-check your output quality on a fixed eval set. V-quantisation plus a very long cached prefix is where I've seen the first signs of drift.
Added a section to the wiki performance page linking here.