anthropic-sdk-python icon indicating copy to clipboard operation
anthropic-sdk-python copied to clipboard

[BUG] Server writes additional cache entries past explicit `cache_control` breakpoint, billing 1.25x for tokens that are never read

Open salman-a-shah opened this issue 6 months ago • 3 comments

Summary

When using an explicit cache_control breakpoint on the system block, with no top-level cache_control field (i.e., not opted into automatic caching), the server writes an additional cache entry inside the user content on warm calls. These additional writes are billed at the 1.25x cache-write rate but are never read back on subsequent calls, since they live past the only explicit breakpoint and the trailing content varies per request.

This contradicts the documented behavior at https://platform.claude.com/docs/en/build-with-claude/prompt-caching:

Cache writes happen only at your breakpoint. Marking a block with cache_control writes exactly one cache entry: a hash of the prefix ending at that block. The system does not write entries for any earlier position.

I have confirmed this reproduces against both the latest SDK (0.102.0) and older versions (0.79.0), ruling out the Python SDK as the cause. The behavior is server-side.

Reproduction

import uuid
import anthropic

# Nonce keeps Call 1 cold across re-runs of this script.
SYSTEM_PROMPT = f"<nonce>{uuid.uuid4().hex}</nonce>\n" + "FACT: The capital of France is Paris.\n" * 200
USER_BLOCK_1 = (
    "Ignore this gibberish\n" * 200 + "\nGenerate some fictional JSON data about a person from france who is "
)
USER_BLOCK_2 = " years old"
STARTING_AGE = 20


def print_cache_usage(usage):
    print(
        f"cache_creation={usage.cache_creation_input_tokens} "
        f"cache_read={usage.cache_read_input_tokens} "
        f"uncached_input={usage.input_tokens}"
    )


client = anthropic.Anthropic()


# Call 1 (cold)
response = client.messages.create(
    model="claude-sonnet-4-5-20250929",
    max_tokens=32,
    system=[{"type": "text", "text": SYSTEM_PROMPT, "cache_control": {"type": "ephemeral"}}],
    messages=[
        {
            "role": "user",
            "content": [
                {"type": "text", "text": USER_BLOCK_1},
                {"type": "text", "text": str(STARTING_AGE) + USER_BLOCK_2},
            ],
        },
        {"role": "assistant", "content": "```json"},
    ],
)
print("Call 1: ", end="")
print_cache_usage(response.usage)


# Call 2 (warm)
response = client.messages.create(
    model="claude-sonnet-4-5-20250929",
    max_tokens=32,
    system=[{"type": "text", "text": SYSTEM_PROMPT, "cache_control": {"type": "ephemeral"}}],
    messages=[
        {
            "role": "user",
            "content": [
                {"type": "text", "text": USER_BLOCK_1},
                {"type": "text", "text": str(STARTING_AGE + 10) + USER_BLOCK_2},
            ],
        },
        {"role": "assistant", "content": "```json"},
    ],
)
print("Call 2: ", end="")
print_cache_usage(response.usage)


# Call 3 (warm)
response = client.messages.create(
    model="claude-sonnet-4-5-20250929",
    max_tokens=32,
    system=[{"type": "text", "text": SYSTEM_PROMPT, "cache_control": {"type": "ephemeral"}}],
    messages=[
        {
            "role": "user",
            "content": [
                {"type": "text", "text": USER_BLOCK_1},
                {"type": "text", "text": str(STARTING_AGE + 20) + USER_BLOCK_2},
            ],
        },
        {"role": "assistant", "content": "```json"},
    ],
)
print("Call 3: ", end="")
print_cache_usage(response.usage)

Expected behavior

Per the documentation, since there is exactly one cache_control marker (on the system block), only one cache entry should be written. Warm calls should show cache_creation=0:

Call 1: cache_creation=2227 cache_read=0    uncached_input=1424
Call 2: cache_creation=0    cache_read=2227 uncached_input=1424
Call 3: cache_creation=0    cache_read=2227 uncached_input=1424

Actual behavior

Warm calls write an additional ~1416 tokens to cache, even though no second breakpoint exists. These writes are billed at 1.25x but never produce a cache read in subsequent calls:

Call 1: cache_creation=2227 cache_read=0    uncached_input=1424
Call 2: cache_creation=1416 cache_read=2227 uncached_input=8
Call 3: cache_creation=1416 cache_read=2227 uncached_input=8

