KV-Cache Optimization and Prefix Stability
Learn how KV-cache reuse and prompt caching work for AI agents. Build a simulator, create stable prefixes, identify silent cache invalidators, preserve append-only history, and verify cache hits with LiteLLM usage data.
We'll cover the following...
In the last two lessons, we gave the on-call assistant a sectioned system prompt and a clean set of tools. Both now stay the same from one call to the next. During an incident, the assistant may get dozens of questions in a few minutes, and each call sends the same tools and system prompt again before the new question.
Model providers can avoid reprocessing that repeated start of a request. This is called prompt caching. In this lesson, we’ll see how it works, build a small simulator that shows when the cache hits and misses, find the everyday code changes that quietly break it, and then check a real response for cache hits.
What is prompt caching?
When a model reads a request, it turns each token into internal values called the KV cache (short for key-value cache). Building these values is a large part of the cost of processing input. If the next request starts with exactly the same tokens, the provider can reuse the stored values for that part instead of computing them again.
The part that stays the same is called the prefix. A provider renders every request in a fixed order:
Tools: All tool definitions come first.
System prompt: The system prompt comes next.
Messages: The conversation, ending with the new question, comes last.
So for our assistant, the tools and the system prompt form a stable prefix, and only the question at the end changes.
The diagram shows the general layout. In our assistant, the second tool is get_recent_changes from the previous lesson. Some providers, such as Anthropic, ask us to mark where the cached part ends with a cache_control breakpoint. A breakpoint at the end of the system prompt covers both the tools and the system prompt. Other providers, such as OpenAI and Gemini, find repeated prefixes automatically.
The savings are large. Anthropic bills a cache read at about 0.1 times the normal input price on most Claude models, and less on some newer ones. Writing an entry costs 1.25 times the normal price with the default 5-minute lifetime, or 2 times with a 1-hour lifetime. Manus, an agent company, reported cost differences of up to 10 times between cached and uncached input in its agent loops. That’s a reported figure, so we should measure our own.