Skip to content

Caching in LLM Applications: Strategies and Practices

Cover: Caching in LLM Applications: Strategies and Practices

Caching is one of the most effective ways to reduce the cost and latency of LLM applications. In this article, I will delve into the main caching strategies, their applicability, and potential pitfalls.

Why Cache LLM Requests

Each request to an LLM API incurs costs and time. Repeated requests with identical or similar content are common in production: users ask similar questions, systems generate the same system prompts, and RAG pipelines reprocess the same documents. Caching can reduce costs by 30–70% and decrease response time from seconds to milliseconds.

Strategy 1: Prompt Caching

Providers of LLM APIs (Anthropic, OpenAI, DeepSeek) support caching of prompt prefixes. If you send a request with the same beginning—such as a system prompt or large context—the provider does not recalculate it but retrieves it from the cache. This reduces costs and processing time.

# Example of using prompt caching in Anthropic API
import anthropic

client = anthropic.Anthropic()

response = client.messages.create(
    model="claude-3-5-sonnet-20241022",
    max_tokens=1024,
    system=[
        {
            "type": "text",
            "text": "You are a support assistant. Respond strictly according to the instructions.",
            "cache_control": {"type": "ephemeral"}
        }
    ],
    messages=[{"role": "user", "content": "How do I reset my password?"}]
)

The cache works automatically when the prefix matches. Important: only the beginning of the request is cached, so the system prompt and static parts of the context should come first.

Strategy 2: Semantic Cache of Responses

Prompt caching does not help when requests are formulated differently but mean the same thing. For such cases, I use a semantic cache: I calculate the embedding of the request, search for the nearest vector in the vector database, and if the cosine similarity is above the threshold, return the saved response.

import numpy as np
from sentence_transformers import SentenceTransformer

model = SentenceTransformer('paraphrase-multilingual-MiniLM-L12-v2')

# Hypothetical function for searching in vector DB
from vector_db import VectorDB

cache_db = VectorDB()

def get_cached_response(query: str, threshold: float = 0.92):
    query_embedding = model.encode(query)
    results = cache_db.search(query_embedding, top_k=1)
    if results and results[0].score >= threshold:
        return results[0].payload['response']
    return None

The similarity threshold is empirically determined. Too low a threshold leads to incorrect responses, too high a threshold to a low hit rate. For most tasks, I use a threshold of 0.90–0.95.

Strategy 3: Caching Embeddings

If you use embeddings for search or classification, calculating them also incurs costs. Caching embeddings is especially useful for static documents in RAG pipelines: the document is embedded once, not with each request.

# Embedding cache based on text hash
import hashlib
import redis

cache = redis.Redis()

def get_embedding(text: str):
    text_hash = hashlib.sha256(text.encode()).hexdigest()
    cached = cache.get(f"emb:{text_hash}")
    if cached:
        return np.frombuffer(cached, dtype=np.float32)
    embedding = model.encode(text)
    cache.set(f"emb:{text_hash}", embedding.tobytes())
    return embedding

Strategy 4: Caching RAG Results

In RAG systems, not only requests but also search results often repeat. If you have a limited corpus of documents, caching search results by request can significantly speed up the pipeline. I combine this with a semantic cache: first, I search for the answer in the cache, and only if there is a miss, I perform the full RAG cycle.

Comparison of Strategies

Strategy Cost Reduction Latency Reduction Implementation Complexity Risks
Prompt Caching High Medium Low None
Semantic Cache High High Medium Incorrect responses with low threshold
Embedding Cache Medium Medium Low Obsolescence of embeddings
RAG Results Cache Medium High Medium Obsolescence of documents

Cache Invalidation

The main problem of caching is invalidation. For prompt caching, invalidation is managed by the provider. For semantic caching, I use TTL (time-to-live) and versioning: when the system prompt or knowledge base changes, I increase the version of the cache key.

CACHE_VERSION = "v2"

def get_cache_key(query: str):
    return f"{CACHE_VERSION}:{hashlib.sha256(query.encode()).hexdigest()}"]

Practical Recommendations

  • Start with prompt caching—it is the simplest and safest option.
  • For semantic caching, use a separate vector database to avoid mixing with the main one.
  • Always log cache hit rate to monitor effectiveness.
  • For dynamic data (news, prices), use short TTL or disable caching.
  • Combine strategies: prompt caching for system prompts, semantic cache for repeated questions.

Caching is a mandatory element of production LLM applications. It not only saves budget but also improves user experience by reducing latency. More on related topics: context window, prompt cache, cost optimization.