<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/"><channel><title>Prompt-Caching on vishctl</title><link>https://vishctl.dev/tags/prompt-caching/</link><description>Recent content in Prompt-Caching on vishctl</description><generator>Hugo</generator><language>en-us</language><lastBuildDate>Wed, 18 Nov 2026 09:00:00 +0800</lastBuildDate><atom:link href="https://vishctl.dev/tags/prompt-caching/index.xml" rel="self" type="application/rss+xml"/><item><title>Prompt Layout for Cache Hits: Put the Stable Part First</title><link>https://vishctl.dev/posts/prompt-layout-prefix-cache-hits/</link><pubDate>Wed, 18 Nov 2026 09:00:00 +0800</pubDate><guid>https://vishctl.dev/posts/prompt-layout-prefix-cache-hits/</guid><category>prompt-caching</category><category>kv-cache</category><category>inference</category><category>vllm</category><category>rag</category><category>ai-infra</category><description>A simple, diagram-first guide to writing prompts that a prefix cache can reuse: why one early timestamp throws away the whole cache, the right order for prompt parts, how to keep chat history append-only, and a script that measures the difference.</description><content:encoded><![CDATA[<p>Two teams send the same model the same 3,000-token prompt: same instructions, same tools, same documents. One team&rsquo;s requests start answering in 150 ms. The other&rsquo;s take over a second.</p>
<p>The only difference is where they put the timestamp.</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-text" data-lang="text"><span class="line"><span class="cl">Prefix cache    = reuses work only for the part that is identical from the very first token
</span></span><span class="line"><span class="cl">One early change = everything after it is computed again
</span></span></code></pre></div><figure class="mermaid-figure">
  <div class="mermaid">flowchart TD
    subgraph BAD["Timestamp first"]
        direction LR
        A1["Time<br/>changes"] a1@--> A2["System<br/>prompt"]
        A2 a2@--> A3["Tools and<br/>documents"]
        A3 a3@--> A4["Question"]
        A4 a4@--> A5["0% reused"]
    end

    subgraph GOOD["Stable part first"]
        direction LR
        B1["System<br/>prompt"] b1@--> B2["Tools and<br/>documents"]
        B2 b2@--> B3["Time<br/>changes"]
        B3 b3@--> B4["Question"]
        B4 b4@--> B5["99% reused"]
    end

    BAD ~~~ GOOD
    a1@{ animate: true }
    a2@{ animate: true }
    a3@{ animate: true }
    a4@{ animate: true }
    b1@{ animate: true }
    b2@{ animate: true }
    b3@{ animate: true }
    b4@{ animate: true }

    classDef warn fill:#302410,stroke:#fbbf24,color:#fff3cf,stroke-width:2px;
    classDef idle fill:#101e27,stroke:#324950,color:#8aa0a8;
    classDef gpu fill:#173f59,stroke:#22d3ee,color:#ecfeff,stroke-width:2px;
    classDef input fill:#13264a,stroke:#38bdf8,color:#e6f6ff,stroke-width:2px;
    class A1,B3,A5 warn;
    class A2,A3,A4 idle;
    class B1,B2,B5 gpu;
    class B4 input;</div>
  <figcaption>Top: a timestamp at the start changes token one, so nothing can be reused. Bottom: the same content with the timestamp at the end reuses almost everything.</figcaption>
</figure>

