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.
- List every interpolation in your prompt template and mark each one as static, per-tenant, per-session, or per-request.
- Move all per-request values into the final user message or a trailing block after the reference material.
- For per-session values like conversation history, append rather than prepend so earlier turns stay in the cached prefix.
- Serialize tool schemas deterministically: sort keys, avoid unordered maps, and pin the schema version.
- 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
- Render the prompt twice with different request IDs and confirm the prefix up to the volatile tail is byte-identical.
- Confirm tool schemas are serialized in a stable order and versioned.
- Verify no timestamp, trace ID, or user-specific value appears before the tenant or volatile boundary.
- Check that retrieved documents and conversation turns are appended, not injected near the top.
- Measure cache read versus cache write tokens after deploy, and compare against the previous prompt version.
- 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.
Частые вопросы
Does prompt caching change the model's output?
Should I cache the whole conversation history?
How do I know caching is working?
Is a longer prefix always better for cost?
Источники
Вызывайте эти модели через один шлюз
Admesh предоставляет единый API, совместимый с OpenAI: один Base URL и один ключ для Claude, GPT, DeepSeek и других моделей. Новым аккаунтам доступен пробный кредит без срока действия.
