Sub topic 5
Laying out prompts: stable content first, variable content last
This chapter assumes you have called an LLM API before, know what tokens and context windows are, and can read short Python. It also assumes you know the earlier idea in this tutorial: a cache hit needs an identical prompt prefix. Here you will use that rule to decide where each piece of a prompt belongs.
The layout rule
A provider can reuse earlier work only for the leading part of a prompt that is byte-for-byte the same as a previous request. The first changed token ends the reusable part. Everything after it is processed again, even if it is identical to the earlier request.
This gives one design rule: order the prompt from the content that changes least to the content that changes most.
- Content that never changes, such as the role description and fixed rules.
- Content that changes rarely, such as tool definitions, a policy document, or a style guide.
- Content that changes per session, such as a user profile or a retrieved document the user is discussing.
- Content that changes per request, such as the timestamp, the latest question, or retrieval results for that question.
The same pieces in a different order can make the difference between a 99% hit rate and none.
A toy model of why order matters
The next snippet treats a prompt as a list of pieces and counts how many leading pieces two prompts share. Real providers compare tokens, but the behavior is the same.
def shared_prefix_len(a, b):
n = 0
for x, y in zip(a, b):
if x != y:
break
n += 1
return n
first = ["SYSTEM", "RULES", "DOC", "Q1"]
second = ["SYSTEM", "RULES", "DOC", "Q2"]
changed = ["SYSTEM", "RULES v2", "DOC", "Q2"]
print(shared_prefix_len(first, second)) # 3 -> three leading pieces are reusable
print(shared_prefix_len(first, changed)) # 1 -> one early edit invalidates everything after itIn the second comparison, DOC is identical in both prompts. It still cannot be reused, because the edit to RULES came before it. A change early in the prompt costs you everything behind it. A change at the end costs you only the end.
The most common mistake: a timestamp at the top
Many prompts begin with the current time, a request ID, or the user's name. These values change on every call, so the prefix differs from the first token.
from datetime import datetime, timezone
STATIC_INSTRUCTIONS = "You are a support assistant. Follow the policy below.\n" + open("policy.md").read()
def bad_prompt(question):
# The timestamp changes on every call, so no two prompts share a prefix.
now = datetime.now(timezone.utc).isoformat()
return f"Current time: {now}\n{STATIC_INSTRUCTIONS}\nQuestion: {question}"
def good_prompt(question):
# Stable text first, per-request values last.
now = datetime.now(timezone.utc).isoformat()
return f"{STATIC_INSTRUCTIONS}\nCurrent time: {now}\nQuestion: {question}"In bad_prompt, the first line differs on every request, so even a long policy.md is never reused. In good_prompt, the policy text forms a long identical prefix, and only the last two lines vary.
The model still sees the same information in both versions. Moving the timestamp later rarely changes answer quality. If you worry that the model will pay less attention to a value placed late, test it on your own cases. Placing the question last often works well anyway.
Choosing a stability tier for each piece
Use a table to classify each piece before you assemble the prompt.
| Piece | How often it changes | Where it goes |
|---|---|---|
| Role and behavior rules | On deploys only | First |
| Tool definitions | On deploys only | Early, in a fixed order |
| Policy or reference document | Days or weeks | After tools and rules |
| Few-shot examples | On deploys only | After the reference material |
| User profile | Per session | After shared material |
| Conversation history | Grows each turn | After session context |
| Retrieved passages | Per request | Near the end |
| Current time and the new question | Per request | Last |
Few-shot examples are one case where the order is a judgment call. If they are the same for every request, they belong in the stable section. If you choose them per request, they belong near the end.
Putting the boundary in the right place
Providers handle the boundary in one of two ways, covered in the previous chapter.
- With explicit breakpoints, you mark the last stable block. Everything up to and including that block is the cached prefix. Place the marker on the last block that stays identical across requests, not on a block that includes per-request text.
- With automatic caching, the provider looks for the longest matching prefix on its own. You do not place a marker, but the layout rule applies in the same way.
The snippet below shows an explicit breakpoint on the policy block. The timestamp and question go in the user message, after the marker.
import anthropic
from datetime import datetime, timezone
client = anthropic.Anthropic()
POLICY = open("policy.md").read() # must meet the model's minimum cacheable length
def ask(question):
now = datetime.now(timezone.utc).isoformat()
return client.messages.create(
model="YOUR_MODEL_NAME",
max_tokens=512,
system=[
{
"type": "text",
"text": "You are a support assistant. Follow the policy below.",
},
{
"type": "text",
"text": POLICY,
"cache_control": {"type": "ephemeral"},
},
],
messages=[
{
"role": "user",
"content": f"Current time: {now}\nQuestion: {question}",
}
],
)The marker sits on the last system block. Everything before it is stable, and the per-request values live in the user message after it.
Keeping the prefix byte-identical
"Stable" means identical character by character, not just similar in meaning. These small differences all break the match:
- A trailing space or a different line ending added by a template.
- Keys in a JSON object that are serialized in a different order.
- A set or dictionary turned into text with an unstable iteration order.
- A date formatted differently between code paths.
- A prompt template edited in a deploy, which changes every cache entry once.
A simple defense is to build the stable section in one function, with no inputs that vary per request, and call that function from every code path.
import json
def render_tools(tools):
# sort_keys and fixed separators give identical bytes for identical content
return json.dumps(tools, sort_keys=True, separators=(",", ":"))
tools_a = {"name": "search", "description": "Find docs"}
tools_b = {"description": "Find docs", "name": "search"}
print(render_tools(tools_a) == render_tools(tools_b)) # TrueWithout sort_keys=True, those two dictionaries would serialize to different strings and would count as different prefixes. Many SDKs build tool definitions for you, so check that your tool list keeps the same order between calls.
Edge cases to plan for
- A static document that is rarely used. If only some requests need a large reference document, including it for all requests puts a long prefix in front of the requests that do not need it. Consider two prompt variants, each with its own stable prefix, rather than one prompt that toggles the document in the middle.
- Per-user content early in the prompt. Putting a user's profile before shared rules means each user gets a separate prefix. Put the shared rules first, so every user shares that part and only the profile differs.
- Optional sections. A section that appears for some requests and not others shifts everything after it. Keep optional sections after the stable parts, or give each combination its own fixed position.
- Growing conversation history. History only extends the prompt at the end, so it works with prefix matching as long as earlier turns are not edited. Later chapters cover editing and trimming history.
- Rewording for quality. Each prompt improvement changes the prefix and starts a new cache entry. This is a one-time cost per edit, so batch edits rather than shipping many small ones during peak traffic.
A quick review checklist
Before shipping a prompt, check the following:
- Is there any per-request value before the last stable block?
- Is the stable part produced by one function with deterministic output?
- Are tool definitions in a fixed order with fixed key order?
- Does the cache marker sit on the last block that is identical across requests?
- Is the stable part long enough to meet the provider's minimum length?
The last item matters because a well-ordered prompt that is too short is still not cached. The minimum length is covered in its own chapter.
Exercise
A prompt is built as: (1) "Request ID: <uuid>", (2) fixed rules, (3) a 6,000-token policy document, (4) the user's question. Cache hits are near zero. Rewrite the order so that most of the prompt can be reused, and explain why the original order fails.
Show answer
Use this order: fixed rules, the policy document, then the request ID, then the question. The request ID is different on every call, and it is the first item in the original prompt. The prefix therefore differs from the first token, and the 6,000-token policy is never matched. After the change, the rules and policy form an identical prefix of about 6,000 tokens. Only the request ID and question are processed again each time.
Exercise
A team serializes tool definitions with a plain json.dumps of a dictionary built from a set of tool names. Hit rates drop at random after each service restart. What is the likely cause, and what is the fix?
Show answer
Iterating over a set can give a different order after each process start, so the tool list serializes to different text, and the prefix no longer matches. Fix it by sorting the tools into a fixed order, for example by name, and using sort_keys=True with fixed separators when serializing. Then the same tools always produce identical bytes.