← Blog
Published on
2026-11-30

Prefix-aware routing in Hivenet Router: test cache reuse across vLLM replicas

Prefix-aware routing helps an inference server operator decide where to send the next turn of a conversation. Hivenet Router v0.1.8 estimates which eligible replica can return the first token soonest, using both its queue and the prompt prefix it may still hold in its key-value (KV) cache. This guide compares that policy with least-loaded routing on two vLLM replicas serving the same model. You’ll measure whether follow-up questions get faster, how often vLLM actually reuses prompt tokens, and what happens to the slowest requests under load.

How does prefix-aware routing balance cache reuse and load?

Prefix-aware routing uses two pieces of information about an incoming chat request: how much of the prompt each eligible replica is likely to have cached and how much work is already waiting there. Suppose a customer asks a follow-up about a long document. Replica A served the first turn and may still hold those prompt tokens. Replica B has an empty queue. Router estimates the time until each replica could produce its first token. A modest queue on A may be worth waiting for. A long queue can make B the faster choice even if it must process the document again.

LLM inference has two phases. During the prefill phase, the inference engine processes input tokens and computes attention keys and values. With automatic prefix caching enabled, vLLM can reuse KV state already in GPU memory for the matching beginning of a new request. During decoding, the model still has to generate each output token. A cache hit saves prefill work for the reused tokens. That distinction matters when you interpret a benchmark: a faster first token can coexist with little change in the time between later tokens. See vLLM’s automatic prefix caching documentation.

Start with two healthy replicas serving the same model

Use a test deployment with one Router and two vLLM agents, one per replica. The vLLM load-balancing guide covers that setup. Check GET /v1/models with the inference key you’ll use for the test. Find your model ID in the response. Check that agents.total and agents.healthy are both 2 and that agents.engines contains only vllm. Use the same model revision, tokenizer, chat template, GPU configuration, and cache allocation on both. Use a test policy with no external fallback or other eligible backends.

Enable prefix caching and cache reporting in both test conditions. On each replica, add these options to its existing vLLM launch command. The v0.1.8 technical report used vLLM 0.31.0. Check the flags against your installed version.

--enable-prefix-caching \
--enable-prompt-tokens-details \
--kv-events-config '{"enable_kv_cache_events":true,"publisher":"zmq","endpoint":"tcp://127.0.0.1:5557","topic":"kv-events"}'

Add --kv-events-endpoint tcp://127.0.0.1:5557 to the corresponding Router agent. Each engine and its agent must agree on the local endpoint. Two separate hosts or pods can reuse port 5557. Two pairs in the same network namespace need separate ports. Keep the event stream on loopback or a shared local socket because it carries token IDs. Cache events let Router track evictions as well as newly stored blocks. Without events, a previously served prefix can still influence routing after the engine has evicted it. See the Router configuration and engine requirements.

Which prompts can reuse the same cache blocks?

Think about two requests that share a system prompt and chat history. The engine needs an exact match in the token sequence up to each reusable block. If the two prompts diverge halfway through the history, complete matching blocks before that position can still be reused. Later blocks depend on the earlier context. A timestamp at the start of the system prompt can therefore cost more cache hits than a timestamp at the end of the user’s question.

Router makes a separate decision about where to send that request. It computes a keyed hash at each message boundary. The agent groups token IDs into fixed-size blocks of 64 tokens for its reports to Router. That block size describes the routing index. vLLM manages its own cache blocks and decides what it can actually reuse. It can recognize a previously served shared system prompt even when the next user message changes. In the least-loaded baseline, cache locality does not determine replica selection. The engine may still get cache hits by chance. Keep prefix caching enabled in both runs so you measure the difference routing makes.

Build two workloads with different levels of prefix reuse

Start with a set of representative, non-sensitive multi-turn chats. Save a JSON array with one entry per conversation. Each entry has an id and a turns array. Each turn contains the full message list the client would send. Use a fixed assistant reply in the saved history so both strategies receive exactly the same follow-up, even if the first generated reply differs. This short entry illustrates the file format.

