Sub topic 13
Routing Hints and Cache Keys for High-Volume Traffic
This chapter covers what happens when one prompt prefix is sent many times per minute. It assumes you know exact prefix matching, cache lifetime, and how to read usage fields from earlier chapters. You should also be able to read short Python snippets.
Why routing affects cache hits
A cached prefix is not a global file. It is attention state held in memory on specific machines in the provider's fleet. A request can only hit the cache if it reaches a machine that already holds that prefix.
At low volume this rarely matters. A few requests per minute usually land on the machine that handled the previous one. At high volume the provider spreads load across many machines. Some of your requests then reach machines that have never seen the prefix, and those requests are misses even though the prompt is byte-for-byte identical.
Routing hints exist to reduce this problem. They tell the provider which requests belong together, so they are sent to the same place.
How providers handle it
Providers differ in how much control they give you.
| Provider style | What you control | Routing hint |
|---|---|---|
| Explicit breakpoints (for example Anthropic's `cache_control`) | Where the cached prefix ends | None in the request. The cache is scoped to your organization or workspace, and the provider handles placement. |
| Automatic caching (for example OpenAI) | Nothing about where the prefix ends | An optional `prompt_cache_key` parameter that is combined with the prefix when routing. |
Details change often, so confirm the current behavior in your provider's documentation. The rest of this chapter uses the automatic-caching model, where a cache key is available. If your provider offers no such key, the layout and measurement advice still applies, but you cannot steer routing yourself.
How a cache key works
In the automatic-caching model, the provider routes a request using a hash of the start of the prompt. OpenAI's documentation describes this as roughly the first 256 tokens. When you pass prompt_cache_key, that value is mixed into the routing decision.
Two consequences follow:
- Requests with the same prefix and the same key go to the same machine, as long as that machine is not overloaded.
- Requests with the same prefix and different keys can go to different machines.
This toy function shows the idea. It is a model of the concept, not the provider's real algorithm.
import hashlib
MACHINES = 8
def route(prefix, key=""):
digest = hashlib.sha256((prefix + "|" + key).encode()).digest()
return int.from_bytes(digest[:4], "big") % MACHINES
PREFIX = "You are a support assistant. Follow the policy below."
print(route(PREFIX, "support-bot")) # same number every run
print(route(PREFIX, "support-bot")) # identical to the line above
print(route(PREFIX, "support-bot:1")) # usually a different machine
print(route(PREFIX, "support-bot:2")) # may collide with another keyThe same inputs always give the same machine. Different keys usually give different machines, though with only eight machines two keys can collide.
The per-prefix rate limit and overflow
A single machine can only take so much traffic for one prefix. OpenAI's documentation has stated that when requests for the same prefix and key exceed about 15 per minute, some are routed to other machines. Each of those machines starts cold, so the overflow requests miss.
This means a popular prompt can lose hits because it is popular. A single key on a prompt that receives 200 requests per minute sends most of that traffic to machines that have to build the cache first.
The fix is to spread the traffic on purpose. You split the load across several keys, so each key stays under the per-machine limit and maps to its own warm machine.
Treat the 15-per-minute figure as an example from one provider at one point in time. Look up the current number for your provider.
Choosing a key
The key should group requests that share a long prefix. Granularity is the main decision.
| Key granularity | Example | Effect |
|---|---|---|
| No key | (omitted) | Routing depends only on the prefix. Fine for low volume. |
| Per prompt template | `support-bot-v3` | Groups all requests that share the same instructions. Good default. |
| Per tenant | `tenant-1042` | Useful when each tenant has its own large document or policy in the prefix. |
| Per conversation | `conv-9f3a` | Keeps a long chat on one machine. It only helps if conversations are long and active. |
| Random per request | `uuid4()` | Defeats caching. Never do this. |
Choose the coarsest key that still matches your shared prefix. A key finer than your prefix sharing splits requests that could have shared a cache entry. A key coarser than your traffic can handle causes overflow.
Sharding a hot prefix
When one prefix receives more traffic than a single machine takes, add a shard number to the key. Estimate the shard count from your rate:
shards = ceil(requests_per_minute / per_machine_limit)At 120 requests per minute and a limit of 15, you need 8 shards. Each shard then carries about 15 requests per minute, which also keeps its cache entry refreshed well within the cache lifetime.
Pick the shard from a stable value, such as a user or session ID, so one conversation stays on one shard. Use hashlib, not Python's built-in hash(). The built-in hash() of a string changes between processes, so two of your servers would pick different shards for the same user.
import hashlib
from openai import OpenAI
client = OpenAI()
PROMPT_ID = "support-bot-v3"
SHARDS = 8
POLICY = open("policy.md").read() # long, identical for every request
def cache_key(session_id):
h = int.from_bytes(hashlib.sha256(session_id.encode()).digest()[:4], "big")
return f"{PROMPT_ID}:{h % SHARDS}"
def ask(session_id, question):
response = client.chat.completions.create(
model="YOUR_MODEL_NAME",
messages=[
{"role": "system", "content": POLICY},
{"role": "user", "content": question},
],
extra_body={"prompt_cache_key": cache_key(session_id)},
)
usage = response.usage
cached = usage.prompt_tokens_details.cached_tokens
return response.choices[0].message.content, cached, usage.prompt_tokens
answer, cached, total = ask("user-77", "Summarize the refund rules.")
print(f"cached {cached} of {total} prompt tokens")The extra_body argument passes the field through even if your SDK version has no named prompt_cache_key parameter. Newer SDK versions accept it directly.
The prompt must still meet the minimum cacheable length. The key only changes where the request goes, not whether the prompt qualifies.
Measuring the effect
Do not guess whether a key helps. Log the key with each request's usage and compare hit ratios before and after the change.
The usage fields differ between providers, and this matters when you reuse the ratio function from the measuring chapter:
- In OpenAI's response,
prompt_tokensincludes the cached tokens, andcached_tokensis a subset. The ratio iscached_tokens / prompt_tokens. - In Anthropic's response,
input_tokensexcludes cache reads and writes. The ratio needs all three counters in the denominator.
Group the ratio by key or shard. A healthy pattern is a low ratio on the first request for each key, then a high ratio afterward. If one shard is much lower than the others, check whether its traffic is too sparse to stay warm or too heavy and overflowing.
Common mistakes
- Putting a per-request value in the key. A request ID or timestamp gives every request a new key. Routing becomes effectively random, and a provider that mixes the key into routing can no longer group your traffic.
- Using too many shards. Spread 20 requests per minute across 8 shards and each shard gets fewer than 3. Gaps between requests may exceed the cache lifetime, so entries expire.
- Expecting a key to fix a prefix mismatch. The key only affects routing. If a timestamp near the top of the prompt changes the prefix, the key cannot save the hit.
- Changing the key format during a deploy. Renaming
support-bot-v3tosupport-bot-v4sends all traffic to cold machines. Expect a temporary drop in hits and cost spike. - Treating the key as a security boundary. Caches are already isolated by organization. The key is a routing hint, so do not rely on it for access control. Use opaque identifiers, not names, emails, or secrets, because keys may appear in logs.
Request flow
When you do not need any of this
Most applications can skip keys entirely. If a given prefix receives fewer than a few requests per minute, routing already works well. If your prefix is unique per request, no key can help. Add sharding only when logged hit ratios show that high-volume prompts are missing despite stable prefixes.
Exercise
Your support bot sends 90 requests per minute with an identical 3,000-token system prompt, and the provider overflows traffic above about 15 requests per minute per prefix and key. How many shards should you use, how would you pick the shard for each request, and what would you log to confirm it worked?
Show answer
Use ceil(90 / 15) = 6 shards. Derive the shard from a stable value such as the session ID with hashlib (not Python's built-in hash()), and set promptcachekey to something like "support-bot-v3:<shard>". Log the key, the cached token count, and the total prompt tokens for each request, then compare the hit ratio per shard before and after the change. Each shard should show a miss on its first request and high ratios afterward.
Exercise
After a deploy, hit ratio falls from 90% to near 0% for ten minutes, then recovers. The prompt text did not change. Name one likely cause related to this chapter and one related to earlier chapters.
Show answer
Related to this chapter: the cache key format changed, for example from "support-bot-v3" to "support-bot-v4", so traffic went to machines that held no cache and had to rebuild it. Related to earlier chapters: a stable-looking part of the prefix changed, such as tool definitions being reordered or a version string added near the top, which breaks the exact prefix match. Both recover once new entries are written.