LLM API Caching: Strategies and Practical Implementation
Overview
Setting up caching for LLM API requests to reduce costs and delays: from simple hash-based caching to semantic caching with a vector database.
Why Cache LLM API
Duplicate requests to LLM API are the primary source of unnecessary costs. Typical scenarios include identical prompts in tests, repeated generation of responses on retries, and identical requests from different users. Caching allows returning a saved response without calling the API.
Caching Strategies
1. Exact Caching by Hash
The simplest approach: compute a hash from the full request (model, prompt, parameters) and store the response in Redis or a file.
import hashlib
import json
import redis
r = redis.Redis(host='localhost', port=6379, decode_responses=True)
def cache_key(model: str, prompt: str, params: dict) -> str:
raw = json.dumps({"model": model, "prompt": prompt, "params": params}, sort_keys=True)
return hashlib.sha256(raw.encode()).hexdigest()
def get_cached_response(model: str, prompt: str, params: dict):
key = cache_key(model, prompt, params)
cached = r.get(key)
if cached:
return json.loads(cached)
return None
def set_cached_response(model: str, prompt: str, params: dict, response: dict, ttl=3600):
key = cache_key(model, prompt, params)
r.setex(key, ttl, json.dumps(response))
2. Semantic Caching
Exact caching does not help with minor changes in formulation. Semantic caching uses embeddings: the request is converted into a vector, and the nearest neighbor is found in the vector database. If the cosine similarity is above a threshold, the saved response is returned.
from sentence_transformers import SentenceTransformer
import numpy as np
import chromadb
model = SentenceTransformer('paraphrase-multilingual-MiniLM-L12-v2')
client = chromadb.PersistentClient(path='./cache_db')
collection = client.get_or_create_collection('llm_cache')
def semantic_get(prompt: str, threshold=0.95):
emb = model.encode(prompt).tolist()
results = collection.query(query_embeddings=[emb], n_results=1)
if results['distances'] and results['distances'][0]:
distance = results['distances'][0][0]
similarity = 1 - distance
if similarity >= threshold:
return results['metadatas'][0][0]['response']
return None
def semantic_set(prompt: str, response: str):
emb = model.encode(prompt).tolist()
collection.add(ids=[str(abs(hash(prompt)))], embeddings=[emb], metadatas=[{"prompt": prompt, "response": response}])
3. Prompt Caching (Prefix Caching)
Some providers support caching a common prefix of the prompt. This is useful when the system prompt is large and rarely changes. In this case, resending the same prefix is cheaper.
# Example for OpenAI (supports prompt caching automatically)
import openai
client = openai.OpenAI()
# The same system prompt for many requests
system_prompt = "You are a technical support assistant. Respond briefly."
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": "How do I reset my password?"}
]
)
Cache Invalidation
Cache should expire. Main strategies:
- TTL (time-to-live) — the response lives for a limited time.
- Prompt versioning — when the prompt changes, the cache key changes.
- Manual cleanup — when the model or parameters change.
def invalidate_by_prefix(prefix: str):
keys = r.keys(f"{prefix}:*")
if keys:
r.delete(*keys)
Monitoring Efficiency
Track hit rate — the proportion of requests served from cache.
hits = 0
total = 0
def track(hit: bool):
global hits, total
total += 1
if hit:
hits += 1
print(f"Hit rate: {hits/total:.2%}")
Practical Recommendations
- Cache only idempotent requests: those where the response does not depend on time or state.
- Do not cache requests with high temperature (temperature > 0.7) as responses are variable.
- For semantic cache, choose a similarity threshold of 0.9–0.95 to avoid false matches.
- Store metadata: model, prompt version, timestamp — for auditing.
- Use Redis for distributed cache if the service runs on multiple instances.