[
  {
    "id": "map-1",
    "turns": [
      [
        {
          "role": "user",
          "content": "Read the North Trail field notes. Which crossing is closed?"
        }
      ],
      [
        {
          "role": "user",
          "content": "Read the North Trail field notes. Which crossing is closed?"
        },
        {
          "role": "assistant",
          "content": "The bridge at Birch Creek."
        },
        {
          "role": "user",
          "content": "Give me a shorter sign for that crossing."
        }
      ]
    ]
  }
]

For a measured run, replace the short field notes with realistic prompt lengths. Keep each earlier message byte-for-byte identical when extending it. Router matches prefixes at message boundaries. For a retrieval-augmented generation (RAG) test, two users might ask different questions about the same document. Keep the shared document in a complete, identical earlier message and put the question in the next one. If your real traffic puts both in a single user message, test that structure too. The engine may still reuse leading tokens, but Router cannot identify that within-message overlap from its message hashes.

Build a second file for the control. Keep the same number of requests, approximate token lengths, output limit, and concurrency. Give each request an unrelated beginning, including the first message, so one request does not deliberately warm the next. The control tells you whether an apparent latency improvement also occurs when there is little cache reuse to exploit.

Compare least-loaded and prefix-aware under the same conditions

For the baseline, set the active test policy to:

routing_policy:
  strategy: least-loaded

Prefix-aware routing is off by default. For the comparison, change only least-loaded to prefix-aware in the policy for the chat model. Use chat completions for this test: Router v0.1.8 sends embedding and reranking requests through least-loaded routing. With a single global test policy, start Router with --policy-file pointing to that file. Use the policy that actually applies to your requested model and omit request-level strategy overrides. Keep the same tenant key for all runs. The policy YAML reference describes how to load the policy.

Run each workload under each strategy. Start each run from equivalent cache conditions. On dedicated test hosts, restarting the test engines, agents, and Router before each run gives you a reproducible starting point. Wait for both replicas to become healthy. If you warm them up, use the same unrelated warm-up requests each time and exclude those from the measurements. Alternate which strategy runs first across repeats and keep other traffic off the deployment.

Measure the first text the client actually receives

Save this small replay client as replay.mjs. It uses Node.js 22 or later with no additional packages. It runs conversations concurrently and sends the turns of each conversation in order. Its timer stops at the first nonempty text delta. HTTP headers, role-only events, and the final usage event do not count as the first token.

import { readFileSync } from "node:fs";
import { createInterface } from "node:readline";
import { Readable } from "node:stream";
import { performance } from "node:perf_hooks";

const [file, workersText = "4"] = process.argv.slice(2);
const workers = Number(workersText);
const { ROUTER_URL, ROUTER_API_KEY, MODEL_ID } = process.env;
if (!file || !Number.isInteger(workers) || workers < 1 ||
    !ROUTER_URL || !ROUTER_API_KEY || !MODEL_ID) {
  throw new Error("Set ROUTER_URL, ROUTER_API_KEY and MODEL_ID; pass a workload file and a positive worker count.");
}
const cases = JSON.parse(readFileSync(file, "utf8"));
const endpoint = ROUTER_URL.replace(/\/$/, "") + "/v1/chat/completions";

async function measure(messages) {
  const body = JSON.stringify({
    model: MODEL_ID, messages, max_tokens: 32, temperature: 0,
    stream: true, stream_options: { include_usage: true }
  });
  const start = performance.now();
  const response = await fetch(endpoint, {
    method: "POST", body, signal: AbortSignal.timeout(120000),
    headers: { Authorization: "Bearer " + ROUTER_API_KEY,
               "Content-Type": "application/json" }
  });
  if (!response.ok) throw new Error("HTTP " + response.status);
  let ttft = null, usage = null, done = false;
  const stream = Readable.fromWeb(response.body);
  try {
    for await (const line of createInterface({ input: stream, crlfDelay: Infinity })) {
      if (!line.startsWith("data:")) continue;
      const data = line.slice(5).trim();
      if (data === "[DONE]") { done = true; break; }
      const chunk = JSON.parse(data);
      if (chunk.error) throw new Error(chunk.error.code || "Stream error");
      if (ttft === null && chunk.choices?.[0]?.delta?.content) {
        ttft = performance.now() - start;
      }
      if (chunk.usage) usage = chunk.usage;
    }
  } finally { stream.destroy(); }
  if (!done || ttft === null) throw new Error("Incomplete stream or no text");
  return { ttft_ms: ttft, prompt: usage?.prompt_tokens ?? null,
           cached: usage?.prompt_tokens_details?.cached_tokens ?? null };
}

