KV Cache and Prefix Caching for Local LLMs

Vladimir Lomtev•
KV Cache and Prefix Caching for Local LLMs

KV-cache stores the states of tokens that have already been processed during generation, while prefix caching lets the system reuse matching states from the shared beginning of different requests. These are related but different mechanisms. They help reduce repeated work, but they consume memory and do not guarantee the same speedup for every response.

Prepared by AI Studio by Vladimir Lomtev on November 14, 2026, for developers building RAG systems, chatbots, and local LLM services. This is an explanation and a verification protocol based on engine documentation, without an original benchmark or guaranteed speedup percentages. Specific flags, metrics, and isolation rules depend on the server version. Caching ready-made business answers is covered only to distinguish the concepts.

Contents

What KV-cache stores

In an attention model, keys and values, or K and V, are formed for processed positions. Saving these states makes it possible to reuse what has already been computed when continuing the sequence. This differs from storing the original text or the final answer in a regular database.

During generation, each new position adds state. As a result, a long conversation requires more memory than a short one, all else being equal. At the same time, active requests create a total demand that depends on the architecture and the runtime strategy.

KV-cache is not a universal long-term memory mechanism for an agent. After a restart or eviction, the state may no longer be available, and the application still has to form the request correctly. Business memory requires separate rules for data storage and access rights.

How prefix caching differs from a regular cache

Mechanism What gets reused What continues to be computed
KV-cache for a sequence States of the already processed context Continuation of the current generation
Prefix caching Matching states from the identical beginning of requests New tail and response generation
Ready response cache A previously saved application result Depends on the scheme; in some cases generation is skipped
Conversation history Messages and application data The model processes the provided context

Mixing up these concepts leads to incorrect expectations. Having a prefix cache does not mean the server returns a previous answer. Saving history does not prove that the computing cache was hit. And caching ready-made answers requires checking source freshness and permission to reuse the result.

The mechanism for reusing a shared input is described in Automatic Prefix Caching vLLM. In SGLang, a proprietary cache organization system is used; parameters and limitations should be checked against the SGLang configuration guide.

Why tokens and order matter

A similar meaning is not enough for a computational match. What matters is the actual sequence the model receives after tokenization and application of the conversation template. Two visually similar prompts can differ in spaces, field order, or special tokens.

If a stable system instruction is preceded by a unique identifier, the shared beginning becomes shorter. If the conversation history is rebuilt entirely with a different template, the match may also change. That is why, during diagnostics, the final input format is preserved without exposing secret data in a public log.

Data order is chosen primarily based on meaning. Do not move a user instruction into a position where it gets different privileges just for the sake of caching. Optimization should not change the trust boundary between system rules, the document, and user text.

Which scenarios are a good fit

Repeated questions about one large document are a natural candidate. The shared portion can be substantial, while the user’s question changes. Another example is stable instructions and tool definitions for a repetitive process.

In RAG, repeatability depends on the retrieved passages and their order. If every request selects a completely different set, the gain from a shared prefix may be small. That does not mean the cache is broken: the workload simply has a different profile.

For large-scale labeling, it is useful to check how stable the shared instruction is before the varying records. But if the prompt is short, overhead and generation may account for a larger share of the total time. Repeatability alone does not determine the business impact.

When caching barely helps

If long generation takes most of the time, reusing the input may have little effect on the overall response time. If the latency is in OCR or an external tool, model caching will not speed up that component. So first divide user time into stages.

Under overload, the queue may remain the main cause of waiting even with a high hit rate. When memory is tight, saved blocks can be evicted. A request that arrives after a model or configuration change should not be considered equivalent to the previous one based on text alone.

In a distributed service, routing to the instance that has the needed state matters. The load balancer and placement policy can affect actual repeatability. This is a separate architecture layer; add complexity only after the effect has been confirmed on a single instance.

How to estimate cache memory

For standard attention, the number of layers, KV heads, head size, number of tokens, and bytes per element determine a rough estimate. But for hybrid and compressed architectures, the formula must be refined. Do not transfer an estimate from one model to another just because the parameter counts are close.

Shared-prefix caching and serving active sequences compete for a limited resource according to the engine’s policy. Watch the available pool, eviction, and queue state. If preserving a rarely used prefix hurts interactive traffic, the configuration needs to be revisited.

KV-cache quantization is a separate way to reduce state size. It differs from weight quantization and requires its own compatibility and quality checks. vLLM Quantized KV Cache documentation describes the supported paths. The general principles of compression are covered in the LLM quantization article.

How to test prefix caching on your server

First, lock in the model, tokenizer, template, runtime version, and cache settings. Prepare permitted text with a long stable section and several different questions. Do not use an internal document if the test trace could send it outside.

