DEV Community

jidonglab
jidonglab

Posted on

Claude Prompt Caching in Parallel: 12 Calls, 12 Cache Writes, 0 Reads

I had a 40K-token contract, twelve questions about it, and a feeling of quiet competence. System prompt holds the contract, cache_control on the contract block, asyncio.gather over the twelve questions. Cached prefix, parallel calls, cheap and fast. Textbook.

Then I printed usage for every response. Twelve rows. cache_creation_input_tokens was about 40,000 on every single one. cache_read_input_tokens was 0 on every single one.

I hadn't built a cache. I'd built twelve caches, paid the write premium twelve times, and read none of them. This is the one Claude prompt caching behaviour I see bite people most often with parallel requests, and nothing in the response tells you it happened. The requests succeed. The answers are fine. The bill is just wrong.

TL;DR

  • A Claude prompt cache entry becomes readable only after the request that writes it begins streaming its response. Requests already in flight before that moment cannot read it.
  • So N parallel requests with an identical cached prefix all miss: each one writes its own entry and pays the cache-write price (1.25x base input on the default 5-minute TTL).
  • The fix: send one request, wait for its first streamed event, then fire the other N-1. They read the entry the first one just wrote.
  • Check usage.cache_read_input_tokens on the second wave. If it's zero, the fan-out is still racing.
  • The same race hits multi-agent setups: parallel workers with byte-different prompts over the same context never share a cache entry.

Why do parallel Claude requests miss the prompt cache?

Parallel Claude requests miss the prompt cache because the entry doesn't exist yet when they arrive. The cache is written during the first request's prefill, and it only becomes readable once that request starts streaming output. Every request that reached the API before that point does its own full prefill and writes its own entry.

Think about what asyncio.gather actually does. It schedules all twelve coroutines, and within a few milliseconds twelve HTTP requests are on the wire. Prefilling 40K tokens takes real time. So all twelve requests are sitting in prefill simultaneously, each one looking for a cache entry that none of them has finished creating.

There's no lock, no "wait, someone's already writing this." Each request is independent. The cache is a prefix lookup, not a coordination service.

What does the naive fan-out look like?

Here's the version I shipped, trimmed down. It looks correct, and every individual call is correct.

import asyncio
from anthropic import AsyncAnthropic

client = AsyncAnthropic()
MODEL = "claude-opus-5-5"  # any model with prompt caching

CONTRACT = open("contract.txt").read()  # ~40K tokens
SYSTEM = [
    {"type": "text", "text": "Answer questions about this contract."},
    {"type": "text", "text": CONTRACT, "cache_control": {"type": "ephemeral"}},
]

async def ask(question: str):
    resp = await client.messages.create(
        model=MODEL,
        max_tokens=2048,
        system=SYSTEM,
        messages=[{"role": "user", "content": question}],
    )
    u = resp.usage
    return u.cache_creation_input_tokens, u.cache_read_input_tokens

async def main(questions):
    rows = await asyncio.gather(*(ask(q) for q in questions))
    for i, (write, read) in enumerate(rows):
        print(f"{i:2d}  write={write:>6}  read={read:>6}")
Enter fullscreen mode Exit fullscreen mode

Every row prints write=~40000 read=0. If you run it twice within five minutes, the second run reads from cache on every call, which is exactly why this bug survives testing. You run the script, fix a typo, run it again, see beautiful cache reads, and conclude caching works.

How much does the race actually cost?

The race costs you the write premium N times instead of once, plus N-1 reads you never got. Work it out in units of "one uncached pass over the 40K prefix":

Pattern Prefix cost
No caching at all 12 x 1.0 = 12.0
Parallel fan-out with cache_control 12 x 1.25 = 15.0
One warm-up, then 11 parallel reads 1.25 + 11 x 0.1 = 2.35

Read that middle row again. Adding cache_control and then fanning out in parallel is more expensive than not caching at all. You pay 25% extra to write twelve entries, and at most one of them ever gets read again.

The read multiplier of 0.1x is the long-standing rate for most Claude models; some newer models charge even less for reads, which makes the gap between rows two and three wider, not narrower. Latency follows the same shape: twelve full prefills instead of one.

How do you fix Claude prompt caching for parallel requests?

Send one request first, wait until it starts streaming, then release the rest. You don't need the first response to finish. You need it to get past prefill, because that's when the entry becomes readable.

