Prompt Caching: Designing Prompts for a Higher Cache Hit Rate
Why most prompt caching setups miss savings, the prompt patterns that break cache hits, and how to measure and fix your hit rate.
How a cache hit is actually decided
Prompt caching is a prefix-matching mechanism. When a request arrives, the provider hashes or otherwise fingerprints the beginning of your prompt and looks for a previously stored entry that matches exactly. If the first differing byte appears early, the rest of the prompt is treated as new input. There is no fuzzy matching and no semantic reuse: a single changed character in the prefix is enough to miss.
Two constraints shape your design. First, providers only cache prefixes above a minimum length, so short system messages and small few-shot blocks may never be eligible. Second, cached entries have a time-to-live. A prompt that is identical but arrives after the TTL expires is a miss, and the provider has to write a new entry. Both the minimum length and the TTL vary by provider and model, so check the current documentation rather than assuming a fixed number.
The practical consequence is that cacheability is a property of your prompt template, not of your SDK configuration. Enabling the feature is necessary but not sufficient.
The five prompt patterns that silently break caching
- Timestamps or request IDs at the top: a line like 'Current time: ...' in the system message changes the prefix on every call. Move dynamic values to the end of the prompt or into a separate user message.
- User or session identifiers in the system prompt: personalizing the opening line feels helpful but guarantees a unique prefix per user. Put identity context after the stable instructions.
- Random or non-deterministic ordering: iterating over a set of tools, documents, or few-shot examples without sorting produces a different prefix each run. Sort by a stable key.
- Interleaved dynamic and static content: alternating between retrieved chunks and instructions forces the cache to break at the first dynamic chunk. Group all static material first.
- Per-request formatting drift: whitespace changes, JSON key reordering, or template engines that inject conditional sections near the top all alter the prefix. Serialize deterministically.
Measuring hit rate and the break-even point
Most provider usage objects distinguish cached input tokens from regular input tokens. The simplest hit-rate metric is cached input tokens divided by total input tokens, aggregated over a window. Track it per endpoint and per prompt template, because a global average hides the templates that never hit.
Hit rate alone is not the goal. Cache writes are often priced higher than ordinary input tokens, while cache reads are discounted. That means a template with a low read-to-write ratio can cost more than no caching at all. To find your break-even point, compare the extra cost of writes against the savings on reads using your provider's current pricing; the ratio depends on the discount and write premium, which you should read from the live pricing page rather than assume.
Also watch the TTL against your traffic pattern. A template used once an hour may expire between calls, producing writes with no reads. In that case, either batch requests closer together or accept that caching is not worthwhile for that path.
A cache-friendly prompt template
- Put all invariant content first: system instructions, persona, output format rules, and static reference material. This block must be byte-identical across requests.
- Place few-shot examples next, sorted deterministically and serialized with a fixed key order.
- Insert retrieved documents or tool definitions after the examples, still sorted by a stable identifier.
- Put dynamic values last: timestamps, user IDs, the actual question, and any per-request flags.
- Log the hash of the prefix you send so you can correlate cache metrics with template changes and catch accidental drift.
Tradeoffs and failure modes
Restructuring prompts for cacheability can conflict with other goals. Moving user context to the end may reduce the model's attention to it, so test quality after reordering. Very long stable prefixes increase the chance of a hit but also raise the cost of a miss, so keep the stable block as small as it can be while still exceeding the minimum cacheable length.
A subtler failure is silent regression: a deploy that changes whitespace in the system prompt resets the cache for every user, and the only symptom is a cost spike days later. Prefix hashing in your logs turns that into an immediate alert. Finally, do not assume caching behaves the same across providers; minimum lengths, TTLs, and pricing all differ, so validate per model family.
How to apply this with Admesh
Admesh gives you one API key and one balance across multiple model families, which makes it practical to compare cache behavior across providers without managing separate accounts. Point your OpenAI-compatible client at https://api.admesh.ai/v1, or use the Anthropic-compatible endpoint at https://api.admesh.ai/v1/messages if your code is built around that format.
Start by checking the model catalog at https://admesh.ai/models and the pricing page at https://admesh.ai/pricing to see which models support prompt caching and how cached tokens are billed. Then restructure one high-volume prompt template using the steps above and log prefix hashes alongside the cached input token fields in each response.
Run the same template against two model families through the same key and compare hit rates and effective cost per request. Because billing is consolidated, you can attribute savings without reconciling multiple invoices. Use the console at https://console.admesh.ai to monitor usage, and the docs at https://docs.admesh.ai for endpoint details.
Частые вопросы
Does prompt caching work if my prompt is semantically the same but worded differently?
Why do I see cache writes but almost no reads?
Is a higher hit rate always cheaper?
Can I cache a prefix shorter than the minimum length?
Источники
Вызывайте эти модели через один шлюз
Admesh предоставляет единый API, совместимый с OpenAI: один Base URL и один ключ для Claude, GPT, DeepSeek и других моделей. Новым аккаунтам доступен пробный кредит без срока действия.
