Skip to main content
Back to all articles
AI Engineering 8 min readUpdated August 31, 2026

Prompt Caching Rewards Boring Prompt Architecture

Provider prompt caches work best when reusable instructions, tool contracts, and background context form a stable prefix. This article restructures agent prompts for cacheability without mixing tenant data, hiding prompt changes, or optimizing away correctness.

By Salman Butt · Senior Full-Stack & Generative AI Engineer
#prompt-caching#prefix-caching#llm-cost#context-engineering#ai-agents#performance#typescript#python
On this page

A prompt cache is one of those optimizations that sounds automatic until you look at the hit rate.

The application sends a 20,000-token system prompt on every request. Most of it is identical: operating policy, examples, tool definitions, output rules, and product documentation. Only the user message changes.

Prompt caching should be ideal.

Then somebody adds a timestamp near the top. Tool definitions arrive in nondeterministic order. A request ID is interpolated into the system text. Retrieved documents are inserted before the stable instructions. The prompt still looks equivalent to a human, but its prefix changes on every request.

The cache quietly becomes much less useful.

That is why I treat prompt caching as a prompt-architecture problem rather than a provider checkbox. The optimization rewards something I already want in production systems: stable policy separated from dynamic request state.

This is different from the semantic cache in the previous article. Semantic caching can reuse an application answer across similar questions. Prefix caching still runs the model; it avoids repeatedly processing an identical reusable prefix.

Draw the prompt boundary explicitly

I divide model input into sections with different rates of change.

Text
stable / slow-changing  system policy  response contract  durable examples  stable tool definitions  static product/background context​request-scoped  authenticated actor projection  current resource state  retrieved evidence  recent conversation tail  user message

That ordering is useful even without provider caching. It makes it obvious which data is policy and which data is observation.

With prefix caching, it also gives repeated requests a large identical beginning.

Build stable content from versioned artifacts

I do not want the system prompt assembled from ten helpers that each inject whatever happens to be convenient today.

A small prompt bundle makes changes explicit:

type PromptBundle = {  version: string;  systemPolicy: string;  responseContract: string;  examples: string[];};​type RequestContext = {  userMessage: string;  recentMessages: Array<{ role: "user" | "assistant"; content: string }>;  evidence: string[];  currentState: string;};​function buildMessages(  bundle: PromptBundle,  context: RequestContext,) {  const stablePrefix = [    `Policy version: ${bundle.version}`,    bundle.systemPolicy,    bundle.responseContract,    ...bundle.examples,  ].join("\n\n");​  const dynamicContext = [    context.currentState,    ...context.evidence,  ].join("\n\n");​  return [    { role: "system" as const, content: stablePrefix },    ...context.recentMessages,    {      role: "user" as const,      content: `${dynamicContext}\n\n${context.userMessage}`,    },  ];}

The actual provider request shape will differ. The architectural point is the stable ordering and versioned boundary.

Do not put a timestamp in the stable prefix

This looks harmless:

Text
You are the support assistant.Current time: 2026-07-18T09:31:04ZFollow these rules...

Now the prefix changes every second.

If the model needs time, put it later in request-scoped context or expose a clock tool when current time is only needed conditionally.

The same applies to:

Text
request IDrun IDuser IDrandom noncecurrent token budgetretrieval queryfeature experiment assignment

Those values may be important. They do not belong before a large reusable prefix unless they genuinely change how the stable content should be interpreted.

Stable does not mean global

A cache optimization should never cause tenant-specific content to cross a trust boundary.

Suppose each tenant has a custom policy document. I have two choices:

  1. include that policy in the stable prefix for requests within the same permitted cache scope;
  2. keep the globally stable prefix smaller and append tenant policy dynamically.

Which is better depends on provider cache isolation, workload, policy size, and security requirements.

I never assume that identical-looking cache keys imply application-level authorization. Provider-side prompt caching and my tenant access model are separate things.

The host still decides which data can enter a request.

Tool definitions are often the biggest accidental prefix churn

An agent with many tools can spend thousands of tokens describing them.

If the set and ordering are stable, that can be good cache material. If the application rebuilds the array from an unordered map, every request can produce a different serialization.

I normalize before sending:

type ToolDefinition = {  name: string;  description: string;  inputSchema: unknown;};​function stableTools(tools: ToolDefinition[]): ToolDefinition[] {  return [...tools].sort((a, b) => a.name.localeCompare(b.name));}

This does not mean “sort tools alphabetically” is a universal provider requirement. It means the application should produce deterministic ordering when order has no semantic reason to vary.

If tool order affects model behavior in your evaluations, preserve the chosen order as a versioned artifact instead.

Dynamic tool retrieval can help or hurt

Earlier in this series I argued that a model should not receive hundreds of irrelevant MCP/tool schemas on every turn.

That still holds.

There is a tradeoff:

Text
large stable tool prefix  more tokens per cache miss  potentially strong cache reuse  more tools for model to discriminate​small dynamically selected tool set  fewer schema tokens  better selection focus  prefix may change between tasks

The right answer comes from measurement, not ideology.

I track both:

Text
raw tool-definition tokenscached tool-definition tokenscache hit ratemodel tool-selection accuracylatencytotal request cost

Saving 8,000 schema tokens is not useful if the new selection layer misses the correct tool. Preserving a perfect cache hit is not useful if the model has to choose among 150 irrelevant capabilities.

Optimization happens after correctness.

Conversation history naturally creates moving prefixes

