Prompts Are Code: Versioning, Caching and Tracing LLM Calls
In an LLM application, the prompt is code, but it is rarely treated like code. It is edited by hand, pasted into string templates, tuned in a chat window and shipped without a test. Three separate concerns hide behind "prompt handling": which prompt text is live, what each call costs and how long it takes, and what the model actually saw when something went wrong. This post takes each in turn, with live measurements of prompt caching from 103 API calls on invented data, the patterns I use in my own projects, where a prompt registry such as Langfuse fits, and five lessons from running prompts in production.
In short
- Treat prompts as code: version them, keep the stable part frozen, put anything that varies at the end, and gate every change on an evaluation.
- Provider caching is an exact prefix match. Measured on Claude Sonnet 5.5, a cached call on a 7,800-token prompt cost about one tenth of an uncached one; a timestamp at the top of the system prompt silently turned every call into a fresh cache write, at 1.25 times the normal input price.
- Caching cut cost by 20 to 24 times on long prompts but barely moved the median time to first token; its latency gain showed in the slow tail, not the typical call.
- A prompt registry such as Langfuse gives versions, labels and traces linked to prompt versions. It also makes it easy to change production text without review, so the evaluation gate has to be yours.
Three concerns behind one word
| Concern | Question it answers | Typical tools |
|---|---|---|
| Managing prompts | Which text is live, who changed it, and can we roll back? | Git, or a prompt registry with versions and labels |
| Caching | How do we avoid paying for, and waiting on, the same tokens twice? | The provider's prefix cache; response, embedding and prompt registry caches |
| Observing | What did the model see, what did it cost, did quality hold after a change? | Tracing on OpenTelemetry, evaluation datasets, LLM judges |
The three interact more than tooling suggests. How a prompt is assembled decides whether it caches; a registry that swaps prompt text changes what caches; and without traces linked to prompt versions, nobody can tell whether a cheaper prompt is also a worse one.
Prompts are code
Most prompt problems are ordinary software problems in an unusual file format. The practices that fix them are ordinary too:
- One source of truth. Prompts live in the repository next to the code that calls them, or in a registry that the code fetches from. Not both: two copies drift, and nobody knows which one production read. I have seen it happen, and the fix is below.
- A frozen stable part. Instructions, reference material and examples stay byte-identical across calls. Dates, user names, request IDs and the question go at the end. This is also the single most important rule for caching, below.
- Deterministic assembly. Tools in a fixed order, JSON with stable key order, no conditional sections that create one variant per feature flag.
- Structure through the API, not through pleading. Structured outputs, and tool schemas in strict mode, guarantee the format; "reply in valid JSON, please" does not.
- A change is a deploy. Small wording edits change behaviour in ways nobody predicts from reading the diff. Run each change against a fixed evaluation set before it reaches users, and record which version served which traffic.
- Prune. Long prompts collect instructions written for older models: shouting in capitals, repeated warnings, workarounds for bugs fixed long ago. Newer models can follow them too literally. Review a prompt as you would review dead code: delete what no longer earns its place.
How provider caching works
Providers cache the computation for the start of a prompt, so a repeated prefix is billed and processed cheaply. On Claude, caching is an exact prefix match over the request in a fixed order: tools, then the system prompt, then messages. You mark where the reusable prefix ends with cache_control, up to four breakpoints per request, or let automatic caching place one for you.
The rules that matter in practice, from Anthropic's documentation:
| Rule | Value | What it means |
|---|---|---|
| Write price | 1.25 times input for a 5-minute lifetime, 2 times for 1 hour | The first call pays a premium |
| Read price | About 0.1 times input; 0.05 times on Claude Sonnet 5.5 and Opus 5.5 | With a 5-minute lifetime, the second call already pays back the write |
| Lifetime | 5 minutes or 1 hour, reset by every read | Steady traffic keeps a cache warm for free |
| Minimum length | 512 tokens on the newest models, up to 4,096 on some older ones | A short prompt never caches, and no error says so |
| Scope | Per model and per workspace | Switching models or splitting traffic across workspaces starts cold |
What the live calls showed
To put numbers on this, I ran 103 calls on Claude Sonnet 5.5 against an invented support handbook, with effort pinned to low and every figure taken from the usage fields the API returns: 26 for the caching tests below, 76 in two latency runs, and one test call. Total cost: about USD 10, most of it the deliberate cold calls on long prompts in the latency runs.
| Test | Tokens written to cache | Tokens read from cache | Cost per call (USD) |
|---|---|---|---|
| Stable prefix, first call | 7,841 | 0 | 0.0204 |
| Stable prefix, second call | 0 | 7,841 | 0.0019 |
| Stable prefix, third call | 0 | 7,841 | 0.0015 |
| Timestamp in system prompt (each call) | 7,864 | 0 | 0.0204 |
| Timestamp moved after the prefix | 0 | 7,841 | 0.0015 |
| Two tools added | 8,207 | 0 | 0.0215 |
| Same tools again | 0 | 8,207 | 0.0015 |
| Same tools, reversed order | 8,207 | 0 | 0.0217 |
| Effort changed, low to medium | 0 | 7,841 | 0.0016 |
| 50-token system prompt | 0 | 0 | 0.0020 |
| 1-hour lifetime, first call | 7,785 | 0 | 0.0317 |
| 1-hour lifetime, second call | 0 | 7,785 | 0.0017 |
Five findings follow directly:
- A stable prefix pays immediately. The first call wrote 7,841 tokens for USD 0.0204; the next two read them for USD 0.0019 and 0.0015.
- One timestamp undoes it. "Current time" at the top of the system prompt made every call a fresh cache write, at USD 0.0204 each. Moving the same timestamp into the user message restored the reads, with the model still seeing the time.
- Tools are part of the key. The same two tools in reverse order rewrote all 8,207 tokens. Sort tool lists, and never build them per user.
- Pinned settings matter. On Sonnet 5.5, changing effort from low to medium kept the system-prompt cache, but the documentation warns that thinking and effort changes invalidate the message cache and, on some models, more. Pin them per route.
- Short prompts fail silently. A 50-token system prompt with a cache marker wrote nothing and read nothing, with no warning.
Automatic caching handles conversations well. In a four-turn chat with one top-level cache_control, each turn read everything before it: 7,841, then 7,860, 7,945 and 8,052 tokens, writing only the newest exchange.
Caching and latency: less than you might expect
Caching is often sold on speed as well as cost, so I measured that too. Time to first token was taken with thinking off for the answer, 10 interleaved calls per group, on prompts of about 31,000 and 152,000 tokens. Cold calls got a unique first line so they could not hit any cache.
| Prompt | Median, cold | Median, cached | Slowest quarter starts at, cold / cached | Cost per call, cold / cached (USD) |
|---|---|---|---|---|
| About 31,000 tokens | 0.81 s | 0.81 s | 0.94 s / 0.85 s | 0.079 / 0.0039 |
| About 152,000 tokens | 0.97 s | 0.91 s | 1.72 s / 0.99 s | 0.380 / 0.0162 |
On this API, at these sizes, caching did not change the typical wait: the medians differ by hundredths of a second. It did narrow the tail on the large prompt, where the slowest cold call took 2.9 seconds against 1.4 for the slowest cached one. At these sizes, processing the prompt was evidently not what kept the first token waiting. Ten calls per group is a small sample, so I would not claim more than this: the reliable gain is cost, and any latency gain should be measured on your own traffic rather than assumed. An earlier run with adaptive thinking left on was noisier still, because the time the model spends thinking varies from call to call and swamps everything else.
Patterns that keep the cache warm
Two of my own projects show what this looks like in code. The CircassianDNA site's assistant builds every request the same way: tools and system prompt constant, reference documents next in a fixed order with one breakpoint on the last of them, and everything volatile (a mode line, the history, the question) after it. A test asserts that the cached prefix is identical across modes and questions, and that the system prompt contains no date. An agent harness I built for a Kaggle hackathon talks to several model families; it adds cache markers only for Claude, which needs explicit marks, on the system prompt and the newest message, and reads cached-token counts from the usage fields of the other providers' APIs.
The request side, in Python:
import anthropic
client = anthropic.Anthropic()
HANDBOOK = open("handbook.md").read() # stable: loaded once, never formatted with request data
def ask(question: str, now: str) -> anthropic.types.Message:
"""One support answer. Stable text is cached; everything that varies comes after it."""
return client.messages.create(
model="claude-sonnet-5-5",
max_tokens=300,
output_config={"effort": "low"}, # pinned per route: changing it invalidates cached messages
system=[{"type": "text", "text": HANDBOOK, "cache_control": {"type": "ephemeral"}}],
messages=[{"role": "user", "content": f"(Current time: {now}.) {question}"}],
)
def usage_row(message: anthropic.types.Message) -> dict:
"""Log these four numbers on every call; the cache hit rate falls out of them."""
u = message.usage
prompt = u.input_tokens + u.cache_creation_input_tokens + u.cache_read_input_tokens
return {"uncached": u.input_tokens, "written": u.cache_creation_input_tokens,
"read": u.cache_read_input_tokens, "output": u.output_tokens,
"hit_rate": round(u.cache_read_input_tokens / prompt, 3) if prompt else 0.0}
On the stable-prefix calls above, that hit rate was 0.997: 7,841 of 7,862 prompt tokens came from the cache. Chart it per route, and a silent invalidator shows up as a cliff the day it ships.
And the test that keeps it honest. It needs no API key and runs in milliseconds:
import json
import re
HANDBOOK = "You are the support assistant for Northwind Home. Answer from this handbook only.\n..."
TOOLS = [{"name": "lookup_order", "description": "Find an order by its number.",
"input_schema": {"type": "object", "properties": {"order_id": {"type": "string"}}}}]
def build_request(question: str, now: str, history: list[dict] | None = None) -> dict:
return {
"tools": TOOLS,
"system": [{"type": "text", "text": HANDBOOK, "cache_control": {"type": "ephemeral"}}],
"messages": [*(history or []), {"role": "user", "content": f"(Current time: {now}.) {question}"}],
}
def cached_prefix(request: dict) -> str:
"""The bytes the cache keys on: tools, then system. No sort_keys: compare what is sent."""
return json.dumps([request["tools"], request["system"]], ensure_ascii=False)
def test_prefix_is_identical_across_questions_times_and_history():
a = build_request("How long do I have to return a kettle?", "2026-12-02 09:00")
b = build_request("Is the label free?", "2026-12-02 17:45",
history=[{"role": "user", "content": "hi"}, {"role": "assistant", "content": "hello"}])
assert cached_prefix(a) == cached_prefix(b)
def test_nothing_volatile_in_the_stable_text():
assert not re.search(r"\d{4}-\d{2}-\d{2}|\d{1,2}:\d{2}", HANDBOOK)
A test is the right tool here because caching failures are silent. Nothing errors; the bill rises. To check the test is not vacuous, I put a timestamp into the stable text: the prefix test failed at once.
The other half is choosing the lifetime by the gap between calls that share a prefix:
| Gap between calls sharing the prefix | Lifetime | Why |
|---|---|---|
| Under 5 minutes | 5 minutes | Every read resets the timer, so the cheaper write stays warm |
| 5 to 60 minutes | 1 hour | The only window where the doubled write pays off |
| Over an hour | Neither | Accept the cold call, or re-warm on a schedule |
Four things called caching
Provider caching is one of four mechanisms that share the name, and they fail in different ways.
| Cache | What it stores | Main risk |
|---|---|---|
| Response or semantic cache | Whole answers, keyed by the question or its embedding | A stale answer after the data changed, or one user's answer served to another |
| Prompt registry cache | The prompt template, inside the SDK | A short delay before a new version reaches every instance |
| Embedding cache | Vectors for documents and queries | Vectors from an old embedding model mixed with new ones |
| Provider prefix cache | The model's computation for a prompt prefix | Silent misses that only show on the bill |
Only the last is exact by construction: it can never return a wrong answer, only a slower or dearer one. A semantic response cache is the opposite: it trades correctness for cost, and it needs its own evaluation and its own privacy review before it goes anywhere near user data.
Where Langfuse fits
Langfuse is an open-source platform for LLM engineering: tracing built on OpenTelemetry, evaluations (LLM judges, code checks, user feedback), datasets and experiments, and prompt management with versions, labels and a playground. It is MIT licensed except for its enterprise folders, can be self-hosted with Docker or Kubernetes, and has been part of ClickHouse since January 2026. Self-hosted instances send basic usage statistics unless TELEMETRY_ENABLED=false is set.
Prompt management works like this. Every saved prompt gets a version number. Labels point at versions: latest follows the newest automatically, and fetching without a label serves the version labelled production. If no version carries the requested label, the request fails rather than falling back. In Python:
from langfuse import get_client
langfuse = get_client() # reads LANGFUSE_PUBLIC_KEY, LANGFUSE_SECRET_KEY, LANGFUSE_BASE_URL
prompt = langfuse.get_prompt(
"support-system",
label="production", # the default when no label is given
cache_ttl_seconds=60, # the default; a stale copy is served while it refreshes in the background
fallback="You are the support assistant for Northwind Home. Answer from the handbook only.",
)
if prompt.is_fallback:
print("warning: serving the fallback prompt") # alert on this: the registry was unreachable
system_text = prompt.compile(brand="Northwind Home") # {{brand}} in the template: stable values only
with langfuse.start_as_current_observation(
as_type="generation", name="support-answer", model="claude-sonnet-5-5", prompt=prompt
):
... # the model call goes here; the trace now records which prompt version produced it
After the first fetch, the SDK caches each prompt for 60 seconds by default and serves the stale copy while it refreshes in the background, so later fetches do not block a request. If the cache is empty and Langfuse is unreachable, get_prompt raises, unless a fallback prompt is given, and prompt.is_fallback tells you when one was used. Passing the prompt object to a generation links each trace to the prompt version that produced it, which is the feature that makes the rest worth having: cost, latency and evaluation scores can then be compared version by version.
The trade-offs are worth deciding before adoption, not after:
| Issue | What happens | What I would do |
|---|---|---|
| Editing outside code review | Anyone with access can move the production label to new text, with no pull request | Require an evaluation run before promotion; protected labels restrict who can move them, on Enterprise or the Pro plan with an add-on |
| Two sources of truth | The repository and the registry drift apart | Pick one. Where people edit prompts in the registry, make it the source of truth; otherwise keep git and sync to the registry |
| Caches interacting | A label move changes the system prompt and costs one cold write per prefix; an A/B test across versions splits the provider cache in two | Budget for both, and keep per-request values out of compiled templates |
| Personal data in traces | Prompts and answers land in a second system | Pseudonymise before logging, set retention, self-host where data must stay in a region |
| Availability | A cold start with the registry down raises an error | Ship a fallback prompt in code and alert when it is used |
The personal-data row deserves its own post, and has one: Pseudonymising Personal Data Before It Reaches an LLM. The same evaluation discipline applies to prompt versions as to models; Making LLM Evaluation Reproducible with MLflow covers the mechanics.
What production taught me
The measurements above are from invented data. These lessons are from LLM services I have worked on, and each one is in the checklist below because it happened:
- A harmless-looking edit is not harmless. A prompt change that read as a small clarification changed results for one type of document, and nobody noticed for days. Since then, every prompt change runs against a fixed evaluation set before release.
- The cache can be off for weeks without anyone knowing. Our hit rate sat near zero because the system prompt included the current date. Moving that one line after the cached prefix fixed it; a hit-rate chart would have caught it on day one.
- Copies drift. Prompts edited in the registry's UI drifted away from the copies kept in the repository. We made the registry the source of truth and stopped keeping a second copy in git.
- Tracing is a data flow. Logging every call captured customer data in a second system. Pseudonymisation has to happen before the trace is written, not as a clean-up afterwards.
- Ask the API for structure. Asking for JSON in the prompt failed often enough to matter. Structured outputs removed that class of error entirely.
A checklist
- Keep the system prompt and tools byte-identical across calls; put time, IDs and questions last.
- Write a test that compares the cached prefix across two different requests, and check that it fails when you break it.
- Log
cache_creation_input_tokensandcache_read_input_tokenson every call and chart the hit rate. - Pin model, thinking and effort per route; one model per cached route.
- Choose the cache lifetime from the gap between calls, not by habit.
- Version prompts in one place, link traces to versions, and gate promotion on an evaluation set.
- Ship a fallback prompt in code if a registry serves production.
- Measure latency on your own traffic before promising that caching makes anything faster.
Why this is worth the effort
Prompt engineering is usually described as the craft of wording. In production, most of the value is elsewhere: in prompts that are assembled the same way every time, tested like code, versioned in one place and traced to their effect. The measurements make the economics concrete. On the 7,800-token prompt, the position of one timestamp decided a roughly tenfold difference in cost per call; on the 152,000-token prompt, a cold call cost 24 times a cached one. That is a cheap fix to make once, and an expensive one to discover on an invoice.
Sources
- Claude documentation: prompt caching
- Claude documentation: pricing
- Langfuse: prompt management
- Langfuse: prompt caching in the SDKs
- Langfuse: guaranteed availability and fallbacks
- Langfuse: versions, labels and protected labels
- Langfuse: linking prompts to traces
- Langfuse on GitHub
- OpenTelemetry semantic conventions for generative AI