All posts
    Blog3 min read

    Four Ways Our Agent Broke Its Own Cache

    Sammy Deprez

    Part 3 of 5. Start with part 1 if you missed it.

    So the provider caches fine, and our app changes the prompt between calls. But where? You could read through all the code and reason about it. We did something much more boring, and much more effective.

    Don't reason, record

    We ran the real agent runtime against a fake HTTP transport. It returns scripted tool calls and stores every request the agent sends. Then we compare each request with the one before. No tokens spent, and the answer is definitive.

    In Python, httpx makes this easy with a MockTransport:

    import httpx, json
    
    sent = []
    
    def handler(request: httpx.Request) -> httpx.Response:
        sent.append(json.loads(request.content))
        return httpx.Response(200, json=next(scripted_responses))
    
    http_client = httpx.Client(transport=httpx.MockTransport(handler))
    # give http_client to your LLM client and run a scripted conversation
    

    And a simple diff that tells you where the prefix broke:

    def first_change(prev: dict, curr: dict) -> str | None:
        if prev.get("tools") != curr.get("tools"):
            return "tools"
        if prev.get("system") != curr.get("system"):
            return "system prompt"
        for i, (a, b) in enumerate(zip(prev["messages"], curr["messages"])):
            if a != b:
                return f"message {i}"
        return None  # only appended, so a cache hit
    

    On our baseline, every single miss could be traced to a named change. Every call with a change read 0 from cache, every call that only appended was a hit.

    The four culprits

    None of these were ever designed as a cache problem.

    1. A tool list that kept changing. The agent searches for tools and loads them on the fly. A capped "most recent tools" list evicted the oldest on almost every search: the list changed on 15 of 20 calls in one turn. It could even evict the tool the model had just asked for.

    2. Memories in the system prompt. Memories are picked by similarity to the question, so they change every turn. In the system prompt, that means the entire history behind it misses. Every turn.

    3. A sliding image window. Only the last few images went in full, older ones became a short note. But swapping an image rewrites an early message, and everything cached after it.

    4. Summarisation that thrashed. If the tail it kept was itself over the trigger, summarisation fired every other call.

    Where do per-turn things go then?

    Our first instinct for the memories: move them to the end of the system prompt. We tested that on all nine models we run. Cache share on the call right after a change:

    Where the memories goClaudeGPTGemini
    End of the system prompt0%0%0%
    Latest user message only~58%~55%unreliable
    Each turn's own message, kept in history99%99%best, still unreliable

    Zero, on every model. The end of the system prompt is still before the whole conversation.

    What works: attach them to the turn they belong to, and leave them there.

    # Before: changes every turn, breaks everything after it
    system = BASE_PROMPT + render(memories)
    
    # After: system prompt stays byte-stable, memories travel with their turn
    messages.append({
        "role": "user",
        "content": f"<memories>{render(memories)}</memories>\n\n{question}",
    })
    

    Same for tools: appending, evicting or reordering all cost one full miss on both Claude and GPT. So the rule became: append only, never evict, never reorder. We use a cap of 50.

    PS: Gemini's implicit cache is best-effort. Even identical requests sometimes missed, so one Gemini miss on its own tells you nothing.

    Result of this first fix: $7.35 → $5.05 per run, hit rate from 45% to 64%. Nice, but the context was still huge.

    Next (8 December): Shrinking the Context Without Shooting Yourself in the Foot

    Documentation

    • AI Agents
    • Prompt Caching
    • LLMOps

    Keep reading.

    New notes, straight to your inbox.

    One email when something new ships. No spam, unsubscribe anytime.

    Cookie Preferences

    Essential cookies keep the site working. With "Accept all" we also use Google Analytics and the LinkedIn Insight Tag to see how the site is used and which kinds of companies visit. Nothing is loaded unless you accept. Learn more in our Privacy Policy