Notes / 06

Prompt cache misses and byte-identical prefixes

2026-11-17Modelry notes

Prefix caching is automatic on the DeepSeek tiers this platform serves: nothing to enable, no cache API, no TTL to manage. It still fails for most teams, because a cache is matched on bytes. A timestamp in the system prompt, a dictionary whose key order drifts between processes, a regenerated tool schema with one reworded description — each one changes the prefix and resets the hit rate to zero. This article shows how to observe cache hits in usage, how to fingerprint your prefix so a regression is visible in CI, and the three habits that quietly destroy a cache, with the measurement that proves each fix.

Where the cache shows up

You do not configure it and you cannot flush it. You can only read whether it happened. Two field shapes exist across providers and a normalising gateway accepts either: usage.prompt_cache_hit_tokens (DeepSeek's own name) and usage.prompt_tokens_details.cached_tokens (OpenAI's). Cached tokens are a subset of prompt_tokens, not an additional count — the arithmetic is prompt_tokens = uncached + cached, and double-counting them is the classic way to inflate your own cost report.

#!/usr/bin/env python3
"""cache_probe.py — send the same prefix three times and report cache behaviour."""
import hashlib, json, os, time
from openai import OpenAI

client = OpenAI(api_key=os.environ["MODELRY_API_KEY"],
                base_url="https://api.tokenaimodels.com/v1",
                timeout=120.0, max_retries=0)

SYSTEM = (
    "You are a contract analyst. Answer only from the document below.\n"
    "Rules: cite clause numbers; never speculate; if a clause is absent, say so.\n"
)
DOCUMENT = open(os.environ.get("DOC", "contract.txt"), encoding="utf-8").read()  # stable, large

def fingerprint(text: str) -> str:
    return hashlib.sha256(text.encode("utf-8")).hexdigest()[:12]

def call(question: str) -> dict:
    # Stable prefix first, volatile content last. Nothing time-dependent above.
    messages = [
        {"role": "system", "content": SYSTEM + "\n<document>\n" + DOCUMENT + "\n</document>"},
        {"role": "user", "content": question},
    ]
    resp = client.chat.completions.create(
        model="deepseek-chat", messages=messages, max_tokens=300,
    )
    u = resp.usage
    details = getattr(u, "prompt_tokens_details", None)
    cached = (getattr(details, "cached_tokens", 0)
              or getattr(u, "prompt_cache_hit_tokens", 0) or 0)
    prefix = fingerprint(SYSTEM + DOCUMENT)
    print(f"prefix={prefix} prompt={u.prompt_tokens} cached={cached} "
          f"hit={cached / max(u.prompt_tokens, 1):.1%} out={u.completion_tokens}")
    return {"prefix": prefix, "prompt": u.prompt_tokens, "cached": cached}

if __name__ == "__main__":
    for q in ["Which clauses mention liability caps?",
              "Which clauses mention termination for convenience?",
              "List every clause that references a governing law."]:
        call(q)
        time.sleep(1)

Run it with a document of a few thousand tokens or more. First call reports cached=0; the second and third should report most of the prefix as cached. If every line says hit=0.0%, the prefix is changing — and the fingerprint column will tell you whether it is changing because of your content or because of something you did not intend to send.

How a cache decision is actually made

The provider hashes the leading tokens of your request and looks for a previously processed block with the same hash. Exact byte equality, from the first byte onward, until the match ends. Everything after the first difference is a miss, even if it is identical later on — there is no partial credit and no fuzzy matching. This is why the ordering rule is absolute: stable content first, volatile content last. A system prompt, a tool schema and a long document are ideal cache material. A user question, a timestamp, a request id and a random few-shot sample are not, and one of them sitting above your document poisons everything below it.

Cache entries also live upstream, on the provider's side, with the provider's own eviction policy. A gateway cannot promise a hit; it can only preserve your bytes so the provider is *able* to match them. Treat any documented hit rate as an observation about one provider's current behaviour, not as a contract.

Failure 1: a timestamp, uuid or user name at the top of the system prompt

The most common form, and the most expensive, because the prompt is usually large. "Today is 2026-11-17T09:14:22Z. You are a helpful assistant..." guarantees a new prefix on every single request. Move the volatile part to the last message: keep the instruction block immutable and inject the date as a final user or system line. If your framework templates the system prompt with {user_name} on line one, that template is a cache destroyer by design — reorder it.

Failure 2: tool schemas that change bytes without changing meaning

json.dumps preserves insertion order, so two processes that build the same schema from a set of properties will serialise different bytes. Regenerating a Pydantic model can reorder fields or reflow a docstring into a different description string. Both are invisible in review and fatal to the cache. Serialise deterministically — json.dumps(schema, sort_keys=True, separators=(",", ":")) — and snapshot the serialised schema in a test so a reordering fails CI rather than your hit rate.

import json
schema_bytes = json.dumps(TOOLS, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
assert schema_bytes == open("tests/tools.snapshot.json", encoding="utf-8").read(), \
    "tool schema drifted; cache prefix will miss"

Failure 3: measuring the wrong request

Two measurement errors look identical to a broken cache. First, testing with a prompt that is too short: providers cache in blocks and do not publish the minimum block size, so a 200-token system prompt may never be eligible — measure with a realistic payload, not a hello-world. Second, reading the *first* call of a fresh process: the cache is populated by a request, so the first one is always a miss by definition. Benchmark the second and third calls, over a period of minutes rather than milliseconds, and record the fingerprint alongside the hit count so you can attribute a regression to a content change instead of guessing.

What to watch when you speak to a gateway instead of OpenAI

Caching is the one performance feature where the gateway is mostly a *pass-through*, so verify three things rather than assume them. Field normalisation: providers report hits under different names, and a gateway that only forwards prompt_cache_hit_tokens will show 0 to a client that only reads prompt_tokens_details.cached_tokens — read both, as the probe above does. Billing split: the cached rate is applied at settlement from the provider's own counts, so a request whose usage the provider omits is settled from an estimate and your hit-rate dashboard will disagree with the usage statement; flag estimated rows. Prefix preservation: any gateway feature that rewrites your prompt — a system-prompt injection, a safety preamble, a tool-schema normaliser — moves the first differing byte and costs you the whole cache. Ask whether the gateway modifies the request body, and test with the fingerprint before and after.

The five-minute audit

Run three calls with the same prefix and print prompt_tokens, cached and the prefix fingerprint for each. If the fingerprint is identical across all three and cached stays at zero, the break is not in your content — look at whether the gateway rewrites the body before it forwards. If the fingerprint changes between calls, diff the two serialised prefixes and the change will be a timestamp, a dictionary order, or a regenerated schema. Either answer takes minutes to obtain and saves weeks of guessing.

Try the probe with your own document at https://tokenaimodels.com — if the third call does not report a high hit ratio, the prefix is the bug, and the fingerprint printed on every line tells you where it moved.

Modelry operates a platform that serves DeepSeek models behind one HTTP endpoint, with prepaid credits and tax handled by its merchant of record at checkout, and a documented data-retention policy. Start with $0.50 of trial credit: create a key.

All notes