---
title: "KV cache"
description: "Every KV-cache strategy in opod — sizing from plan.workload, 8-bit precision, prefix reuse, KV-aware routing, cache isolation and offload tiers — with formulas, knobs, proofs and costs."
url: "https://opod.io/docs/control-plane-endpoints/kv-cache/"
markdown_url: "https://opod.io/docs/control-plane-endpoints/kv-cache.md"
section: "Endpoints"
last_updated: "2026-10-30"
---

# KV cache

> Every KV-cache strategy in opod — sizing from plan.workload, 8-bit precision, prefix reuse, KV-aware routing, cache isolation and offload tiers — with formulas, knobs, proofs and costs.

A worker's GPU memory holds the model's weights and its **KV cache**: the attention keys and values of every token the engine is working on. The KV cache decides how many requests a worker serves at once, how long a request may be, and how much of a repeated prompt is free.

opod has six strategies for it. Each one below says what it solves, how it works, the knobs, where it is proven, what it costs and how it fails.

> **Note**
>
> This page describes `0.3.0`. The published `0.2.1` has vLLM's CPU tier and the routing knobs; sizing from `plan.workload`, cache isolation, the other engines' tiers, the `disk` and `auto` tiers and the KV advice routes came after it. See [Releases](https://opod.io/docs/get-started/releases/).

| Strategy                | Where it is set                                       | Changes take                         |
| ----------------------- | ----------------------------------------------------- | ------------------------------------ |
| [Sizing](#sizing)       | `plan.workload`, `flags.ctx`, `flags.max_model_len`   | a rollout                            |
| [Precision](#precision) | `flags.kv_cache_dtype`, `flags.kv_cache_type`         | a rollout                            |
| [Prefix](#prefix)       | your prompts; nothing to switch on                    | nothing                              |
| [Routing](#routing)     | the endpoint policy (`routing.*`) and `plan.kvEvents` | policy: live · `kvEvents`: a rollout |
| [Isolation](#isolation) | `plan.routing.cacheIsolation`                         | live, no pod restart                 |
| [Tiers](#tiers)         | `workers[].kvOffload`, `shardGroups[].kvOffload`      | a rollout                            |

In 0.3.0, each of these has a control. The create form sets sizing, precision, events, isolation and tiers. `opodcp endpoint kv` changes them on a running endpoint, and `opodcp endpoint policy` changes the routing knobs ([CLI](https://opod.io/docs/control-plane-reference/cli/#endpoint-kv--policy--expose)). For example, `opodcp endpoint kv --dtype fp8 --events on chat`.

Try each strategy below before you read its section. Every tab uses the planner's own arithmetic and rules.

**Figure: KV-cache strategies.** One tab per strategy: workers needed when each card holds weights and its share of the KV pool; requests that fit one 80 GB card's KV room at 16-bit and 8-bit KV; prefix reuse across three requests; four workers' routing scores and the worker picked; and the memory tiers where requests found their prefix blocks. The interactive figure is on the web page: <https://opod.io/docs/control-plane-endpoints/kv-cache/>

## In short

The KV cache is the GPU memory a worker uses for the requests it is serving. Its size decides how many requests run at once and how long each may be. Tell the planner your traffic in `plan.workload` and it sizes the cache for you and shows the arithmetic. The other strategies on this page reuse cache that is already computed, or keep more of it in host memory.

## When you need it

- Requests queue or get preempted at the peak: size from `workload`, or use an 8-bit KV cache.
- An engine starts with a shorter context than you asked for: the cache does not fit beside the weights.
- Many requests share a long prefix (RAG, agents, a long system prompt): keep the prefix stable, route by prefix, add a tier.
- Several teams share one endpoint and must not share cached prompts: set `cacheIsolation`.

## Do it

1. **Describe the traffic**

   Add a `workload` block to the plan, or pick a preset on the create form:

   ```yaml
   workload: { inputTokens: 2000, outputTokens: 500, peakConcurrency: 80 }
   ```

2. **Read the arithmetic in Preview**

   Preview the create body (or the plan) and read the `workload` and `context` advisories:

   ```bash
   curl -s -H "$H" -H 'Content-Type: application/json' -X POST https://cp.example.com/api/v1/endpoints/preview \
     -d @chat.json | jq '.advisories[] | select(.kind=="workload" or .kind=="context")'
   ```

   They state one request's memory, the endpoint's pool, the requests per worker and, when the workers cannot hold the peak, the `autoscale.floor` to set.

3. **Apply it**

   Create the endpoint, or post the plan as a verified rollout (`POST /api/v1/endpoints/{id}/rollouts`). Sizing is pinned into engine flags, so it rides a rollout.

4. **Compare with what was measured, after a week**

   ```bash
   curl -s -H "$H" https://cp.example.com/api/v1/endpoints/<id>/kv/advice | jq .
   ```

   The answer is one of `insufficient`, `oversized`, `undersized`, `fits` or `unknown`, with one suggested edit.

## Check it worked

```bash
curl -s -H "$H" https://cp.example.com/api/v1/endpoints/<id>/kv | jq .
```

A good answer shows, per worker, the planner's `planned` figure beside the engine's own `load` sample, and the KV in use stays below the pool at the peak. In the console, the endpoint page's KV card shows the same verdict and **Review the suggested size**.

## If it fails

| Symptom or code                                       | Cause                                                                           | Fix                                                                          |
| ----------------------------------------------------- | ------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- |
| `E-FIT`                                               | one request of the workload's length does not fit beside the weights            | a shorter context, an 8-bit KV cache, or a bigger card                       |
| Preview says the model is not sized                   | the catalog records too little architecture for the model                       | pin `flags.ctx` or `flags.max_model_len` yourself                            |
| `400`: the workload is longer than the model's window | `maxContext` (or input + output) is above the model's context window            | a shorter `maxContext`                                                       |
| `E-KV-DTYPE`                                          | an 8-bit KV cache on TensorRT-LLM over weights that are not FP8                 | FP8 weights (`model.format: fp8`), or 16-bit KV                              |
| `E-KV-EVENTS`                                         | `kvEvents` on an engine other than vLLM or SGLang                               | `prefixAffinity` instead                                                     |
| `E-CACHE-REMOTE`                                      | `cacheIsolation` other than `none` on a remote endpoint                         | leave it `none`                                                              |
| `E-KV-OFFLOAD`, `E-KV-RAM`, `E-DISK`                  | a tier on an unproven vendor, or one that the node's memory or disk cannot hold | see [KV cache tiers](https://opod.io/docs/control-plane-endpoints/kv-tiers/) |

## Sizing

**Problem.** A KV cache sized from guesses either wastes cards or runs out at the peak. An engine that cannot hold its context also shortens it silently at start.

**How it works.** You describe the traffic in `plan.workload`. The planner turns it into memory and shows the arithmetic in Preview, term by term (advisory `workload`).

```yaml
workload:
  inputTokens: 2000       # one typical prompt
  outputTokens: 500       # one typical answer
  maxContext: 4096        # the longest request, prompt + answer; default inputTokens + outputTokens
  peakConcurrency: 80     # requests in flight at the busiest moment; default 1
  peakRps: 20             # recorded and said back, never sized from
  headroomPct: 15         # margin over the pool; default 15, 0 = no margin
```

### The per-token formula

The planner reads the model's shape from the catalog (`architecture`) and the element size from the plan's flags (2 bytes by default). One token of KV cache is:

| Architecture                                                   | Bytes per token                                                                   | Catalog fields                                             |
| -------------------------------------------------------------- | --------------------------------------------------------------------------------- | ---------------------------------------------------------- |
| Grouped-query or multi-head attention                          | 2 × layers × KV heads × head dim × bytes per element                              | `layers`, `kv_heads` (else `heads`), `head_dim` (else 128) |
| Multi-head latent attention, on vLLM, SGLang, TensorRT-LLM     | layers × (`kv_lora_rank` + `qk_rope_head_dim`) × bytes                            | the engine keeps one compressed latent per layer           |
| Multi-head latent attention, on llama.cpp                      | layers × heads × (`qk_nope_head_dim` + `qk_rope_head_dim` + `v_head_dim`) × bytes | llama.cpp keeps K and V per head                           |
| Sliding-window layers                                          | as GQA, but only for the last `sliding_window` tokens                             | `sliding_window`, `sliding_layers`                         |
| Hybrid state layers (SSM, linear attention, short convolution) | nothing per token; a fixed `state_bytes` per sequence                             | `state_layers`, `state_bytes`                              |

One request of `n` tokens therefore needs:

```text
full layers × per-layer bytes × n
+ sliding layers × per-layer bytes × min(n, window)
+ state bytes
```

A model whose catalog entry records too little architecture is not sized. Preview says so instead of inventing a number.

### From one request to the pool

```text
one request   = the formula above at the workload's context
endpoint pool = peakConcurrency × one request × (1 + headroomPct / 100)
per worker    = (card budget − weights − engine overhead − unmeasured margin) ÷ (one request × margin)
```

- **The context** is, in this order: a context the row pins (`flags.ctx` for llama.cpp, `flags.max_model_len` for vLLM, SGLang and TensorRT-LLM), then `workload.maxContext`, then `inputTokens + outputTokens`. The shortest context an engine is started with is 512. A workload longer than the model's context window is refused.
- **What gets pinned.** vLLM, SGLang and TensorRT-LLM get `max_model_len` = the context. A dedicated llama.cpp worker starts at one request's length and the fill gives it as many slots as its card holds. A shared llama.cpp worker gets one pool for its share of the peak (`ctx` = its share × the context, `parallel` = its share).
- **No workload.** A llama.cpp worker with no context gets 8,192 tokens, capped at the model's window, and Preview says so. A llama.cpp gang gets no default: it keeps the model's full window, and a gang that cannot hold that much KV cache fails at start. Set `shardGroups[].flags.ctx` (see [Gangs](https://opod.io/docs/control-plane-endpoints/gangs/)). vLLM and SGLang are left at their own defaults.
- **Card budget.** A row's `vramBudgetGb`, else the smallest usable card on the node. A dedicated vLLM worker fills 0.85 of its card unless `flags.gpu_memory_utilization` says otherwise.
- **Engine overhead per worker:** vLLM 837 MiB on NVIDIA and 1,103 MiB on AMD; 190 MiB for anything not measured. llama.cpp in 0.3.0: 640 MiB on NVIDIA.
- **llama.cpp's overhead, from 0.3.2,** is three terms, read from llama-server's own buffer log:

  - a fixed part per card model: 160 MiB on an RTX 3060 Ti, 365 MiB on an AMD Radeon RX 7900 XTX, 570 MiB on an RTX 5090. A card not measured (another AMD card included), or a worker not placed yet, takes 570.
  - a compute base of 136 MiB (the largest measured, a 7B model; 34 MiB at 0.5B).
  - the attention mask, 1 KiB per attended token at llama.cpp's default micro-batch of 512. A shared worker's mask spans its whole pool; a dedicated worker's spans one slot.

  The slot count adds nothing at a fixed pool. Example: a shared llama.cpp worker on an RTX 3060 Ti with an 8,192-token pool: 160 + 136 + 8 = 304 MiB. The same worker before it is placed: 570 + 136 + 8 = 714 MiB. A 2-million-token shared pool adds 2 GiB of mask.
- **Weights and the unmeasured margin.** The catalog records weights in GB (10⁹ bytes); the card is measured in GiB (2³⁰ bytes). The planner converts the weights to GiB, and adds an *unmeasured margin* of 7.4 % of them, which Preview names in every reason. The margin keeps every claim the size it was in 0.2.1, which counted the weights in GB as if they were GiB. It is the one margin over what is not measured, and it stays. New in 0.3.0.
- **llama.cpp KV layout.** The planner pins `kv_unified`: `true` (one pool every slot shares) on a shared worker, `false` (one partition per slot) on a dedicated one.

When the workers cannot hold the peak, Preview says how many workers it takes and suggests `autoscale.floor`. It never changes your plan. A worker that cannot hold even one request of the workload's length is refused `E-FIT`, and a shared worker no card in the cell can hold is `E-FIT` with the number of workers it takes. See [Error codes](https://opod.io/docs/control-plane-reference/error-codes/).

The planner sizes **memory only**. A request rate without a latency gives no concurrency, so `peakRps` alone is said back with a request for `peakConcurrency`.

### Worked example: an 8B model

Llama 3.1 8B (`llama-3.1-8b`): 32 layers, 8 KV heads, head dim 128 (not recorded, so the 128 default), bf16 weights of 16.07 GB.

| Step                                         | Arithmetic                       | Result                                    |
| -------------------------------------------- | -------------------------------- | ----------------------------------------- |
| One token, 16-bit                            | 2 × 32 × 8 × 128 × 2 B           | 131,072 B = 128 KiB                       |
| One request, chat preset (2,000 + 500)       | 2,500 × 128 KiB                  | 0.31 GiB                                  |
| One request at 4,096 tokens                  | 4,096 × 128 KiB                  | 0.50 GiB                                  |
| One request at the full 131,072-token window | 131,072 × 128 KiB                | 16 GiB                                    |
| Endpoint pool, 80 at once, 15 % margin       | 80 × 0.305 × 1.15                | 28.1 GiB                                  |
| Weights in GiB, and the unmeasured margin    | 16.07 × 10⁹ ÷ 2³⁰; 16.07 − 14.97 | 14.97 GiB; 1.10 GiB                       |
| Room on a dedicated vLLM worker, 48 GiB card | 48 × 0.85 − 14.97 − 1.10 − 0.82  | 23.9 GiB                                  |
| Requests per worker                          | 23.9 ÷ (0.305 × 1.15)            | 68                                        |
| Workers for the peak                         | ⌈80 ÷ 68⌉                        | 2 — Preview suggests `autoscale.floor: 2` |
| The same with an 8-bit KV cache              | 23.9 ÷ (0.153 × 1.15)            | 136 per worker, so 1 worker               |

The other shapes, at 32,768 tokens:

| Model                              | Shape                                                                | Plain formula | What the planner sizes                              |
| ---------------------------------- | -------------------------------------------------------------------- | ------------- | --------------------------------------------------- |
| `gpt-oss-20b`                      | 24 layers, 12 sliding at a 128-token window, 8 KV heads, head dim 64 | 1,536 MiB     | 771 MiB (12 full layers, plus 3 MiB for the window) |
| `lfm2.5-8b-a1b`                    | 24 layers, 18 short-convolution state layers                         | 1,536 MiB     | 384 MiB, plus a 0.28 MiB state                      |
| DeepSeek-V2-Lite on llama.cpp      | 27 layers × 16 heads × (192 K + 128 V)                               | —             | 8,640 MiB (measured)                                |
| DeepSeek-V2-Lite on vLLM or SGLang | 27 layers × (512 latent + 64 rope)                                   | —             | 972 MiB                                             |

The llama.cpp MLA figure was measured on the engine. The vLLM latent figure has not been measured on a card yet.

### Presets

The create form fills `plan.workload` from three presets:

| Preset         | In     | Out   | At once |
| -------------- | ------ | ----- | ------- |
| Chat assistant | 2,000  | 500   | 80      |
| Long documents | 16,000 | 1,000 | 8       |
| Batch          | 1,000  | 300   | 128     |

**Cost.** None at run time: this is arithmetic. **Limits.** It is an estimate. The catalog's `head_dim` default of 128 is too high for small models (Qwen2.5-0.5B's is 64). The measured advice below corrects it. **Gangs.** A gang's pool is stated per gang, not counted in the workload pool, and a llama.cpp RPC gang does not shrink its context to fit: pin `flags.ctx` on it. See [Gangs](https://opod.io/docs/control-plane-endpoints/gangs/).

## Precision

**Problem.** At 16 bits per element the KV cache is often the limit on concurrency or context length.

**How it works.** An 8-bit KV cache stores each key and value element in one byte, so a token takes half the memory and a card holds twice the tokens. It is opt-in on every engine. 16-bit stays the default.

| Engine       | Flag                   | Example values                | Engine argument                                     |
| ------------ | ---------------------- | ----------------------------- | --------------------------------------------------- |
| vLLM         | `flags.kv_cache_dtype` | `fp8`, `fp8_e4m3`, `fp8_e5m2` | `--kv-cache-dtype`                                  |
| SGLang       | `flags.kv_cache_dtype` | `fp8_e4m3`, `fp8_e5m2`        | `--kv-cache-dtype`                                  |
| TensorRT-LLM | `flags.kv_cache_dtype` | `fp8`                         | `kv_cache_config.dtype` in the engine's config file |
| llama.cpp    | `flags.kv_cache_type`  | `q8_0`, `q4_0`                | `-ctk` and `-ctv`                                   |

The planner sizes the value by its name. Every `fp8…` type is 1 byte per element. llama.cpp's block types store a scale with each block of 32 elements, so `q8_0` is 34/32 bytes, `q5_1` 24/32, `q5_0` 22/32, `q4_1` 20/32 and `q4_0` 18/32. `f32` is 4 bytes, and any other name is sized at 2 bytes, which reserves more, never less. When the KV cache is what limits the plan, Preview's `E-FIT` remedy names the smaller type for the plan's own engine, under that engine's flag.

> **Warning**
>
> Up to and including 0.2.1, the planner read the digits of the value: `fp8_e4m3` was sized as a 4-bit cache, half of what the engine allocates, and `q8_0` as exactly 1 byte. Use `fp8` or `fp8_e5m2` on 0.2.1. 0.3.0 reads the name.

**Proven.** SGLang on NVIDIA with `fp8_e5m2`: the engine reported a pool of 54,448 tokens against 27,216 at 16-bit, exactly 2.0×. TensorRT-LLM over an FP8 checkpoint served on an RTX 5090. vLLM and llama.cpp pass the flag to the engine and are sized at the new element size; no separate hardware proof is recorded for them.

**Failure.** On TensorRT-LLM an 8-bit KV cache over 16-bit weights died at start for want of an attention kernel. The planner refuses it `E-KV-DTYPE` unless the plan's weights are FP8 (`model.format: fp8`). Weights of unknown precision are refused too.

**Cost.** Lower precision changes the values attention reads. opod does not measure answer quality for you: add an eval step to the rollout before you keep it (see [Rollouts and runs](https://opod.io/docs/control-plane-endpoints/rollouts/)). **When not to use it:** when the KV cache is not the limit, or on a task where small numeric differences matter and you have no eval.

## Prefix

**Problem.** Many requests start with the same tokens: a system prompt, tool definitions, a shared document. Computing them again for each request wastes prefill time.

**How it works.** Every engine keeps a prefix cache on the card. A new request is matched against it **from the first token** and the match **stops at the first token that differs**. Everything after that point is computed again at full prefill cost, even when the rest is identical.

```text
cached:  [system prompt ......][tools ....][document ..........][question A]
new:     [system prompt ......][tools ....][document ..........][question B]
          └───────────────────── reused ───────────────────────┘└ computed ┘

new:     [2026-10-23 09:14][system prompt ......][tools ....][document ....][question B]
          └ differs ──────┘└──────────── all of it computed again ─────────────────────┘
```

There is nothing to switch on. What decides the reuse is the order of your prompt's parts.

### Prompt layout: stable first, changing last

1. The system prompt.
2. Tool definitions, always in the same order.
3. Shared reference material: a policy, a manual, a document many requests use.
4. The conversation so far. Append new turns; do not rewrite earlier ones.
5. Last: what changes per request — the user's name, the date, a request id, the question.

What breaks reuse without anyone noticing:

- A timestamp, request id or user name at the top of the system prompt.
- Tools in a different order from one request to the next (a map iterated in random order). Sort them by name.
- JSON whose key order changes. Serialise with sorted keys.
- Whitespace that varies: trailing spaces, line endings, a template that sometimes adds a blank line. The cache compares tokens, not meaning.
- A chat template that inserts today's date or a random id into the system header. Reuse then breaks once a day, or on every request.
- Retrieved documents in a different order. Order them by a stable key, the most shared first.

**Measure it.** The leader reports the engines' prefix-cache hit rate on `/loadz` as `prefix_hit_pct` (vLLM, SGLang, TensorRT-LLM; llama.cpp reports none). On core v0.4.0 it is the plain mean of the workers' own rates, and a worker that served no request yet counts as 0 %: two workers, one serving everything at 98 %, read 49 %. From core v0.4.1 (control plane 0.3.2 pins core v0.4.2), a vLLM endpoint's figure is hit tokens ÷ looked-up tokens over all its workers, so it is weighted by traffic and an idle worker adds nothing; `/loadz` also carries the two counters, `prefix_hit_tokens_total` and `prefix_query_tokens_total`, so two reads give the rate over the time between them. SGLang and TensorRT-LLM publish a rate and no counters, so their figure stays the mean: check that every worker carries traffic before you act on it. The endpoint page's **Load** card shows it. A long average prompt with a low hit rate means the prompts share little prefix. One worker much lower than its siblings points at [routing](#routing), not at the prompt. A rate that drops at the same time every day usually means a date in the chat template.

**Limits.** The cache on the card holds only what fits beside the running requests; under load the engine evicts old prefixes. A [tier](#tiers) keeps them in host memory. opod never reads your prompts to judge their layout: the advice comes from the engines' own counters.

## Routing

**Problem.** With several workers, a request that lands on the wrong one either queues behind a full KV cache or recomputes a prefix a sibling already holds.

**How it works.** The leader picks the worker. The control plane only sets its policy (`PUT /api/v1/endpoints/{id}/policy`, see [Routing policy](https://opod.io/docs/control-plane-endpoints/routing/)). The leader reads each worker's KV use and queue depth from its heartbeat, every 5 seconds, and ranks the workers in four steps:

1. **Saturated workers go last.** A worker whose requests in flight fill its slots, or whose KV use is at or above `kvSaturationPct`, sorts behind every worker with headroom. It gets a request only when no other worker has room.

2. **Lowest score wins.**

   ```text
   score = in-flight + queue depth + kvWeight × KV used % / 100 − prefixBlockWeight × leading blocks held
   ```

3. **Prefix pin.** With `prefixAffinity` on, and only when no worker reported holding any block of this request, the worker that last served the longest matching part of the prompt moves to the front — unless it is saturated or its slots are full.

4. The first worker in the list takes the request.

| Knob                        | Range               | Default                                            | What it does                                                                                                                                                                                       |
| --------------------------- | ------------------- | -------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `routing.kvWeight`          | 0–100               | 0 (off)                                            | how many in-flight requests a full KV cache counts as                                                                                                                                              |
| `routing.kvSaturationPct`   | 0–100               | 0 (off)                                            | KV use at which a worker goes behind every worker with headroom                                                                                                                                    |
| `routing.prefixAffinity`    | true / false        | false                                              | the prefix pin, for engines that publish no cache events                                                                                                                                           |
| `routing.stickyTtlSeconds`  | 0–86,400            | 0 (the leader's: sessions off, prefix pins 10 min) | how long a session or a prefix pin lasts; live (0.3.0). See [Sticky sessions](https://opod.io/docs/control-plane-endpoints/routing/#sticky-sessions)                                               |
| `routing.prefixBlockWeight` | 0–10                | 0 (off)                                            | how many in-flight requests one held leading block is worth; needs `plan.kvEvents: true`                                                                                                           |
| `routing.prefixBlockTier`   | `gpu` / `cpu-lower` | `gpu`                                              | `cpu-lower` also counts a leading block the worker's CPU tier holds, at 0.8 of a card block; vLLM with a `cpu` tier (0.3.0). The leader's `/loadz` `prefix_index.cpu_blocks` shows what it indexed |
| `plan.kvEvents`             | true / false        | false                                              | the engine publishes its cache events and the worker reports block hashes; vLLM and SGLang only (`E-KV-EVENTS` otherwise)                                                                          |

To see why a worker did or did not win, run the leader at `OPOD_LOG_LEVEL=debug` (0.3.0). Each pick with a prompt chain logs one `prefix block credits` line: per candidate, its leading blocks on the card (`card`), in its CPU tier (`cpu`), from a peer (`peer`) and the `credit` they earned. Every chain starts with the blocks all requests share, so `card=0` on every worker means the index is missing them; from 0.3.0 a worker restates what it holds after any heartbeat that did not land, including the first one after a leader restart.

**Should you turn them on?** Measured on two RTX 3060 Ti workers with Qwen2.5-0.5B-Instruct, three seeds each, on vLLM, SGLang and llama.cpp: neither the pin nor `prefixBlockWeight` beat routing by load by more than the spread between runs. With one shared system prompt every way tied, except the pin on llama.cpp, which cost 2 %. With eight system prompts the best gain was +2.4 % (the pin on vLLM). On llama.cpp the pin raised the hit rate from 48 % to 94 % and still gained no throughput, because a 0.5B model's prefill is cheap. So both stay off by default. Turn one on when your prompts are long enough that prefill dominates, and measure your own traffic with it off and on.

The policy knobs apply live. `kvEvents` is an engine launch flag, so a change rides a rollout.

**Where KV use comes from.** vLLM: `vllm:kv_cache_usage_perc`. SGLang: `sglang:token_usage`. TensorRT-LLM: `kv_cache_utilization`, which the pinned image reports only when its config file turns on iteration statistics, as a [tier](#tiers) does. llama.cpp: `kv_cache_usage_ratio`, else busy slots ÷ slots — then the "KV use" is slot occupancy, not memory. A worker with no fresh sample is scored on in-flight requests alone.

### What the prefix pin hashes

The leader hashes the request's leading text — the system prompt, then every message in order with its role — in a chain of 256-byte chunks. Each link is 8 bytes of a SHA-256 over the previous link and its chunk, so two prompts share links exactly as long as their text does. Every 256-byte chunk counts to 4 KiB. From the core release after v0.4.8 the chain then keeps one link at each doubling distance (8, 16, 32 … KiB) up to the leader policy's `routing.prefixDepthKiB` (default 256; 4 = the 4 KiB chain). A match at the deepest common link is within 2× of the true shared prefix. The request's cache salt seeds the chain, so a pin never crosses [isolation](#isolation). The leader keeps links and worker ids only, never the text: at most 131,072 entries, each kept for 10 minutes after the last request that used it.

### What `prefixBlockWeight` counts

With `kvEvents` on, vLLM or SGLang publishes every block it stores and evicts on a local socket. The worker turns each block into opod's own hash of the block's token ids and its parent block, and sends the hashes on its heartbeat. Token ids never leave the worker. The leader keeps up to 200,000 hashes per worker, and empties a worker's set on a gap in its sequence, a new boot id, or the engine's own clear.

For each request, the leader asks the engine's `/tokenize` for the first 2,048 tokens (from the core release after v0.4.8: `prefixDepthKiB` × 256 tokens, 65,536 at the default, never fewer than 2,048; it waits at most 250 ms) and builds the same chain of block hashes. A worker is credited only for **leading** blocks: block 3 is a hit only when blocks 1 and 2 were. One block is 16 tokens, so a 4,000-token system prompt is 250 blocks.

### Worked example

Policy `kvWeight: 50`, `kvSaturationPct: 90`, `prefixBlockWeight: 0.1`. The request opens with a 4,000-token system prompt (250 blocks). Worker A served it a minute ago.

| Worker | In flight | Queue | KV used | Load score          | Leading blocks held | Final score      | Rank  |
| ------ | --------- | ----- | ------- | ------------------- | ------------------- | ---------------- | ----- |
| A      | 3         | 0     | 40 %    | 3 + 0 + 20 = 23     | 250                 | 23 − 25 = **−2** | **1** |
| B      | 1         | 2     | 60 %    | 1 + 2 + 30 = 33     | 0                   | 33               | 3     |
| C      | 0         | 0     | 93 %    | saturated (93 ≥ 90) | 0                   | —                | 4     |
| D      | 2         | 0     | 10 %    | 2 + 0 + 5 = 7       | 0                   | 7                | 2     |

- With `prefixBlockWeight: 0`, D wins (7). A, the worker that holds the prompt, is third.
- With `kvWeight: 0` as well, the scores are A 3, B 3, D 2: D still wins, and C still goes last because of `kvSaturationPct`.
- With all three knobs off, C wins: it has the fewest requests in flight, and nothing tells the leader its cache is full.
- On llama.cpp (no cache events) with `prefixAffinity: true`, no worker reports blocks, so the pin moves A to the front because it served this prefix last.

**Proven.** Block routing was measured on vLLM on NVIDIA: on a pool large enough for both caches it tied the prefix pin, so both stay off by default. On SGLang the leader's index fills from the engine's events and its hashes match SGLang's tokens; a choice between two SGLang workers has not been run yet. The load score and saturation rule work on every engine that reports KV use.

**Cost.** Block routing adds one tokenize call per request (at most 250 ms; a slower one is skipped) and up to 200,000 block hashes per worker in the leader's memory. The prefix pin costs one hash chain per request.

**Failure modes.** A wrong index routes worse than none, so any doubt empties it and the prefix pin decides. With an index that is briefly empty the leader routes by load. Until the core release after v0.4.8 the block index is not salted, so a worker may be credited for blocks it holds under another caller's salt: a cold prefill there, never a shared one. From that release each worker seeds a prompt's first block from the salt its engine published (vLLM, SGLang), and the leader seeds the request's chain from the salt it sent and the LoRA adapter, so a worker is credited only for blocks it would share with that caller. A request whose keys the leader cannot rebuild, such as one with an image, earns no credit.

**When not to use it.** One worker: there is nothing to choose. Requests with no shared prefix: block credit is zero and the tokenize call is pure cost. A high `prefixBlockWeight` makes a hot prefix pile onto one worker. Choose it from what the shared prefix should be worth: in-flight requests ÷ the prefix's blocks. To make a 250-block prompt worth 5 requests, set 5 ÷ 250 = 0.02.

## Isolation

**Problem.** A shared prefix cache lets one caller reuse a prefix another caller computed, and the faster first token shows it: someone sent that text before. On a multi-tenant endpoint that is a side channel.

**How it works.** `plan.routing.cacheIsolation` says whose requests may share:

| Mode             | Who shares a cache                                                           |
| ---------------- | ---------------------------------------------------------------------------- |
| `team` (default) | every key of one team; teams never share. A key with no team is its own team |
| `key`            | each key alone                                                               |
| `none`           | every caller                                                                 |

The leader turns the caller into a **salt**: the first 128 bits of an HMAC-SHA256 under the endpoint's admin token, over `opod-cache-salt/v1`, the mode and the team or key id. The id itself never goes on the wire. The leader sends the salt as `cache_salt` to vLLM, SGLang and TensorRT-LLM, which key their prefix cache by it, and seeds the prefix pin with it. Front doors hold the same admin token, so they derive the same salt for the same caller.

The plan owns the field; the control plane copies it into the policy, and the leader applies it live with no pod restart.

**Exceptions.**

- **llama.cpp takes no salt.** Every caller shares its cache whatever the mode, and Preview says so in an advisory.
- **No key, no salt.** On an endpoint that does not require keys, every request shares.
- **Remote endpoints** are `none`: the vendor's API refuses a `cache_salt` field. Any other mode is refused `E-CACHE-REMOTE`.
- **An older leader image** that does not advertise `cache_salt` shares until the endpoint is rolled; Preview says so.
- A bare `opod up` leader with no admin token salts under a random key drawn at start, so its salts change on restart.

**Cost.** Each team (or key) computes and stores its own copy of a shared prefix: prefill time and KV memory once per team. With `key` that is once per key. **When not to use it:** `none` is right only for a single-tenant endpoint that wants every hit.

## Tiers

**Problem.** The card evicts old prefixes under load. A request that needs one again pays its full prefill.

**How it works.** `workers[].kvOffload` gives the engine a tier below VRAM: blocks the card evicts are kept in host memory (and, on vLLM, on disk below that) and copied back on a prefix hit instead of being computed again. It helps when many requests share a long prefix: RAG, agents, one long system prompt.

| Tier                 | Plan                                                                              | Engines                                  | Proven on                           |
| -------------------- | --------------------------------------------------------------------------------- | ---------------------------------------- | ----------------------------------- |
| `cpu`                | `{tier: cpu, sizeGb: 8}` — host memory per replica, whole GiB                     | vLLM, SGLang, llama.cpp, TensorRT-LLM    | NVIDIA; vLLM also on AMD from 0.3.2 |
| `disk`               | `{tier: disk, sizeGb: 8, diskGb: 200}` — a CPU tier with a disk tier below it     | vLLM                                     | NVIDIA; AMD from 0.3.2              |
| `auto`               | `{tier: auto, maxGb: 16}` — a CPU tier the control plane resizes from measurement | as `cpu`                                 | as `cpu`                            |
| `peer` **(planned)** | a CPU tier shared between an endpoint's workers                                   | refused on every engine (`E-KV-OFFLOAD`) | none                                |

- **Host memory is claimed.** The worker's `/dev/shm`, memory request and memory limit grow by `sizeGb`. Every tier on a node may take at most `kvOffload.maxNodePct` (default 50) of its memory, and tiers plus the workers' own memory must fit it, or the plan is refused `E-KV-RAM`.
- **Disk is claimed.** `diskGb` is claimed on the node's model-cache volume with 15 % of the volume kept free (`E-DISK`). A `kv-prune` container keeps the directory under its cap.
- **Auto** re-reads the tier advice every 10 minutes and resizes through a verified rollout when the size should move by at least a quarter, at most once in 30 minutes.
- **Other vendors** are refused `E-KV-OFFLOAD`, naming the vendors the tier is proven on. A tier under tensor parallel and a tier on a gang are built but not yet proven on hardware.

The whole mechanism — the engine arguments, the claims, the pruner, the auto loop's numbers, gangs and why `peer` is refused — is on [KV cache tiers](https://opod.io/docs/control-plane-endpoints/kv-tiers/).

## What was measured

The control plane compares its arithmetic with what the engines report.

| Route                                       | Answers                                                                                                                                                                                                                             |
| ------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `GET /api/v1/endpoints/{id}/kv`             | per worker: the planner's figure (`planned`: tokens, bytes per token, GB), the engine's own sample (`load`: KV in use, the pool it built, slots, preemptions, evictions, tier counters), slots, requests in flight and `tierHitPct` |
| `GET /api/v1/endpoints/{id}/kv/advice`      | the plan's pool against a week of measured use, with one suggested edit                                                                                                                                                             |
| `GET /api/v1/endpoints/{id}/kv/tier-advice` | the tier size that would help, from the blocks the engines evicted and computed again                                                                                                                                               |

A figure the engine does not report is absent, never 0.

### The sampler and the pool advice

The `kv-sampler` loop records each worker's KV in use every **2 minutes** and keeps **8 days** (at most 5,760 rows per worker). `/kv/advice` reads the last **7 days**:

```text
hourly peak = Σ over workers of each worker's highest sample in that hour
p90         = the 90th percentile of the hourly peaks (nearest rank)
need        = p90 × (1 + headroomPct / 100)     # 15 % when the plan states none
ratio       = need ÷ pool
```

| State          | When                                                                                                        |
| -------------- | ----------------------------------------------------------------------------------------------------------- |
| `insufficient` | fewer than 24 hours carry samples                                                                           |
| `oversized`    | ratio below 0.75                                                                                            |
| `undersized`   | ratio above 1.25, or a worker used 95 % or more of the pool its engine built in more than 10 % of the hours |
| `fits`         | between the two                                                                                             |
| `unknown`      | samples exist, but there is no pool to hold them against                                                    |

The pool comes from the workload (`peakConcurrency` × the request length × the margin), from the plan (the contexts llama.cpp workers are started with), or from the pools the engines report. The suggestion edits exactly one of `workload.peakConcurrency`, `flags.ctx` or `vramBudgetGb`.

### The tier advice

`/kv/tier-advice` needs `plan.kvEvents: true`. The leader keeps a ghost list of up to 131,072 evicted blocks per worker. A block the engine stores again was computed again, and the number of evictions between its eviction and its return is its depth. A tier that holds `T` tokens keeps the last `T ÷ block size` evicted blocks, so:

```text
estimated hit rate(T) = returns with depth ≤ T ÷ block size  ÷  blocks computed
```

The candidate sizes come from depth buckets of 1,024, 4,096, 16,384, 65,536 and 131,072 blocks, converted to GiB with the model's bytes per token. The advice needs at least 16,384 computed blocks (about 262,000 tokens at 16-token blocks). It suggests the smallest size within 90 % of the best estimate, and nothing when the best is under 5 %. Each size is judged by the planner first, so a size the node cannot hold reads as refused. The estimate is stated as ±10 points: it assumes the traffic stays the same, and decode blocks count as computed, so it leans low.

| State          | Meaning                                                               |
| -------------- | --------------------------------------------------------------------- |
| `unknown`      | no cache events, or no model shape to turn tokens into bytes          |
| `insufficient` | under 16,384 computed blocks                                          |
| `none`         | a tier would serve under 5 %, or no size fits                         |
| `advise`       | a size is suggested                                                   |
| `has-tier`     | the worker keeps a tier you sized; the measurement is shown beside it |

Advice changes nothing. On the endpoint page, the KV card shows the verdict, and **Review the suggested size** opens the plan editor with the edit applied, to preview and roll.

**Metrics** (`opodcp` `/metrics`, labels `endpoint`, `node`): `opodcp_kv_tier_hit_tokens`, `opodcp_kv_tier_query_tokens`, `opodcp_kv_tier_loaded_bytes`, `opodcp_kv_tier_stored_bytes`, `opodcp_kv_tier_used_percent`, `opodcp_kv_tier_alloc_failures`. See [Observability](https://opod.io/docs/control-plane-operate/observability/).

## Which strategies for which workload

| Workload shape                                                      | Turn on                                                                                       | Leave off                                           |
| ------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- | --------------------------------------------------- |
| One worker, any traffic                                             | `workload`; 8-bit KV if the KV cache is the limit                                             | routing knobs (nothing to choose)                   |
| Chat, several workers, short shared system prompt                   | `workload`; `kvWeight` and `kvSaturationPct` (for example 90)                                 | tiers (the prefix fits on the card)                 |
| RAG or agents: long shared prefixes, several vLLM or SGLang workers | `workload`; `kvEvents` + a small `prefixBlockWeight`; a `cpu` or `auto` tier                  | `cacheIsolation: none` unless single-tenant         |
| The same on llama.cpp                                               | `prefixAffinity`; a `cpu` tier (`--cache-ram`)                                                | `kvEvents` (refused `E-KV-EVENTS`)                  |
| Long documents: few requests, very long contexts                    | `workload.maxContext`; 8-bit KV; on vLLM a `disk` tier for re-read documents                  | `prefixAffinity` (little sharing between documents) |
| Batch: many short independent requests                              | `workload` with a high `peakConcurrency`; `kvWeight`                                          | tiers, prefix routing                               |
| Many tenants on one endpoint                                        | `cacheIsolation: team` or `key` on vLLM, SGLang or TensorRT-LLM                               | llama.cpp (it cannot separate tenants)              |
| Not sure what the traffic will be                                   | `workload` from a preset, then read `/kv/advice` after a week; an `auto` tier with `kvEvents` | hand-sized tiers                                    |
