Back to Home
Cache-Aware Prompt Layout: Stable Prefixes, Volatile Suffixes
Cost optimization8 min readSource: Admesh Engineering

Cache-Aware Prompt Layout: Stable Prefixes, Volatile Suffixes

How to order system prompts, tools, references, and user turns so prompt caching actually hits, plus multi-tenant boundaries and a pre-ship checklist.

Why prompt order is a cost decision

Prompt caching works on prefixes. The provider hashes the start of your request and looks for a match from an earlier call; the moment one byte differs, everything after that point is treated as new input. That means a prompt with the same content but a different order can have wildly different cache behavior, and a single dynamic field near the top can erase the savings for the entire request.

The practical consequence is that prompt layout is an engineering artifact, not a writing style. If your system prompt starts with a greeting that includes the current date, or your tool list is serialized from a dict whose key order changes between processes, you are paying full price on every call while believing you have caching enabled. The fix is structural: decide which bytes are stable across requests, put them first, and keep them byte-stable.

The four layers of a production prompt

Most production prompts decompose into four layers with very different stability profiles. Ordering them from most to least stable gives the cache the longest possible reusable prefix.

  • Layer 1, identity and rules: system instructions, persona, output format rules, safety constraints. These change only when you deploy a new prompt version, so they are the best cache candidates.
  • Layer 2, tool definitions: JSON schemas for function calling. Stable for as long as your tool surface is stable, and usually large enough that caching them is worth real money in agent loops.
  • Layer 3, long-lived reference material: product documentation, policy text, few-shot examples, style guides. Stable per tenant or per product, but not necessarily global.
  • Layer 4, the volatile tail: the user turn, retrieved chunks, timestamps, request IDs, conversation history that grows each turn.

Where dynamic fields belong

Every field that changes between requests is a cache boundary. The goal is to have exactly one boundary, as far to the right as possible. In practice this means auditing your prompt builder for anything that varies and moving it into the final message or a trailing metadata block.

Timestamps are the classic offender. A line like 'Current time: 14:32:07' at the top of a system prompt guarantees a miss on every call, and it buys you almost nothing that a tool call or a trailing context line would not. Request IDs, trace IDs, user IDs used only for logging, and A/B experiment flags have the same problem: they are observability data smuggled into the prompt. Put them in the tail, or better, in headers and logs rather than the prompt body.

  1. List every interpolation in your prompt template and mark each one as static, per-tenant, per-session, or per-request.
  2. Move all per-request values into the final user message or a trailing block after the reference material.
  3. For per-session values like conversation history, append rather than prepend so earlier turns stay in the cached prefix.
  4. Serialize tool schemas deterministically: sort keys, avoid unordered maps, and pin the schema version.
  5. Diff two consecutive rendered prompts in a test and assert that the shared prefix length meets your target.

Multi-tenant cache boundaries

In a multi-tenant product, the stable prefix is not global. Tenant A's policy documents and tenant B's policy documents are both long-lived, but they are different bytes, so they cannot share a cache entry. The layout rule becomes: global content first, then a tenant-specific block, then the volatile tail. That way the global instructions and tool schemas can still be reused across tenants, while each tenant gets its own boundary.

The failure mode here is worse than a cache miss. If you build a shared prefix that includes tenant data and reuse it across tenants, you risk cross-tenant leakage through a cache hit, which is a security incident rather than a billing problem. Keep tenant identifiers out of the shared segment, and treat the tenant block as the start of a per-tenant cache lineage. If you have many small tenants, consider whether per-tenant caching is worth it at all; below a certain request volume the cache never warms up enough to matter.

Failure modes to watch for

  • Silent invalidation: a prompt template change, a library upgrade that reorders JSON keys, or a new field in the system prompt quietly resets your hit rate. Monitor cache read tokens, not just total tokens.
  • Cache thrashing from A/B tests: two prompt variants interleaved on the same traffic split the cache. Run experiments per variant with separate prefixes, or accept the cost.
  • Over-long prefixes: caching a huge reference block that only a fraction of requests need can cost more than it saves if the cache expires between uses. Check the provider's cache lifetime and your traffic shape.
  • Retrieved context in the prefix: RAG chunks change per query. They belong in the tail, after the stable instructions, or in a separate message.
  • Growing history: appending is correct, but unbounded history eventually pushes you past context limits and forces truncation that breaks the prefix. Plan a summarization boundary.

Checklist before shipping a prompt change

  1. Render the prompt twice with different request IDs and confirm the prefix up to the volatile tail is byte-identical.
  2. Confirm tool schemas are serialized in a stable order and versioned.
  3. Verify no timestamp, trace ID, or user-specific value appears before the tenant or volatile boundary.
  4. Check that retrieved documents and conversation turns are appended, not injected near the top.
  5. Measure cache read versus cache write tokens after deploy, and compare against the previous prompt version.
  6. Re-check provider pricing and cache lifetime on the live pricing page, since the economics of a long prefix depend on both.

How to apply this with Admesh

Admesh exposes an OpenAI-compatible base URL at https://api.admesh.ai/v1 and an Anthropic-compatible endpoint at https://api.admesh.ai/v1/messages, so the same layered prompt can be sent to different model families without rewriting your client. Keep your cache-aware layout in one prompt builder and let the transport layer decide which provider serves the request.

Use one API key and one balance across OpenAI, Anthropic, Google, DeepSeek, Qwen, Moonshot, Zhipu, and MiniMax. That makes it cheap to test whether a given layout caches well on more than one family: run the same stable-prefix prompt against two providers and compare cache read tokens in your logs. Model names and context limits change, so pull the current list from https://admesh.ai/models rather than hardcoding versions.

Before you commit to a long reference block, check the live pricing at https://admesh.ai/pricing to see how cached input is billed for the model you plan to use. Then wire the prefix-diff test from the checklist into CI, and use the console at https://console.admesh.ai to watch usage per key. The docs at https://docs.admesh.ai cover the request format for both endpoints.

Admesh API docs →

FAQ

Does prompt caching change the model's output?
No. Caching is a transport and billing optimization; the model sees the same tokens. The risk is operational, not behavioral: a layout change that breaks the prefix costs money without changing answers, so it can go unnoticed.
Should I cache the whole conversation history?
Cache the stable part and append new turns. History grows every turn, so it is only stable in the sense that earlier turns do not change. Truncation or summarization is a deliberate cache boundary; schedule it rather than letting a context limit force it.
How do I know caching is working?
Compare cache read tokens to total input tokens per request in your provider logs. If cache reads stay near zero while your prompt is unchanged, something in the prefix is varying. The prefix-diff test catches this before deploy.
Is a longer prefix always better for cost?
Not necessarily. A large prefix only pays off if it is reused before the cache expires. Low-traffic tenants or rarely used reference blocks may never amortize the cache write, so measure per workload rather than assuming.

References

Call these models through one gateway

Admesh provides a unified OpenAI-compatible API: one Base URL and one key for Claude, GPT, DeepSeek and more. New accounts get trial credit that never expires.