Multi-turn agents add a new message each turn. Some providers support caching patterns designed for growing conversation history; the exact controls differ and should be checked against current provider documentation.

At the application layer, I still keep history deterministic.

Do not rewrite earlier messages every turn just to make them prettier. Do not reserialize tool results into a different shape after they have already become durable history. Do not insert a new system instruction in the middle of an old conversation unless the product genuinely changed policy.

A growing transcript is easier to cache and replay when earlier content remains immutable.

That is also good durable-workflow design.

Compaction changes the cache boundary deliberately

Context compaction eventually replaces old history with a summary.

That is expected to invalidate part of the previous prefix.

I treat compaction as a versioned event:

TypeScript
type CompactionArtifact = {  id: string;  sourceThroughEventId: string;  summary: string;  summarizerVersion: string;  createdAt: string;};

Once generated, the artifact itself should remain stable for later turns. Re-summarizing the same old history differently on every request creates both behavioral drift and cache churn.

This is another place where caching pressure leads toward cleaner state management rather than provider-specific hacks.

Exact cacheability depends on exact bytes or blocks

Semantic equivalence does not normally help a prefix cache.

These two instructions mean the same thing to a person:

Text
Answer concisely.
Text
Keep your answer concise.

They are different prompt content.

That means “harmless” copy edits to a large prefix can cause a temporary drop in hit rate. I expect that during a prompt deployment and monitor it rather than mistaking the higher input cost for a traffic anomaly.

Prompt versions make those transitions explainable.

Use a content hash to detect accidental changes

Before sending the stable section, I can hash its canonical representation and put the hash in application telemetry.

import { createHash } from "node:crypto";​function prefixFingerprint(value: string): string {  return createHash("sha256").update(value, "utf8").digest("hex");}

I do not send this hash to make the provider cache work. The provider has its own mechanism.

The fingerprint is for me.

If prompt.version=17 suddenly has six different fingerprints in production, some supposedly stable builder is injecting dynamic state. That is much faster to diagnose than inspecting raw prompts containing customer data.

Track writes and reads separately

A prompt cache is not free simply because it has the word cache in the name.

Providers can account for cache creation and cache reads differently. The exact prices and TTLs change, so I do not embed them into application logic from a blog post.

I do record usage fields separately when the provider exposes them:

TypeScript
type PromptCacheUsage = {  uncachedInputTokens: number;  cacheWriteTokens: number;  cacheReadTokens: number;};

That lets a cost pipeline answer:

Text
How many input tokens were actually reused?Are we paying repeatedly to create prefixes that nobody reuses?Which workflow versions have poor cache hit rates?

A cache with frequent writes and few reads can cost more operational complexity than it saves.

Traffic shape matters

A 50,000-token prefix reused by 5,000 requests in a short window is an obvious candidate.

The same prefix used once every few hours may never remain warm long enough to matter, depending on the provider's cache lifetime and behavior.

I therefore evaluate caching against real traffic distribution:

Text
requests per prefix versioninter-arrival timeprefix token sizereuse countcache read/write tokenslatency deltacost delta

Average daily traffic can hide this. Ten thousand requests spread across ten thousand unique prompt variants have almost no reuse.

Warming is situational

It can be tempting to send a dummy request after a deployment to warm a large prompt prefix.

That only makes sense when the provider's cache behavior supports it, the expected near-term traffic justifies the write, and the warm-up request itself is safe and measurable.

I do not build background traffic merely to make a dashboard show a higher cache-hit percentage.

Natural warm-up from the first real request is often enough.

A cache miss should never change correctness

This is the most important property.

The system should produce an acceptable result whether the provider serves the prefix from cache or processes it from scratch.

If a miss causes timeouts because the uncached request cannot fit the latency budget, the service has become dependent on an optimization it does not control completely.

I budget for the uncached path, then treat caching as a reduction in cost and latency.

The same rule applies during provider incidents, cache expiry, deployments, and new prompt versions.

Security and privacy still apply to cached content

Do not move secrets or unnecessary personal data into the stable prefix because it gets reused often.

A cached prefix is still model input. Provider retention and cache isolation rules matter. So do your own policies around what data may be sent to that provider in the first place.

The safest stable prefix is usually policy, schemas, public/static context, and carefully chosen examples—not a convenient dump of user or tenant data.

If sensitive context must be present, scope it deliberately and verify the provider's current data-handling guarantees for the deployment you use.

Evaluate prompt changes with cache state visible

When comparing two prompt versions, I want two views:

Text
quality / task success  independent of cache state​operational behavior  cached latency  uncached latency  cache read/write tokens  total cost

Otherwise a newly deployed prompt can look “slower” simply because it is cold, or an old version can look cheaper because most of its prefix is already cached.

Do not confuse a cache-warm baseline with a model-quality improvement.

When prefix caching is not worth designing around

Short prompts, low traffic, highly unique context, or a workflow whose tools/policy change every request may offer little reusable prefix.

In those systems I keep the prompt clean but do not distort the architecture chasing cache hits.

The useful case is repetitive structure: long system policy, large stable examples, durable tool definitions, or conversation history reused across turns.

The engineering lesson is pleasantly boring.

Put stable things together. Keep dynamic things out of their way. Version what changes. Make ordering deterministic. Measure the uncached path and the cached path separately.

Prompt caching then becomes a consequence of good context architecture instead of another fragile layer of magic around the model.

KEEP READING

Related engineering notes