<p>Most posts about prompt caching are written for platform teams. This one is for whoever builds the prompt.</p>
<p>The cache is already there in vLLM, SGLang, and most hosted APIs. Whether you benefit is decided by the order of your prompt.</p>
<h2 id="why-only-the-prefix-counts">Why only the prefix counts</h2>
<p>When a model reads a prompt, the state it builds for each token depends on <strong>every token before it</strong>. That state is the <a href="https://vishctl.dev/posts/llm-basics-visual-guide/#5-context-is-the-input-kv-cache-saves-work">KV cache</a>.</p>
<p>So a saved state for token 500 is only valid if tokens 1 to 499 are exactly the same as last time. Change token 3, and the saved state for tokens 4 onward is no longer correct. The server has to throw it away.</p>
<p>That gives one rule that explains everything else in this post:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-text" data-lang="text"><span class="line"><span class="cl">A cache hit ends at the first token that differs.
</span></span></code></pre></div><p>It does not matter that the other 2,990 tokens are identical. They come after the change.</p>
<h2 id="a-four-request-walkthrough">A four-request walkthrough</h2>
<p>Take one prompt of about 2,900 tokens and send it four times, with a new question and a new timestamp each time.</p>
<div class="table-scroll">
  <table>
    <thead>
        <tr>
            <th scope="col">Request</th>
            <th scope="col">Timestamp first: tokens reused</th>
            <th scope="col">Stable part first: tokens reused</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>1</td>
            <td>0 (nothing cached yet)</td>
            <td>0 (nothing cached yet)</td>
        </tr>
        <tr>
            <td>2</td>
            <td>0</td>
            <td>2,896</td>
        </tr>
        <tr>
            <td>3</td>
            <td>0</td>
            <td>2,896</td>
        </tr>
        <tr>
            <td>4</td>
            <td>0</td>
            <td>2,896</td>
        </tr>
    </tbody>
  </table>
</div>
<p>With the timestamp first, request four costs exactly as much as request one. The cache is full of state that never matches.</p>
<p>With the stable part first, every request after the first only has to read about 26 new tokens. That is the difference in <a href="https://vishctl.dev/posts/llm-inference-metrics-ttft-tpot-throughput-goodput/#1-ttft-time-to-first-token">time to first token</a> from the opening example.</p>
<h2 id="the-right-order-slowest-changing-first">The right order: slowest-changing first</h2>
<p>Sort the parts of your prompt by how often they change. The part that changes least goes first.</p>
<figure class="mermaid-figure">
  <div class="mermaid">flowchart TD
    L1["System prompt<br/>changes on deploy"] o1@--> L2["Tool definitions<br/>changes on deploy"]
    L2 o2@--> L3["Examples<br/>changes rarely"]
    L3 o3@--> L4["Documents<br/>changes per topic"]
    L4 o4@--> L5["Chat history<br/>grows each turn"]
    L5 o5@--> L6["Question, time, IDs<br/>changes every request"]

    o1@{ animate: true }
    o2@{ animate: true }
    o3@{ animate: true }
    o4@{ animate: true }
    o5@{ animate: true }

    classDef gpu fill:#173f59,stroke:#22d3ee,color:#ecfeff,stroke-width:2px;
    classDef tree fill:#281d48,stroke:#a78bfa,color:#f1edff,stroke-width:2px;
    classDef input fill:#13264a,stroke:#38bdf8,color:#e6f6ff,stroke-width:2px;
    classDef warn fill:#302410,stroke:#fbbf24,color:#fff3cf,stroke-width:2px;
    class L1,L2,L3 gpu;
    class L4 tree;
    class L5 input;
    class L6 warn;</div>
  <figcaption>Order prompt parts from never changing at the top to always changing at the bottom. The cache can reuse everything above the first part that changed.</figcaption>
</figure>

<div class="table-scroll">
  <table>
    <thead>
        <tr>
            <th scope="col">Position</th>
            <th scope="col">Part</th>
            <th scope="col">Shared by</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>1</td>
            <td>System prompt</td>
            <td>Every request to this app</td>
        </tr>
        <tr>
            <td>2</td>
            <td>Tool definitions</td>
            <td>Every request to this app</td>
        </tr>
        <tr>
            <td>3</td>
            <td>Few-shot examples</td>
            <td>Every request to this app</td>
        </tr>
        <tr>
            <td>4</td>
            <td>Retrieved documents</td>
            <td>Requests about the same topic</td>
        </tr>
        <tr>
            <td>5</td>
            <td>Conversation history</td>
            <td>Later turns of the same chat</td>
        </tr>
        <tr>
            <td>6</td>
            <td>New question, timestamp, request ID, user name</td>
            <td>Nobody</td>
        </tr>
    </tbody>
  </table>
