Back to blog

LLM Caching Architecture: Reduce Latency and Cost with Prompt Caching (2026)

How to diagram LLM caching architecture. Covers KV cache, semantic cache, prompt caching (Claude, GPT), exact-match cache, and CDN-style response caching — with prompt templates to generate diagrams in seconds.

R
Ryan·Senior AI Engineer
·

LLM inference is expensive and slow. For most production AI applications, caching is the single highest-leverage optimization: it can cut latency by 80%+ and token costs by 50–90% on workloads with repeated or templated prompts. An LLM caching architecture diagram maps every caching layer in your inference pipeline — from on-device KV cache to CDN-level response caching — making cost attribution, cache hit paths, and invalidation logic explicit for engineering reviews and optimization work.

This guide covers the four main caching strategies for LLM systems, the components you need for each, and prompt templates to generate diagrams instantly.

The four layers of LLM caching

  • KV cache (model-internal): During autoregressive generation, the transformer's attention mechanism computes key-value pairs for every token in the context. The KV cache stores these tensors so that re-running the same prefix doesn't recompute attention. This is an implementation detail of the inference engine (vLLM, TensorRT-LLM, llama.cpp) but becomes architecturally relevant when you design batching strategies, prefix sharing, and multi-turn conversation routing.
  • Prompt prefix caching (provider-level): Cloud LLM providers (Anthropic Claude, OpenAI, Google Gemini) support caching a fixed system prompt prefix. Tokens in the cached prefix are billed at a steep discount (50–90% off input token price) and added to context with near-zero latency. Your architecture must route requests to the same provider endpoint, keep the prefix stable, and understand the TTL (typically 5–60 minutes depending on provider).
  • Semantic cache: An embedding-based cache that returns a stored LLM response when the incoming prompt is semantically similar to a previously cached prompt, even if not identical. Implemented with a vector database (pgvector, Qdrant, Redis with vector search). Useful for FAQ bots, support chatbots, and search applications where users rephrase the same question.
  • Exact-match / CDN response cache: For deterministic prompts (temperature=0, fixed system prompt, same user message), the full LLM response can be cached at the application layer (Redis, Memcached) or edge (Cloudflare Workers KV). Cache key is a hash of the full prompt. Ideal for code generation templates, product description generation, and document summarization at scale.

Prompt templates for LLM caching architectures

Multi-tier caching for a customer support chatbot

"An API gateway receives user chat messages. Before calling the LLM, three cache layers are checked in order: (1) Exact-match cache in Redis — key is SHA-256(system_prompt + user_message + session_id), TTL 24h. (2) Semantic cache in Qdrant — embed the user message with text-embedding-3-small, retrieve any stored response within cosine similarity 0.95. (3) On miss, call Claude claude-sonnet-4-6 with a cached system prompt (5,000 tokens of product documentation, marked as cache_control: ephemeral). The response streams back to the user and is written asynchronously to both the exact-match cache and the semantic cache. Cache metrics (hit rate, latency, cost saved) are exported to Datadog."

Prompt prefix caching for document analysis

"A legal document analysis service receives PDF uploads. Documents are converted to text and sent as the system prompt prefix to Claude, with cache_control set on the document content block. User questions are sent as the human turn. Because the same document is queried many times (lawyer reviews a contract clause by clause), the document tokens are cached after the first call — subsequent questions pay only for the new question tokens at input price plus cache read price (10% of normal). Cache TTL is 5 minutes; a heartbeat job re-warms the cache by resending the full prompt every 4 minutes while a document session is active. Cost savings per 100-page document analyzed 20 times: ~85% reduction in input token cost."

Semantic cache for a RAG-powered search

"A product search system uses RAG to answer natural-language queries. Before retrieval and LLM generation, the query is embedded and checked against a semantic cache in Redis Stack (vector similarity search with HNSW index). Cache threshold: cosine similarity ≥ 0.92. On cache hit, the stored answer (with source citations) is returned immediately — median latency drops from 2.1s to 45ms. On cache miss, the full RAG pipeline runs: retrieve top-5 chunks from Pinecone, rerank with Cohere, generate with GPT-4o. The response is stored in the semantic cache with a 6-hour TTL. Cache is invalidated by a Kafka consumer that listens to ProductUpdated events and deletes semantically similar cached answers about the changed product."

Self-hosted inference with KV cache prefix sharing

