KV-Cache is a memory optimization technique that stores previously computed Key and Value tensors from the attention mechanism during autoregressive text generation. By caching these intermediate representations, the model avoids recomputing them for all prior tokens at each new generation step, transforming the quadratic computational complexity of attention into a linear operation per new token.
Glossary
KV-Cache

What is KV-Cache?
A memory mechanism in transformer models that stores the computed key and value tensors from previous tokens to avoid redundant computation during autoregressive text generation.
This mechanism is fundamental to achieving acceptable Time-to-First-Token (TTFT) and inter-token latency in production language model serving. The cache grows linearly with sequence length, making its memory footprint a critical constraint in continuous batching systems and a primary target for optimization through techniques like PagedAttention and quantized KV-Cache compression.
Core Characteristics of KV-Cache
The KV-Cache is a fundamental inference optimization that eliminates redundant computation by storing previously computed Key and Value tensors, transforming the quadratic cost of autoregressive generation into a linear memory operation.
Linearized Autoregressive Decoding
Without a cache, each new token forces a full recalculation of attention over the entire growing sequence, resulting in O(n²) time complexity. The KV-Cache stores the Key and Value projections from all prior tokens. When generating token t+1, the model only computes the Query, Key, and Value for the single new token and appends them to the cache. This reduces the computational cost of each step to O(n) linear time, making long-form generation feasible.
Memory Capacity Planning
The cache size scales linearly with four factors:
- Batch Size (B): Number of concurrent sequences
- Sequence Length (L): Total tokens generated
- Number of Layers (H): Transformer depth
- Hidden Dimension (D): Model width
Total memory = 2 * B * L * H * D * sizeof(dtype) bytes. For a 7B model generating 2048 tokens with a batch of 32 in FP16, the cache alone consumes over 2 GB of VRAM. This often exceeds the model weights themselves, making it the primary bottleneck for high-throughput serving.
Prefill vs. Decode Phase Disparity
The KV-Cache creates a distinct performance profile with two phases:
- Prefill Phase: The initial prompt is processed in parallel. This is compute-bound, saturating the GPU's matrix multiplication units as it computes the full cache for all input tokens simultaneously.
- Decode Phase: Each subsequent token is generated sequentially. This is memory-bound, as the entire cache must be loaded from VRAM to compute attention for a single new token. Optimization strategies must target these two bottlenecks differently.
Multi-Query and Grouped-Query Attention
Standard Multi-Head Attention (MHA) stores separate Key and Value tensors for each head, multiplying memory usage. Optimization variants reduce this:
- Multi-Query Attention (MQA): All heads share a single Key and Value tensor, drastically cutting cache size but potentially degrading quality.
- Grouped-Query Attention (GQA): A middle ground where heads are divided into groups sharing a single K and V. Models like Llama 2 70B use GQA to achieve near-MHA quality with a significantly smaller memory footprint, directly lowering the cost of the KV-Cache.
Cache Eviction and Quantization
For extremely long contexts, the cache can exceed available memory. Mitigation strategies include:
- Sliding Window Attention: Only the most recent W tokens' cache entries are retained, enforcing a fixed memory bound.
- KV-Cache Quantization: Storing Keys and Values in lower precision (e.g., INT8 or FP8 instead of FP16) reduces memory pressure by 2-4x with minimal accuracy loss.
- Token Dropping: Heuristics like StreamingLLM evict the cache entries for middle tokens while preserving initial 'attention sinks' and recent tokens to maintain coherence.
KV-Cache vs. Related Caching Mechanisms
A technical comparison of KV-Cache against other caching strategies used in retrieval-augmented generation and inference pipelines.
| Feature | KV-Cache | Semantic Cache | Embedding Cache | LRU Cache |
|---|---|---|---|---|
Primary Purpose | Stores key-value tensors from prior tokens to avoid recomputation during autoregressive decoding | Stores query-answer pairs based on semantic similarity to skip retrieval and generation | Persists computed vector embeddings to eliminate redundant neural network inference | Evicts least recently accessed items to maintain a bounded memory footprint for general data |
Data Stored | Multi-head attention key and value tensors per layer per token | Natural language query and its synthesized response | High-dimensional floating-point vector representations | Arbitrary byte sequences or objects |
Cache Key | Sequence position and layer index | Semantic vector of the user query | Hash of the raw text chunk | Exact object reference or string |
Hit Determination | Exact sequence prefix match | Cosine similarity above threshold | Exact hash match | Exact key match |
Typical Latency Reduction | 10-100x for decode step | Eliminates retrieval + generation entirely | Eliminates embedding model inference | Variable, depends on backend latency |
Memory Overhead | High; scales with batch size × sequence length × layers × hidden dim | Low; stores only text pairs | Medium; stores one vector per chunk | Configurable; bounded by max size |
Invalidation Trigger | Sequence divergence or max length exceeded | Semantic drift or TTL expiration | Source document update | Capacity eviction or TTL |
Primary Use Case | Transformer text generation | FAQ and conversational AI | Semantic search indexing | General-purpose application caching |
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Frequently Asked Questions
Explore the core concepts behind the Key-Value Cache, the critical memory mechanism that makes autoregressive text generation computationally feasible by eliminating redundant attention calculations.
A KV-Cache (Key-Value Cache) is a memory mechanism in transformer-based language models that stores the computed Key and Value tensors from previous tokens during autoregressive text generation. Without a KV-Cache, the model would recompute the attention scores for the entire sequence every time it generates a new token, leading to quadratic time complexity. The mechanism works by appending the new Key and Value projections for the latest token to the cached tensors, so the model only computes attention for the single new query token against all historical keys. This optimization reduces the computational complexity of generation from O(n²) to O(n), transforming a theoretical architecture into a practical inference engine.
Related Terms
Understanding the KV-Cache requires familiarity with the memory hierarchies, optimization techniques, and failure modes that govern its performance in production inference engines.
Time-to-First-Token (TTFT)
The elapsed time between a user submitting a query and the model generating the first output token. A populated KV-Cache eliminates the need to recompute the prompt's attention state, directly minimizing TTFT. In scenarios with long system prompts, a pre-computed KV-Cache can reduce TTFT from seconds to milliseconds by serving as a pre-filled prompt state.
Cache Eviction Policy
The algorithm determining which key-value pairs to discard when the KV-Cache exceeds its memory budget. Common strategies include:
- LRU (Least Recently Used): Evicts the least recently accessed sequences, ideal for stateless API serving.
- FIFO (First-In, First-Out): Simple queue-based eviction.
- TTL (Time-to-Live): Expires entries after a fixed duration. Poor eviction policies cause cache thrashing, where frequently reused prompts are repeatedly evicted and recomputed.
Cache Stampede
A cascading failure mode where a popular, shared KV-Cache entry (e.g., a long system prompt) expires or is evicted. This triggers a flood of concurrent requests to simultaneously recompute the attention state, overwhelming GPU compute and memory bandwidth. Mitigation strategies include probabilistic early recomputation (stochastically refreshing the cache before expiry) and locking to ensure only one process regenerates the entry.
Multi-Query Attention (MQA)
An attention variant where all attention heads share a single set of key and value projections while retaining distinct query projections. This drastically reduces the KV-Cache size by a factor equal to the number of heads. Grouped-Query Attention (GQA) is a compromise, using a small number of key-value groups. Models like Llama 2 70B and Mistral use GQA to balance memory savings with model quality.

About the author
Prasad Kumkar
CEO & MD, Inference Systems
Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.
His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us