There is currently no documented way to opt out.

Request

  1. Confirm whether this is intended behavior.
  2. If intended: please update the prompt-caching docs (the quoted paragraph is misleading) and provide an opt-out mechanism (header or request field) so users on explicit caching can prevent unrequested cache writes.
  3. If unintended: please patch.

Environment

  • anthropic Python SDK: 0.102.0 (also reproduced on 0.79.0)
  • Model: claude-sonnet-4-5-20250929
  • Python: 3.12.3
  • OS: Ubuntu 24.04
  • API: Direct Anthropic API (not Bedrock/Vertex)

salman-a-shah avatar May 15 '26 02:05 salman-a-shah

This matches what I've been seeing in production cost tracking — your repro is cleaner than what I had, thanks for posting it.

A few diagnostic angles in case they help your bug report land faster, plus a mitigation pattern I'm using until this is resolved server-side:

Diagnostic — surface the silent write

The usage.cache_creation_input_tokens field on the warm call is the smoking gun. Per the docs you quoted, a warm call should show:

  • cache_read_input_tokens ≈ system prompt tokens (your explicit breakpoint)
  • cache_creation_input_tokens ≈ 0 (no new cache entry)
  • input_tokens ≈ varying user-block tail

If Call 2 in your repro is instead showing cache_creation_input_tokens > 0, that's quantifiable evidence of the extra write. Would be worth adding the numbers from Call 2/3 to your issue body — gives Anthropic engineers concrete deltas to grep server logs against.

Mitigation while waiting on a server-side fix

If this is hitting production billing, route around it: when cache_creation_input_tokens on a warm call exceeds the size of your explicit cache prefix (i.e. there's an unexpected extra write), fall back to a non-cached request for that turn. Trades cache hit rate for predictable cost.

Rough sketch:

def detect_phantom_cache_write(usage, expected_prefix_tokens: int) -> bool:
    # On a warm call, only the cache_read should be populated.
    # An additional cache_creation past your breakpoint signals the bug.
    return (usage.cache_read_input_tokens > 0
            and usage.cache_creation_input_tokens > 0
            and usage.cache_creation_input_tokens > expected_prefix_tokens * 0.1)

I instrument {input, cache_read, cache_write, output, cost_usd} per request in my streaming starter for exactly this kind of cost-bleed-detection — happy to share the cost calc if useful: https://github.com/YorickLane/claude-streaming-starter/blob/main/cost.py (the 1.25× multiplier is in there).

Subscribing to the issue. If you find a server-side fix lands, I'd love a ping.

XavierZhao1989 avatar May 28 '26 10:05 XavierZhao1989

Came here looking at the same thing for a different reason — building a pre-execution budget gate (burnstop) and the cache_creation vs cache_read decomposition is one of the things I had to expose in the receipt because the SDK response shape did not surface it cleanly.

One data point: in our gate, we project the 1.25x cost separately before the call lands, using:

from burnstop.pricing import decompose_cache, estimate_cost
d = decompose_cache({}, response_body)
# d = {input, cache_creation, cache_read, output}
# estimate_cost weights cache_creation at 1.25x input rate

That lets you see per-call whether the writes inside user content (the behavior you describe) actually got re-read on warm calls, which makes the regression easy to catch even when total billing looks normal.

If it helps the repro: the gate writes a per-call jsonl ledger of (projected, actual, decomposition) that should make divergence between expected and actual cache_creation visible. We ran it against our own warm/cold pattern and saw a similar shape to what you describe (writes past breakpoint, no corresponding reads).

Not trying to derail the issue — your repro is great. Just noting the same gap from a tooling angle in case it is useful for anyone landing here while waiting for a fix.

santicalderon avatar Jun 07 '26 16:06 santicalderon

@salman-a-shah sorry for the delay here, and thanks for the precise repro. This was server-side and has since been fixed: running your script today against claude-sonnet-4-5-20250929 produces exactly your "expected" output — Call 1 cache_creation=2227 cache_read=0 uncached_input=1424, Calls 2 and 3 cache_creation=0 cache_read=2227 uncached_input=1424 — so nothing is written (or billed as a write) past your explicit breakpoint, consistent with the "cache writes happen only at your breakpoint" rule in the docs: https://platform.claude.com/docs/en/build-with-claude/prompt-caching#how-automatic-prefix-checking-works

dtmeadows-ant avatar Aug 05 '26 15:08 dtmeadows-ant