"A vLLM cluster runs Llama 3.1 70B on 4× A100 GPUs with tensor parallelism. All API requests share a common 2,000-token system prompt. vLLM's prefix caching is enabled: the KV cache for the system prompt prefix is computed once and reused across all concurrent requests that share the prefix, avoiding redundant GEMM operations and reducing time-to-first-token by 60% compared to recomputing the prefix on each request. Requests are routed by a load balancer that implements consistent hashing on the prefix hash, ensuring the same prefix always reaches the same GPU worker where its KV cache is warm. Cache eviction follows an LRU policy with 20GB of GPU HBM reserved for cached KV tensors."

LLM caching strategy comparison

Cache typeHit conditionLatency savingBest for
KV cache (inference engine)Same prefix tokens in same session50–70% TTFT reductionMulti-turn chat, long-context tasks
Provider prompt prefix cachingIdentical cached prefix blockNear-zero added latency for prefixLarge system prompts, repeated documents
Semantic cacheEmbedding similarity ≥ thresholdFull response latency → ~50msFAQ bots, search, support chatbots
Exact-match response cacheHash(full prompt) matchFull response latency → <5msDeterministic generation, batch jobs

What every LLM caching architecture diagram must show

  • Cache check sequence: Draw the decision tree explicitly — which cache is checked first, second, third. The order matters for both latency and cost: cheapest/fastest checks first.
  • Cache key definition: Annotate what inputs compose the cache key for each layer (exact hash, embedding vector + threshold, prefix block ID). This is where most caching bugs originate.
  • TTL and invalidation: Show TTL values and the invalidation trigger (event-based, time-based, manual flush). Without this, cached responses become stale and your AI gives wrong answers.
  • Write path: Show when and how cache misses are written back to each cache layer — synchronous vs. asynchronous, partial write (headers only) vs. full response.
  • Cost attribution: Annotate the token cost at each path: cache hit (near-zero), prefix cache hit (read price), full generation (input + output price). This lets you project ROI and explain cost to non-technical stakeholders.

Common LLM caching architecture mistakes

  • Using non-deterministic prompts with an exact-match cache — timestamp, session ID, or random seed in the prompt makes every request a cache miss
  • No similarity threshold calibration for semantic caches — too low (≤ 0.85) returns wrong answers; too high (≥ 0.99) misses obvious paraphrases
  • Caching PII-containing responses in a shared cache — user A's personalized answer should never be served to user B; scope cache keys to user IDs where needed
  • Forgetting streaming — most production LLM responses stream token by token; caching must either buffer the full stream before caching or store a streamable format
  • No cache warm-up for provider prefix caching — if the TTL expires between requests, you pay full price for prefix tokens on the next call; heartbeat pings prevent cold cache surprises

Frequently asked questions about LLM caching architecture

What is prompt caching and how does it differ from a response cache?

Prompt caching (as offered by Anthropic Claude and OpenAI) works at the inference level: the provider caches the internal KV tensors for a designated prompt prefix, so tokens in that prefix are processed at reduced cost and near-zero added latency on subsequent requests. A response cache is an application-level cache that stores the complete generated text and returns it directly without ever calling the LLM. Prompt caching reduces cost while still running generation; response caching eliminates generation entirely. The best architectures use both.

When should I use a semantic cache vs. an exact-match cache?

Use an exact-match cache when your prompts are fully deterministic — the same input always produces the same desirable output (batch processing, template-based generation, code scaffolding). Use a semantic cache when users rephrase the same underlying question in different ways — customer support, search, FAQ bots. In practice, most production systems layer both: exact-match check first (nanoseconds, zero cost), semantic check second (milliseconds, embedding cost), LLM call last.

How do I handle cache invalidation for LLM responses?

LLM response invalidation has three common patterns: (1) TTL-based — responses expire after a fixed duration (minutes to hours), appropriate when underlying data changes on a predictable schedule. (2) Event-driven — a Kafka or webhook event (product updated, knowledge base refreshed) triggers targeted cache deletion of affected entries. (3) Version-stamped — the system prompt version is part of the cache key; bumping the version automatically invalidates all old entries without a separate deletion step.

Related guides: RAG architecture diagrams, LLM architecture diagrams, LLMOps architecture, Redis architecture diagrams, and vector database architecture.

Ready to try it yourself?

Start Creating - Free