</div>
<p>The third column is the real point. Parts 1 to 3 are shared by <strong>all users</strong>, so they are cached once and reused by everyone. Put a user name above them, and each user gets a private copy of the whole thing.</p>
<h2 id="six-things-that-quietly-break-the-cache">Six things that quietly break the cache</h2>
<p>These are the mistakes I would check for first. None of them looks like a bug.</p>
<div class="table-scroll">
  <table>
    <thead>
        <tr>
            <th scope="col">Mistake</th>
            <th scope="col">Why it breaks the prefix</th>
            <th scope="col">Fix</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Timestamp in the system prompt</td>
            <td>Token one changes every second</td>
            <td>Move it to the end, or use the date without the time</td>
        </tr>
        <tr>
            <td>User name or ID near the top</td>
            <td>Every user has a different prefix</td>
            <td>Put per-user details after the shared parts</td>
        </tr>
        <tr>
            <td>Tools listed in a different order</td>
            <td>Same tools, different tokens</td>
            <td>Sort tools by name before sending</td>
        </tr>
        <tr>
            <td>JSON with unstable key order</td>
            <td><code>{&quot;a&quot;:1,&quot;b&quot;:2}</code> is not <code>{&quot;b&quot;:2,&quot;a&quot;:1}</code></td>
            <td>Serialize with sorted keys</td>
        </tr>
        <tr>
            <td>Documents in relevance order</td>
            <td>Same documents, new order each query</td>
            <td>Keep a stable order, such as by document ID</td>
        </tr>
        <tr>
            <td>Rewriting old chat turns</td>
            <td>Editing turn 2 invalidates turns 3 onward</td>
            <td>Only append; never edit earlier messages</td>
        </tr>
    </tbody>
  </table>
</div>
<p>The JSON row catches many agent frameworks. If tool definitions are built from a dictionary and the language does not guarantee key order, two identical requests can produce two different prompts.</p>
<h3 id="a-timestamp-does-not-have-to-go-last">A timestamp does not have to go last</h3>
<p>Sometimes the model needs the date. You have two cache-friendly options:</p>
<ul>
<li><strong>Put it at the end</strong>, next to the question.</li>
<li><strong>Make it coarse.</strong> <code>2026-10-13</code> changes once a day. <code>2026-10-13T02:45:17</code> changes every second.</li>
</ul>
<p>A date that changes once a day costs one cache miss per day. That is fine.</p>
<h2 id="chat-history-append-never-rewrite">Chat history: append, never rewrite</h2>
<p>A conversation is the best case for a prefix cache, because every turn starts with the entire previous turn.</p>
<figure class="mermaid-figure">
  <div class="mermaid">flowchart TD
    subgraph APPEND["Append only"]
        direction LR
        P1["Turn 1<br/>read 2,000"] p1@--> P2["Turn 2<br/>reuse 2,000<br/>read 300"]
        P2 p2@--> P3["Turn 3<br/>reuse 2,300<br/>read 300"]
    end

    subgraph REWRITE["Summarize every turn"]
        direction LR
        R1["Turn 1<br/>read 2,000"] r1@--> R2["Turn 2<br/>new summary<br/>read 1,500"]
        R2 r2@--> R3["Turn 3<br/>new summary<br/>read 1,600"]
    end

    APPEND ~~~ REWRITE
    p1@{ animate: true }
    p2@{ animate: true }
    r1@{ animate: true }
    r2@{ animate: true }

    classDef input fill:#13264a,stroke:#38bdf8,color:#e6f6ff,stroke-width:2px;
    classDef gpu fill:#173f59,stroke:#22d3ee,color:#ecfeff,stroke-width:2px;
    classDef warn fill:#302410,stroke:#fbbf24,color:#fff3cf,stroke-width:2px;
    class P1,R1 input;
    class P2,P3 gpu;
    class R2,R3 warn;</div>
  <figcaption>Top: when history only grows, each turn reuses everything before it. Bottom: when history is rewritten into a summary, the prefix changes and the turn starts from zero.</figcaption>