Run four scenarios:

  1. The first request with the shared section after an agreed state reset.
  2. A repeated request with the same beginning and a different question.
  3. A request where an early element of the shared section is changed.
  4. A stream with other work between repeats to see the impact of eviction.

For each case, record TTFT, total latency, input and output lengths, memory usage, and the available cache metrics. Generation constraints should be comparable. If responses have different lengths, do not attribute all of the difference in total time to the cache mechanism.

On the vLLM side, verify metric definitions against Production Metrics and the actual /metrics. Metric names and sets change, so it is better to start with the observable export for your version.

How to measure the effect

For the same metric, you can calculate the relative change:

Time reduction = (baseline time − variant time) / baseline time

The baseline time must be positive, and the conditions being compared must be described. Example for illustration: 4 seconds to first token and 3 seconds in a repeated scenario gives a 25% reduction. This is an arithmetic example with fictional data, not a measured result from vLLM or SGLang.

One repeat is not enough to assess stability. Save multiple runs and explain the variation. For a report, use real observations, not just the best result. Aggregate hit rate also needs a definition: it can refer to requests, blocks, or tokens, and those have different denominators.

How to modify the application for repeatability

First eliminate random changes that do not add useful meaning: unique metadata fields before shared context, unstable ordering of identical descriptions, and differing formatting. For each change, verify that the final task and message permissions are preserved.

Do not remove the date if it affects the correctness of the answer. Do not merge contexts from different users just to improve hit rate. Do not retain results after changing document permissions just because the technical key matches.

For precomputed responses, you need a separate freshness key: source version, model, access policy, and request conditions. This is especially important when updating the knowledge base. Document release rules are covered in the RAG update checklist in Qdrant.

User isolation and security

The cache must operate within the permitted trust boundary. Check which isolation mechanisms the pinned version supports, how tenants are defined, and what data is available to the operator. Do not treat any shared server as safe just because the model is local.

Do not use a match as permission to access a document. Permissions are checked by the application before data is sent to the model and when the response is returned. Compute separation does not replace authorization.

Do not log full prompts in metric labels. This creates disclosure risk and high cardinality. For diagnostics, use limited technical attributes, identifiers for approved tests, and a protected log with controlled retention.

Caching protocol template

Model, revision, and chat template:
Engine, version, cache parameters:
Shared prefix and tail-change rule:
Cold-start procedure:
Input length and actual output length:
TTFT, total time, memory:
Hit metric and its denominator:
Behavior under mixed load:
Quality and isolation check:
Decision:

This template helps avoid mixing up first-token acceleration with a reduction in the overall business process. If there is no effect, the saved protocol is still useful: it rules out the wrong optimization and points the investigation to the real bottleneck.

The mechanisms behind server settings are covered in the engine and inference acceleration guide. Before choosing hardware, it is useful to go through the self-hosted inference vs API comparison.

Frequently asked questions

Does the cache guarantee the same answer?

No. Reusing input states is not the same as preserving a completed result. The answer depends on the continuation and generation parameters.

Does prefix caching speed up long output?

It primarily applies to reprocessing a matching input. If generation dominates, the overall effect may be small.

Why is the repeated request not faster?

Check the actual token match, whether state is present, eviction, routing, and the share of time spent in other stages. A short input may produce too little effect for the chosen measurement.

Can you turn on the cache and forget about it?

You need to monitor memory, load, and quality after changes. When the model, template, or prompt structure is updated, the previous result should not be assumed to remain valid automatically.

How Vladimir Lomtev's AI studio helps speed up your workflow

Vladimir Lomtev's AI studio can connect process auditing with data preparation, testing, and LLM deployment. For repeated context, that means identifying the real source of latency, checking the appropriate execution option, and integrating it with data access rules.

The first step is to choose one process, record the current latency, and define the criterion for a correct result. Discuss the task.

When caching is worth using

Use prefix caching as a verifiable optimization for a workload with a stable shared input. Evaluate time to first token, total latency, memory, and quality together. If the main problem is in another stage, continue diagnosing while keeping the comparison conditions reproducible.

Request an audit

Share your contact details and we will follow up.

← All articles

Comments (0)

Loading comments…

Leave a comment
No registration required

Book a strategy call
for agentic operations

Tell us which workflow you want to improve. We will map feasibility, risks, and the fastest MVP path.

By submitting, you agree to our privacy policy

Contacts

Global Operations

Serving U.S. clients remotely
with private cloud and on-prem options

Strategy calls by request

We respond after reviewing your workflow context.

info@agentsunrise.pro

For partnership inquiries

Have a proposal?

Write to us in messengers

© 2026 AgentSunrise