Sub topic 1
How Prompt Caching Works and How to Keep Cache Hits High
Prerequisites
Assume you can call an LLM API, understand tokens and context windows, and read short Python examples.
Why processing a long prompt is expensive
Before generating an answer, a model processes the input prompt. This step is called prefill. It converts prompt tokens into internal attention data. A long system prompt, policy document, tool list, or conversation history increases both processing time and input-token cost.
Prompt caching lets a provider reuse this work for a later request. The request still pays for new input and output, but it may avoid processing a repeated portion of the prompt.
What the provider actually stores: reusable attention state
During attention, the model produces key/value data for earlier tokens. A provider can store this KV cache, which is reusable attention state. A later request can use it instead of rebuilding the state for the same prompt prefix.
def shared_prefix_len(a, b):
n = 0
for left, right in zip(a, b):
if left != right:
break
n += 1
return n
first = ["SYSTEM", "RULES", "DOC", "Q1"]
second = ["SYSTEM", "RULES", "DOC", "Q2"]
print(shared_prefix_len(first, second)) # 3Why only an identical prefix can hit
Most providers match tokens from the beginning of the prompt. If one token changes at position N, the cached state after that position is no longer valid. Identical text later in the prompt does not repair the broken prefix.
A changed timestamp, reordered tool definition, edited message, or different whitespace can therefore cause a miss.
Explicit breakpoints and automatic caching
Providers differ in how caching is enabled:
| Provider behavior | How reuse is selected |
|---|---|
| Explicit caching | Add a cache breakpoint to a stable content block |
| Automatic caching | The provider detects eligible repeated prefixes |
Check the provider's minimum length, TTL, pricing, and usage fields. An explicit breakpoint gives more control, while automatic caching gives simpler integration.
Laying out prompts: stable content first, variable content last
Place long-lived content first:
- Stable system instructions.
- Policies, reference documents, and tool definitions.
- Conversation history that changes less often.
- Current time, user question, and other request-specific values.
Exercise
Why does putting a timestamp at the start of a prompt reduce cache hits?
Show answer
The timestamp changes the early prefix, so the provider cannot reuse the cached attention state that follows it.