</figure>

<p>Summarizing history feels efficient, because the prompt gets shorter. But a shorter prompt that misses the cache can cost more than a longer one that hits it.</p>
<p>In the diagram, the summarized chat reads 1,500 fresh tokens on turn 2. The append-only chat reads 300.</p>
<p>You do have to trim eventually, when the context window fills up. Do it rarely and in big steps:</p>
<ul>
<li><strong>Summarize once every many turns</strong>, not every turn. You pay one cache miss, then get hits again.</li>
<li><strong>Trim from a fixed point.</strong> Dropping the oldest messages changes the prefix, so drop a large chunk at once instead of one message per turn.</li>
<li><strong>Keep the system prompt and tools untouched</strong> when you trim. They stay cached for everyone.</li>
</ul>
<h2 id="retrieved-documents-the-hard-case">Retrieved documents: the hard case</h2>
<p>RAG prompts are where the simple rule runs out. The same documents come back in a different order, ranked by relevance to each new question.</p>
<div class="table-scroll">
  <table>
    <thead>
        <tr>
            <th scope="col">Document order</th>
            <th scope="col">What gets reused</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Same documents, same order</td>
            <td>Everything up to the question</td>
        </tr>
        <tr>
            <td>Same documents, different order</td>
            <td>Only the system prompt and tools</td>
        </tr>
        <tr>
            <td>Different documents</td>
            <td>Only the system prompt and tools</td>
        </tr>
    </tbody>
  </table>