let next = 0;
async function worker() {
  while (next < cases.length) {
    const c = cases[next++];
    for (const [turn, messages] of c.turns.entries()) {
      const row = { id: c.id, turn: turn + 1 };
      try { Object.assign(row, await measure(messages)); }
      catch (error) {
        console.log(JSON.stringify({ ...row, error: error.message }));
        break;
      }
      console.log(JSON.stringify(row));
    }
  }
}
await Promise.all(Array.from({ length: workers }, worker));

Set ROUTER_URL to your Router HTTPS base URL without /v1, provide ROUTER_API_KEY through your shell environment, and set MODEL_ID to the catalog ID. Save the conversation array as chats.json. Run node replay.mjs chats.json 4 > least-loaded-chats.jsonl for the baseline. Use a different output filename for each strategy, workload, and repeat. Four workers is a starting point. A file with one conversation exercises only one worker. Use enough independent conversations to reach your chosen concurrency.

Compare time to first token with the KV cache hit rate

For each run, calculate the median (p50) and 99th percentile (p99) of ttft_ms. Report first turns and follow-ups separately so cold first requests cannot hide a change in repeat turns. For the same set of requests, divide the sum of cached by the sum of prompt. This weights long and short prompts by their token counts. A missing usage field is unknown. Report how many rows have both counts and include only those rows in both sums.

Record the number of successful requests, errors, and planned turns skipped after a failure. Keep timeouts and failures visible alongside latency. A lower p99 computed from fewer completed requests can be misleading. Use enough requests for a meaningful tail estimate, repeat each condition, and compare run-to-run variation. The inference metrics guide explains how to interpret these percentiles.

If follow-up p50 improves and cached-token share rises, check p99 at your usual concurrency before adopting the policy. If cached-token share rises but p99 worsens, inspect per-replica queues and repeat at peak load. Router’s hivenet_prefix_routing_total records its selections. An outcome of hit describes what Router believed the chosen replica held. The engine’s usage report tells you how many tokens it actually reused. If multiple tenants share a replica, check prefix cache isolation between tenants before drawing conclusions about whose requests can reuse those tokens.

When should you keep least-loaded routing?

Use the no-reuse control to make this decision. If the requests share little input and both policies land within the same run-to-run range, you have little evidence for changing the production configuration. If only long follow-ups improve, check how often those follow-ups occur in real traffic. A workload designed to maximize cache hits can tell you whether the mechanism works, but the latency distribution from your usual mix of requests tells you whether it is worth enabling.

What if Router reports a hit but the engine reports no cached tokens?

First check the individual response. A missing cached_tokens field means the client lacks a measurement. A reported zero means the engine recorded zero reused tokens for that request. Next, check the event feed on the replica that received the request. A router can choose an agent based on a cache report and the engine can evict those blocks before the request arrives. Compare outcomes across a whole run before treating one miss as a configuration problem.

What Hivenet measured

Hivenet’s published benchmark used three routers and six replicas of Qwen2.5-7B-Instruct, four running vLLM and two running SGLang, on a mixed workload with constrained KV caches. At concurrency 32, the mean of the three runs’ median time to first token for multi-turn chat fell from 205 ms with least-loaded routing to 63 ms with prefix-aware routing. The report found no clear benefit when reuse was confined inside a single message. Those figures come from Hivenet’s six-replica benchmark. Use the two-replica replay above to decide which setting serves your own conversations better. Read the benchmark setup and results.

Your next workload belongs on Hivenet.

Pick one AI, compute, or storage workload and see the difference for yourself. Spin it up in minutes, or let our team map your fastest path to production.