Sub topic 12
Parallel Requests and Warming the Cache
This chapter assumes you have read the earlier chapters on exact prefix matching, cache lifetime, and reading usage fields. You should be comfortable calling an LLM API from Python and reading short snippets that use threads or asyncio.
Why parallel requests can all miss
A cache entry does not exist until a provider has finished processing the prefix and stored the result. A request that arrives before that point finds nothing to read.
Suppose you send 20 requests at the same moment, and all 20 share a 30,000-token prefix. None of them can read the prefix, because no earlier request has finished writing it. Each request may process the prefix in full. Depending on the provider, each may also pay the cache write price. You get no savings, and you may pay more than you would with no caching at all.
The same thing happens on a smaller scale. A request that starts 200 milliseconds after another one may still arrive before the first has written its entry.
When the entry becomes available
Providers differ in when an entry becomes readable. The details are in each provider's documentation, and they can change. Check the current documentation instead of relying on a number from this chapter.
For explicit breakpoints, such as Anthropic's cache_control, the usual guidance is that an entry is available only after the first response has begun. A second request has to wait for that first response to start before it can hit. For automatic caching, such as OpenAI's, you generally get no guarantee of when a prefix becomes readable. Hits are best-effort.
For planning, use this rule: the first request must have started returning output before you can expect any later request to read its entry.
Warming the cache
Cache warming means sending one request on purpose so that the cache entry exists before the real traffic arrives. After the warm-up, the remaining requests can read the entry.
A warm-up request needs to do three things:
- Use exactly the same prefix as the real requests, through the last breakpoint you plan to use.
- Finish writing the entry before the others start.
- Cost as little as possible beyond the write itself.
For the third point, set max_tokens to a small value, such as 1. The provider still processes the whole prompt. It only stops after a few output tokens. Input processing is the work you want to cache, and output is not needed.
import anthropic
client = anthropic.Anthropic()
POLICY = open("policy.md").read() # must meet the model's minimum cacheable length
SYSTEM = [
{
"type": "text",
"text": POLICY,
"cache_control": {"type": "ephemeral"},
}
]
def ask(question, max_tokens=512):
return client.messages.create(
model="YOUR_MODEL_NAME",
max_tokens=max_tokens,
system=SYSTEM,
messages=[{"role": "user", "content": question}],
)
def warm():
# Same system block as real traffic. Only one output token is requested.
response = ask("ping", max_tokens=1)
return response.usage.cache_creation_input_tokens
written = warm()
print("warm-up wrote", written, "tokens")The warm-up question ("ping") differs from real questions. That is fine, because the breakpoint is on the system block, and the user message comes after it. Only the text up to the breakpoint has to match.
Warm first, then fan out
Once the warm-up call returns, send the parallel work. This example uses a thread pool.
from concurrent.futures import ThreadPoolExecutor
questions = [
"Summarize the refund rules.",
"What is the return window?",
"Who pays for return shipping?",
"Are digital goods refundable?",
]
warm() # blocks until the response arrives, so the entry exists
with ThreadPoolExecutor(max_workers=4) as pool:
responses = list(pool.map(ask, questions))
for r in responses:
u = r.usage
print(u.cache_read_input_tokens, u.cache_creation_input_tokens, u.input_tokens)If warming worked, every line shows a large cache_read_input_tokens value and zero cache_creation_input_tokens. If the first column is zero for some requests, the entry was not readable yet, or something in the prefix differs between calls. Use the checks from the previous chapter on cache misses to tell which.
Warming costs money
A warm-up request is not free. You pay for processing the full prefix, at the cache write price where the provider charges one. You gain only if enough later requests read the entry.
Consider a rough comparison. Let W be the write multiplier, R the read multiplier, both relative to the normal input price, and N the number of requests that share the prefix within the cache lifetime.
| Strategy | Prefix cost, in units of the normal input price |
|---|---|
| No caching | `N` |
| Cold burst, all miss and all write | `N * W` |
| Warm first, then fan out | `W + (N - 1) * R` |
Use your provider's published W and R. As an illustration only, if W is 1.25 and R is 0.1, then for N = 20 a cold burst costs 25 units, no caching costs 20, and warming first costs 1.25 + 1.9 = 3.15 units. For N = 2, warming costs 1.35 against 2.5 for a cold burst. The warm-up request still has to be worth it, and it only is when N is greater than 1.
The warm-up request also adds latency, because the fan-out waits for it. For a long prefix this may be several seconds. If the work is a background batch job, that delay is usually acceptable. If a user is waiting, consider the alternatives below.
Alternatives to a separate warm-up
You do not always need a dedicated warm-up call.
- Let the first real request be the warm-up. Send one real request, wait until it has started returning output, then send the rest. You skip the extra call and its cost. The first user still waits for a full uncached pass.
- Warm when the prefix changes. Warm once at deploy time or when a document is loaded, not before each burst. This works when the next request is likely to arrive within the cache lifetime.
- Stagger the start. If you cannot wait for the first response, a small delay between the first and the second request still helps, but it gives no guarantee.
Keeping an entry alive
Each time a request reads an entry, the provider refreshes its lifetime, as covered in the chapter on cache lifetime. In steady traffic this keeps a popular prefix alive on its own. If traffic has gaps longer than the lifetime, the entry expires and the next request pays the write cost again.
Some teams send a periodic keep-alive request to bridge gaps. This is only worth doing when the cost of the keep-alive, one cheap read per interval, is lower than the cost of a rewrite after expiry, and when you know a real request will come soon. A keep-alive loop that runs all night for a prefix nobody uses wastes money.
import time
def keep_alive(interval_seconds, stop):
# interval_seconds must be shorter than the cache lifetime.
while not stop():
time.sleep(interval_seconds)
if stop():
break
warm()Choose interval_seconds with a margin below the lifetime. If the lifetime is 5 minutes, an interval of 4 minutes leaves room for a slow response. Always give the loop a stop condition tied to real demand.
Concurrency and multiple prefixes
Warming one prefix is simple. Real systems often have several:
- Different tenants or documents, each with its own static section.
- Several model versions.
- Different tool sets, which change the prefix from the very start.
Each distinct prefix needs its own warm-up. Warming too many of them at once can cost more than it saves. Warm the prefixes that you expect to be used often, and let rare ones warm themselves on first use.
Parallelism also interacts with breakpoints that sit at different depths. Suppose request A has a breakpoint after the system prompt and request B has one after a long document that follows it. Warming with A's shape caches only the system prompt. B then has to write the document part itself. To warm everything, the warm-up must use the deepest breakpoint that real requests use.
Multi-turn conversations in parallel
In a conversation, each turn extends the previous prompt, so the next turn can read what the last one wrote. This only works if the turns are sequential. If you send turn 3 before turn 2 has finished, turn 3 builds on a prefix that may not be cached yet.
When you branch a conversation, for example to run several tool calls or several candidate answers from the same history, treat the shared history like any other shared prefix. Make one call first to write it, then run the branches in parallel. The branch-specific text goes after the shared prefix.
Checking that warming worked
Log the three usage counters for every request, as in the earlier chapter on measuring hits. For a burst, check two things:
- The warm-up call shows a high write count and a near-zero read count.
- Every request after it shows a high read count and a near-zero write count.
def check_burst(responses, expected_prefix_tokens, tolerance=0.9):
problems = []
for i, r in enumerate(responses):
read = r.usage.cache_read_input_tokens or 0
if read < expected_prefix_tokens * tolerance:
problems.append((i, read))
return problemsAn empty list means every request read most of the prefix. A non-empty list names the requests that missed, which you can compare against the request that wrote the entry.
Common mistakes
- Warming with a different prefix. A different system prompt, tool list, or model in the warm-up creates a different entry.
- Not waiting for the warm-up. Starting the fan-out in the same moment as the warm-up reproduces the cold burst.
- Warming too early. If the entry expires before the real traffic arrives, you paid for nothing.
- Setting
max_tokensto 0 or too high. Many APIs reject 0. A large value pays for output you discard. - Forgetting that warm-ups count as traffic. They appear in your usage and cost reports, so tag or log them to separate them from real requests.
Summary of the decision
- If requests that share a prefix arrive one at a time with gaps shorter than the lifetime, you do not need to warm.
- If many requests share a prefix and start together, send one request first and wait for it to start returning output.
- If gaps in traffic exceed the lifetime and a request is likely soon, consider a warm-up or a bounded keep-alive.
- Always confirm with usage data.
Exercise
You launch 50 parallel requests that share a 20,000-token system prompt with a cache breakpoint. Usage shows every request has cachecreationinputtokens of about 20,000 and cachereadinputtokens of 0. Why did this happen, and what change would fix it?
Show answer
All 50 requests started before any of them had written the cache entry, so none could read it, and each wrote its own copy. The fix is to send one warm-up request first (with a small maxtokens such as 1), wait for its response, and then send the other 49 in parallel. Their usage should then show about 20,000 in cachereadinputtokens and near zero in cachecreationinput_tokens.
Exercise
With a write multiplier of 1.25 and a read multiplier of 0.1 (relative to the normal input price), compare the prefix cost of a cold burst of 10 requests with a warm-first burst of 10 requests, in units of the normal input price.
Show answer
Cold burst: 10 1.25 = 12.5 units. Warm first: 1.25 + 9 0.1 = 2.15 units. Warming first costs about 83% less in this example.
Exercise
A keep-alive loop pings a cache every 6 minutes, but the cache lifetime is 5 minutes. Real traffic arrives about once an hour. Name two problems with this setup.
Show answer
The interval is longer than the lifetime, so the entry expires before each ping and every ping pays a full write, which defeats the purpose. Also, with real traffic only once an hour, a keep-alive would run about 10 pings per real request, so it costs more than letting the entry expire and rewriting it once per request.