</div>
<p>If your retriever often returns the same set, sorting by a stable key (document ID, or source and page number) turns the second row into the first.</p>
<p>There is a real trade-off. Some models pay more attention to documents near the start or end of the context, so relevance order can help answer quality. Measure both before deciding.</p>
<p>For reuse that survives reordering, you need something beyond a prefix cache. That is what CacheBlend does in <a href="https://vishctl.dev/posts/why-lmcache-is-needed/#what-about-rag-documents-in-a-different-order">LMCache</a>.</p>
<h2 id="try-it-measure-the-layouts">Try it: measure the layouts</h2>
<p>This script builds the same prompt in three layouts and counts how many tokens a prefix cache could reuse. It uses only the Python standard library.</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="ch">#!/usr/bin/env python3</span>
</span></span><span class="line"><span class="cl"><span class="s2">&#34;&#34;&#34;prefix_share.py: how much of a prompt can a prefix cache reuse?&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="n">BLOCK</span> <span class="o">=</span> <span class="mi">16</span>  <span class="c1"># vLLM caches whole 16-token blocks</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">part</span><span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="n">size</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;A stand-in for `size` tokens of fixed text.&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="k">return</span> <span class="p">[</span><span class="sa">f</span><span class="s2">&#34;</span><span class="si">{</span><span class="n">name</span><span class="si">}{</span><span class="n">i</span><span class="si">}</span><span class="s2">&#34;</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">size</span><span class="p">)]</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="n">SYSTEM</span><span class="p">,</span> <span class="n">TOOLS</span> <span class="o">=</span> <span class="n">part</span><span class="p">(</span><span class="s2">&#34;sys&#34;</span><span class="p">,</span> <span class="mi">600</span><span class="p">),</span> <span class="n">part</span><span class="p">(</span><span class="s2">&#34;tool&#34;</span><span class="p">,</span> <span class="mi">300</span><span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="n">DOC_A</span><span class="p">,</span> <span class="n">DOC_B</span> <span class="o">=</span> <span class="n">part</span><span class="p">(</span><span class="s2">&#34;docA&#34;</span><span class="p">,</span> <span class="mi">1000</span><span class="p">),</span> <span class="n">part</span><span class="p">(</span><span class="s2">&#34;docB&#34;</span><span class="p">,</span> <span class="mi">1000</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">reusable</span><span class="p">(</span><span class="n">previous</span><span class="p">,</span> <span class="n">current</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="s2">&#34;&#34;&#34;Tokens at the start of `current` that match `previous`, in whole blocks.&#34;&#34;&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="n">same</span> <span class="o">=</span> <span class="mi">0</span>
</span></span><span class="line"><span class="cl">    <span class="k">for</span> <span class="n">a</span><span class="p">,</span> <span class="n">b</span> <span class="ow">in</span> <span class="nb">zip</span><span class="p">(</span><span class="n">previous</span><span class="p">,</span> <span class="n">current</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">        <span class="k">if</span> <span class="n">a</span> <span class="o">!=</span> <span class="n">b</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">            <span class="k">break</span>
</span></span><span class="line"><span class="cl">        <span class="n">same</span> <span class="o">+=</span> <span class="mi">1</span>
</span></span><span class="line"><span class="cl">    <span class="k">return</span> <span class="n">same</span> <span class="o">//</span> <span class="n">BLOCK</span> <span class="o">*</span> <span class="n">BLOCK</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">request</span><span class="p">(</span><span class="n">layout</span><span class="p">,</span> <span class="n">n</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="n">stamp</span> <span class="o">=</span> <span class="p">[</span><span class="sa">f</span><span class="s2">&#34;time-</span><span class="si">{</span><span class="n">n</span><span class="si">}</span><span class="s2">&#34;</span><span class="p">,</span> <span class="sa">f</span><span class="s2">&#34;request-id-</span><span class="si">{</span><span class="n">n</span><span class="si">}</span><span class="s2">&#34;</span><span class="p">]</span>
</span></span><span class="line"><span class="cl">    <span class="n">question</span> <span class="o">=</span> <span class="n">part</span><span class="p">(</span><span class="sa">f</span><span class="s2">&#34;question</span><span class="si">{</span><span class="n">n</span><span class="si">}</span><span class="s2">-&#34;</span><span class="p">,</span> <span class="mi">20</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="n">docs</span> <span class="o">=</span> <span class="n">DOC_A</span> <span class="o">+</span> <span class="n">DOC_B</span>
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="n">layout</span> <span class="o">==</span> <span class="s2">&#34;timestamp first&#34;</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">        <span class="k">return</span> <span class="n">stamp</span> <span class="o">+</span> <span class="n">SYSTEM</span> <span class="o">+</span> <span class="n">TOOLS</span> <span class="o">+</span> <span class="n">docs</span> <span class="o">+</span> <span class="n">question</span>
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="n">layout</span> <span class="o">==</span> <span class="s2">&#34;documents reshuffled&#34;</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">        <span class="n">docs</span> <span class="o">=</span> <span class="n">DOC_A</span> <span class="o">+</span> <span class="n">DOC_B</span> <span class="k">if</span> <span class="n">n</span> <span class="o">%</span> <span class="mi">2</span> <span class="k">else</span> <span class="n">DOC_B</span> <span class="o">+</span> <span class="n">DOC_A</span>
</span></span><span class="line"><span class="cl">        <span class="k">return</span> <span class="n">SYSTEM</span> <span class="o">+</span> <span class="n">TOOLS</span> <span class="o">+</span> <span class="n">docs</span> <span class="o">+</span> <span class="n">stamp</span> <span class="o">+</span> <span class="n">question</span>
</span></span><span class="line"><span class="cl">    <span class="k">return</span> <span class="n">SYSTEM</span> <span class="o">+</span> <span class="n">TOOLS</span> <span class="o">+</span> <span class="n">docs</span> <span class="o">+</span> <span class="n">stamp</span> <span class="o">+</span> <span class="n">question</span>   <span class="c1"># stable first</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="k">for</span> <span class="n">layout</span> <span class="ow">in</span> <span class="p">(</span><span class="s2">&#34;timestamp first&#34;</span><span class="p">,</span> <span class="s2">&#34;documents reshuffled&#34;</span><span class="p">,</span> <span class="s2">&#34;stable first&#34;</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="n">prompts</span> <span class="o">=</span> <span class="p">[</span><span class="n">request</span><span class="p">(</span><span class="n">layout</span><span class="p">,</span> <span class="n">n</span><span class="p">)</span> <span class="k">for</span> <span class="n">n</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">5</span><span class="p">)]</span>
</span></span><span class="line"><span class="cl">    <span class="n">total</span> <span class="o">=</span> <span class="nb">sum</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">p</span><span class="p">)</span> <span class="k">for</span> <span class="n">p</span> <span class="ow">in</span> <span class="n">prompts</span><span class="p">[</span><span class="mi">1</span><span class="p">:])</span>
</span></span><span class="line"><span class="cl">    <span class="n">hit</span> <span class="o">=</span> <span class="nb">sum</span><span class="p">(</span><span class="n">reusable</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">)</span> <span class="k">for</span> <span class="n">a</span><span class="p">,</span> <span class="n">b</span> <span class="ow">in</span> <span class="nb">zip</span><span class="p">(</span><span class="n">prompts</span><span class="p">,</span> <span class="n">prompts</span><span class="p">[</span><span class="mi">1</span><span class="p">:]))</span>
</span></span><span class="line"><span class="cl">    <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s2">&#34;</span><span class="si">{</span><span class="n">layout</span><span class="si">:</span><span class="s2">21</span><span class="si">}</span><span class="s2"> </span><span class="si">{</span><span class="n">hit</span><span class="si">:</span><span class="s2">5,</span><span class="si">}</span><span class="s2"> of </span><span class="si">{</span><span class="n">total</span><span class="si">:</span><span class="s2">,</span><span class="si">}</span><span class="s2"> prompt tokens reused  (</span><span class="si">{</span><span class="mi">100</span> <span class="o">*</span> <span class="n">hit</span> <span class="o">/</span> <span class="n">total</span><span class="si">:</span><span class="s2">4.1f</span><span class="si">}</span><span class="s2">%)&#34;</span><span class="p">)</span>
</span></span></code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">python3 prefix_share.py
</span></span></code></pre></div><p>The output:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-text" data-lang="text"><span class="line"><span class="cl">timestamp first           0 of 8,766 prompt tokens reused  ( 0.0%)
</span></span><span class="line"><span class="cl">documents reshuffled  2,688 of 8,766 prompt tokens reused  (30.7%)
</span></span><span class="line"><span class="cl">stable first          8,688 of 8,766 prompt tokens reused  (99.1%)
</span></span></code></pre></div><p>Same content in all three. The middle row is the RAG case: the system prompt and tools are reused, and the reshuffled documents are not.</p>
<p>The <code>BLOCK = 16</code> line reflects how vLLM matches prefixes: in whole blocks of 16 tokens, as I described in <a href="https://vishctl.dev/posts/sglang-vs-vllm/#1-kv-cache-reuse-block-hash-tables-vs-radixattention">SGLang vs. vLLM</a>. The last partial block is always recomputed, which is why the best case is 99% and not 100%.</p>
<h2 id="check-it-on-a-real-server">Check it on a real server</h2>
<p>A simulation shows the idea. The server shows the truth.</p>
<p><strong>Time it.</strong> Send the same long prompt twice with the timing script from my <a href="https://vishctl.dev/posts/llm-inference-metrics-ttft-tpot-throughput-goodput/#try-it-measure-ttft-and-tpot-yourself">inference metrics guide</a>. If the second TTFT is much lower, the prefix was reused. Then move a timestamp to the front and watch the gain disappear.</p>
<p><strong>Read the counters.</strong> vLLM counts how many prompt tokens it looked up and how many it found:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">curl -s http://localhost:8000/metrics <span class="p">|</span> grep prefix_cache
</span></span></code></pre></div><p>The hit rate is hits divided by queries:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-text" data-lang="text"><span class="line"><span class="cl">sum(rate(vllm:prefix_cache_hits_total[5m])) / sum(rate(vllm:prefix_cache_queries_total[5m]))
</span></span></code></pre></div><p>That is panel 6 in my <a href="https://vishctl.dev/posts/monitoring-vllm-prometheus-dashboard-alerts/#6-prefix-cache-hit-rate">vLLM monitoring guide</a>. If it drops right after a release, someone changed the prompt template.</p>
<p>Hosted APIs follow the same prefix rule. Some cache automatically once a prompt is long enough, and some ask you to mark where the reusable part ends.</p>
<p>Either way, their usage report shows how many input tokens were served from cache, and cached tokens are usually billed at a discount. The layout advice here applies unchanged.</p>
<h2 id="when-layout-is-not-enough">When layout is not enough</h2>
<p>Good layout makes hits possible. Two other things decide whether they happen.</p>
<div class="table-scroll">
  <table>
    <thead>
        <tr>
            <th scope="col">Problem</th>
            <th scope="col">Symptom</th>
            <th scope="col">Fix</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Requests spread over many replicas</td>
            <td>Hits on one Pod, misses on the next</td>
            <td>Cache-aware routing with <a href="https://vishctl.dev/posts/llm-d-kubernetes-inference-routing/">llm-d</a></td>
        </tr>
        <tr>
            <td>Cache evicted under memory pressure</td>
            <td>Hit rate falls when traffic rises</td>
            <td>More KV cache room, or offload with <a href="https://vishctl.dev/posts/why-lmcache-is-needed/">LMCache</a></td>
        </tr>
    </tbody>
  </table>
</div>
<p>Fix the layout first. It is free, it needs no new infrastructure, and the other two fixes work better once it is done.</p>
<h2 id="cheat-sheet">Cheat sheet</h2>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-text" data-lang="text"><span class="line"><span class="cl">Prefix cache        = reuses saved state for the part of a prompt identical from token one
</span></span><span class="line"><span class="cl">First difference    = where the cache hit ends; everything after is recomputed
</span></span><span class="line"><span class="cl">Stable-first layout = order parts by how rarely they change: system, tools, examples, docs, chat, question
</span></span><span class="line"><span class="cl">Shared prefix       = the parts every user sends; cached once and reused by all
</span></span><span class="line"><span class="cl">Timestamp rule      = put it last, or make it coarse (a date, not a time)
</span></span><span class="line"><span class="cl">Deterministic JSON  = sort keys and tool lists so identical content gives identical tokens
</span></span><span class="line"><span class="cl">Append-only history = add new turns at the end; never edit or summarize earlier ones each turn
</span></span><span class="line"><span class="cl">Stable document order = sort retrieved documents by ID so the same set gives the same prefix
</span></span><span class="line"><span class="cl">16-token blocks     = vLLM matches prefixes in whole blocks, so the last partial block is redone
</span></span><span class="line"><span class="cl">Hit rate            = cached prompt tokens / all prompt tokens
</span></span><span class="line"><span class="cl">Rule of thumb       = anything that changes per request goes at the end
</span></span></code></pre></div><p>For what the cache stores and why it saves time, read <a href="https://vishctl.dev/posts/why-lmcache-is-needed/">Why LMCache Exists</a>. For how much memory all that cached state takes, read <a href="https://vishctl.dev/posts/llm-gpu-memory-sizing-weights-kv-cache/">How Much GPU Memory Does an LLM Need?</a>.</p>
]]></content:encoded></item></channel></rss>