async def ask_streaming(question: str, started: asyncio.Event | None = None):
    try:
        async with client.messages.stream(
            model=MODEL,
            max_tokens=2048,
            system=SYSTEM,
            messages=[{"role": "user", "content": question}],
        ) as stream:
            async for event in stream:
                if started and not started.is_set() and event.type == "content_block_start":
                    started.set()
            msg = await stream.get_final_message()
    finally:
        if started:
            started.set()  # never leave the others hanging if this call fails
    u = msg.usage
    return u.cache_creation_input_tokens, u.cache_read_input_tokens

async def main(questions):
    started = asyncio.Event()
    first = asyncio.create_task(ask_streaming(questions[0], started))
    await started.wait()
    rest = [ask_streaming(q) for q in questions[1:]]
    rows = await asyncio.gather(first, *rest)
    for i, (write, read) in enumerate(rows):
        print(f"{i:2d}  write={write:>6}  read={read:>6}")
Enter fullscreen mode Exit fullscreen mode

Now row 0 shows the write, and rows 1 through 11 show roughly 40,000 under read. The finally matters more than it looks: without it, a 429 or a network error on the first call leaves started unset and the whole batch waits forever.

Is there a simpler option than waiting for the first token?

Yes: pre-warm the cache with a request that only exists to write it. The current API accepts max_tokens: 0 for this. It runs prefill, writes the cache at your breakpoint, and returns immediately with empty content and zero output tokens billed. Await it fully, then fan out with plain gather.

await client.messages.create(
    model=MODEL,
    max_tokens=0,
    system=SYSTEM,
    messages=[{"role": "user", "content": "warm"}],
)
rows = await asyncio.gather(*(ask(q) for q in questions))
Enter fullscreen mode Exit fullscreen mode

Two catches. The warm-up must render the same prefix as the real calls, so send the same model, tools, system blocks and thinking or effort settings; a different setting can write an entry your real traffic never hits. And max_tokens: 0 is rejected with stream: true, so don't route it through your streaming helper.

If your traffic already arrives continuously, skip all of this. The first real request warms the cache and the rest of the stream reads it. The race only bites when a burst starts cold.

Why does this also break multi-agent and subagent setups?

Multi-agent fan-outs hit the same wall, plus a second one. Workers launched at the same moment race exactly like my twelve questions. And workers whose prompts differ by a few bytes before the breakpoint (a role line, a worker ID, a different tool list) can never share an entry, even sequentially, because caching is an exact prefix match.

The pattern I use now:

  1. Put the shared context first and byte-identical across workers: same tools, same system blocks, same order.
  2. Put anything worker-specific after the last cache_control breakpoint, in the user turn.
  3. Warm once, then fan out.

If input cost dominates, fewer lanes over one identical prefix beat many lanes over slightly different ones. Twelve "specialized" agents that each restate the codebase in their own words are twelve cache writes.

How do you verify the cache is actually being read?

Log cache_creation_input_tokens and cache_read_input_tokens on every response, and look at the second wave of any fan-out. A healthy burst has one large write and many large reads. Twelve large writes means you raced. All zeros on both fields usually means your prefix is below the model's minimum cacheable length, which is model-dependent and fails silently with no error.

I now keep a one-line assertion in an integration test: fire a warm request, then a second identical one, and assert cache_read_input_tokens > 0. It has caught two regressions since, both from someone adding a timestamp to the system prompt. A datetime.now() in the prefix is the same bug wearing a different hat.

So why did my 12 parallel calls write 12 caches and read none?

Because a Claude prompt cache entry only becomes readable once the request that writes it starts streaming its response, and all twelve of my requests were already in prefill before that happened. Each one missed, wrote its own copy at 1.25x the input price, and none read anything, which made caching more expensive than no caching at all. The fix is to send one request first and wait for its first streamed event (or pre-warm with max_tokens: 0), then fan out the rest, and to confirm it worked by checking that usage.cache_read_input_tokens is non-zero on the second wave.


Written by the developer behind Preterview, an interview prep platform.

Top comments (1)

Collapse
 
userxnom profile image
Abdullah Naseer •

The middle row of your cost table is the part that should sting: parallel fan-out with cache_control (15.0) costs more than no caching at all (12.0), because every one of the twelve writes pays the 1.25x premium and at most one entry ever gets read again. And the second-run trap explains why it survives testing — run it twice within five minutes and every call reads from cache. One question on the max_tokens: 0 warm-up: it has to render the same prefix as the real calls, so how do you keep the prefix byte-identical when tools or system blocks drift between deploys — is that what the cache_read_input_tokens > 0 assertion is really guarding?