AI Wisdom

Semantic Cache

Cache LLM responses by semantic similarity of the prompt rather than exact string match, reducing cost and latency for similar queries.

In this article

Problem: LLM API calls are expensive and slow. Traditional exact-match caching misses semantically identical queries phrased differently.

Solution: Embed each prompt using a fast embedding model, store the embedding alongside the cached response, and on new requests compare the query embedding against cached embeddings using cosine similarity. If the similarity exceeds a threshold (e.g., 0.95), return the cached response.

Implementation:

  1. Hash the system prompt + user message
  2. Generate embedding via a lightweight model (e.g., text-embedding-3-small)
  3. Query vector store for nearest match above threshold
  4. Cache hit โ†’ return stored response; cache miss โ†’ call LLM, store result + embedding

Trade-Offs:

  • โœ” Pro: 60-90% cost reduction for repetitive workloads (customer support, FAQ)
  • โœ” Pro: Sub-50ms response for cache hits vs 1-5s for LLM calls
  • โœ– Con: Stale responses if underlying data changes โ€” need TTL or invalidation
  • โœ– Con: Threshold tuning is domain-specific; too low = wrong answers, too high = low hit rate

When To Use: High-volume, repetitive query patterns โ€” chatbots, search, customer support. When to avoid: Creative/generative tasks, real-time data queries, low-volume APIs.

Related Articles

the ai gateway pattern

Discussion

Sign in to share your feedback and join the discussion.