# Your Prompt Layout Is Defeating the Prefix Cache

> Why a timestamp or reshuffled tool list near the top of a prompt wipes out prefix cache hits, and how to lay out, test and monitor prompts to keep them.

Published 2026-11-06 by Sovont. Tags: LLM Engineering, Inference & Cost.
Web page: https://sovont.com/blog/your-prompt-layout-is-defeating-the-prefix-cache/

Prefix caching lets an inference server skip recomputing the parts of a prompt it has already seen. That cuts time-to-first-token and, on hosted APIs that discount cached input, your bill. Most teams turn it on, assume it works, and never check the hit rate. Often it's close to zero, because the prompt is laid out so that every request looks new from the first few tokens.

## Why one changed token throws away the cache

During prefill, the model computes key/value tensors for every input token. A prefix cache stores those tensors and reuses them when a new request starts with *exactly* the same token sequence. It can't partially match, skip a token, or fill in a gap. Attention means each token's KV state depends on everything before it, so the cache is only valid up to the first token that differs.

That makes position the whole game. A per-request value at token 40 of a 6,000-token prompt invalidates 5,960 tokens of reusable work. Put the same value at the end and you lose almost nothing.

This applies whether you self-host (vLLM's automatic prefix caching, SGLang's radix cache) or call a hosted API. Some providers cache automatically. Others make you mark cache breakpoints explicitly. All of them match on exact prefixes.

## The usual suspects

These break the prefix without anyone noticing:

| Breaker | Why it happens | Fix |
|---|---|---|
| Timestamp in the system prompt | "Current time: 14:32:07" added for date-aware answers | Move it to the end, or round to the day |
| User name or account ID up top | Personalization added to the first line | Put it in the final user turn |
| Tool definitions in varying order | Built from a set or dict, or filtered per request | Sort deterministically and keep the full list stable |
| Non-deterministic JSON | Schemas serialized without sorted keys | Serialize with sorted keys and fixed whitespace |
| Randomly sampled few-shot examples | Someone wanted variety | Fix the set, or pick from a small number of fixed variants |
| Retrieved chunks before instructions | RAG context placed early "so the model sees it" | Instructions and tools first, retrieved context after |
| Sliding-window history | Oldest turns dropped one at a time, shifting everything | Truncate or summarize in blocks so the prefix changes rarely |

The system prompt is usually where this starts. As it grows, people splice dynamic snippets into the middle. [The System Prompt That Grew Without Anyone Noticing](https://sovont.com/blog/the-system-prompt-that-grew-without-anyone-noticing/) covers how that sprawl happens.

## Order the prompt from most stable to least stable

Treat the prompt as layers sorted by how often they change:

1. **Static for every request:** system instructions, policies, output schema, tool definitions, fixed few-shot examples.
2. **Static per tenant or per product surface:** tenant-specific instructions, a glossary.
3. **Static per session:** conversation summary, earlier turns.
4. **Per request:** retrieved documents, current date, user metadata, the new user message.

Anything that varies per request goes last, even if it feels like "context" that belongs near the top. Models handle a date or user name in the final turn fine. If you want to verify that for your task, run your eval suite on both layouts and compare scores before you ship.

This is not the same as [semantic caching](https://sovont.com/blog/semantic-caching-the-missing-layer-in-your-rag-architecture/). A semantic cache skips the model call for similar questions. A prefix cache makes every call cheaper, including ones that are never repeated. You want both.

## Test it, measure it, keep it from regressing

Layouts regress silently. One innocent commit that adds a request ID to the system prompt erases the gains, and nothing errors. Add a test that renders two unrelated requests and checks that they share the full static prefix:

```python
def test_static_prefix_is_shared():
    a = render(build_messages(user="u1", query="reset my password", now=T1))
    b = render(build_messages(user="u2", query="export my invoices", now=T2))
    shared = len(os.path.commonprefix([a, b]))
    assert shared >= len(render(static_layers()))
```

In production, track the share of input tokens served from cache, per route and per prompt version. Hosted APIs report cached input tokens in the response's usage data. vLLM exposes prefix cache counters on its Prometheus endpoint. Warning signs:

- The cached-token ratio drops right after a prompt or tool change.
- Time-to-first-token rises with no change in traffic or prompt length.
- The ratio is high in staging (one tester, one tenant) and low in production.

If you self-host behind a load balancer, check routing too. Each replica keeps its own cache, so round-robin spreads identical prefixes across replicas and every replica warms up separately. Session- or prefix-aware routing at your [gateway](https://sovont.com/blog/why-your-llm-api-gateway-is-critical/) keeps related requests on the same replica.

## What it costs you

None of this is free, so weigh the trade-offs:

- **Freshness vs. hits.** Rounding the date to the day is fine for most assistants. Agents that reason about minutes need the exact time in the last turn.
- **Cache memory vs. batch size.** On your own GPUs, cached prefixes take KV memory that could hold active sequences. Under heavy load the server evicts them. Watch eviction alongside hit rate.
- **Affinity vs. balance.** Sticky routing can create hot replicas. Cap how much load one replica takes per prefix.
- **Hosted cache lifetimes.** Hosted caches expire after a period of inactivity, and some providers charge to write them. Low-traffic routes may never get a hit. Check your provider's current terms before planning around savings.

For most teams the fix is an afternoon of reordering, plus one test and one dashboard panel. Then you get the prefill savings you assumed you already had.

If you run your own inference fleet and want to know how much GPU time goes to recomputing the same tokens, the [GPU Spend & Capacity Audit](https://sovont.com/#audit) is built to find it.
