<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom"><channel><title>Gptcache on lo0 — Tech Blog</title><link>https://blog.lo0.es/en/tags/gptcache/</link><description>Recent content in Gptcache on lo0 — Tech Blog</description><generator>Hugo -- gohugo.io</generator><language>en</language><lastBuildDate>Thu, 04 Jun 2026 08:00:00 +0200</lastBuildDate><atom:link href="https://blog.lo0.es/en/tags/gptcache/index.xml" rel="self" type="application/rss+xml"/><item><title>Semantic cache in RAG: the receptionist with a photographic memory</title><link>https://blog.lo0.es/en/posts/semantic-cache-rag-receptionist-photographic-memory/</link><pubDate>Thu, 04 Jun 2026 08:00:00 +0200</pubDate><guid>https://blog.lo0.es/en/posts/semantic-cache-rag-receptionist-photographic-memory/</guid><description>&lt;h2 id="tldr">TL;DR&lt;/h2>
&lt;p>In a RAG system with real traffic, 30–70% of queries are semantically equivalent to some earlier one even when the text differs. The semantic cache intercepts those queries ahead of the retriever and the LLM, returning the answer already computed if the cosine similarity with a previous query exceeds a threshold θ (typically 0.92–0.95). At 10,000 requests/day and a 45% hit rate, that amounts to not running 4,500 LLM generations: roughly 0.62 GPU hours saved every day on a cluster running Llama-3.1-70B. The fundamental trade-off is that a high θ gives more accurate answers but less saving; a low θ maximises saving but can return incorrect answers for subtly different queries.&lt;/p>
&lt;hr>
&lt;h2 id="the-analogy-the-receptionist-with-a-notebook">The analogy: the receptionist with a notebook&lt;/h2>
&lt;p>Picture the front desk of a 400-room hotel. Over the course of the day, the receptionist takes hundreds of questions. But if you look through the log book, you will see that 60% of those questions are variants of the same ten:&lt;/p>
&lt;ul>
&lt;li>&amp;ldquo;Where is the gym?&amp;rdquo;&lt;/li>
&lt;li>&amp;ldquo;What time is breakfast?&amp;rdquo;&lt;/li>
&lt;li>&amp;ldquo;Do you have parking?&amp;rdquo;&lt;/li>
&lt;li>&amp;ldquo;How do I connect to the WiFi?&amp;rdquo;&lt;/li>
&lt;/ul>
&lt;p>By the third day, the receptionist has built a mental notebook of answers. When someone asks &amp;ldquo;where can I go to exercise?&amp;rdquo;, they do not call the concierge (retrieval) or open the hotel&amp;rsquo;s 300-page internal manual (LLM): they look at the notebook, work out that the question is the same as &amp;ldquo;where is the gym?&amp;rdquo;, and answer in two seconds.&lt;/p>
&lt;p>But when someone asks &amp;ldquo;what time does the gym close &lt;strong>today&lt;/strong>?&amp;rdquo;, the receptionist knows the notebook cannot be trusted: the schedule may have changed because of a private event. They have to call the concierge.&lt;/p>
&lt;p>That is exactly the mechanism of a semantic cache:&lt;/p>
&lt;ul>
&lt;li>The &lt;strong>notebook&lt;/strong> is the cache store (Redis with a vector index, or a Qdrant collection).&lt;/li>
&lt;li>&lt;strong>Working out that &amp;ldquo;exercise&amp;rdquo; ≈ &amp;ldquo;gym&amp;rdquo;&lt;/strong> is the cosine similarity search with threshold θ.&lt;/li>
&lt;li>&lt;strong>Calling the concierge&lt;/strong> is retrieval over the corpus.&lt;/li>
&lt;li>&lt;strong>Consulting the manual&lt;/strong> is LLM generation.&lt;/li>
&lt;li>&lt;strong>&amp;ldquo;Today&amp;rdquo;&lt;/strong> is the temporal query signal that invalidates the cache.&lt;/li>
&lt;/ul>
&lt;p>The threshold θ is exactly what separates &amp;ldquo;where is it&amp;rdquo; (semantically the same) from &amp;ldquo;what time is it open today&amp;rdquo; (semantically different). It is not magic: it is vector arithmetic over learned representations.&lt;/p>
&lt;hr>
&lt;h2 id="the-problem-in-production">The problem in production&lt;/h2>
&lt;p>A typical RAG pipeline has three layers of latency and compute: embedding the query, vector search over the corpus, and generation with the LLM. In development, that cost is irrelevant. In production with 50 concurrent users, each of those layers scales linearly with the number of requests.&lt;/p>
&lt;p>The problem is that users ask the same questions over and over, with slightly different wording:&lt;/p>
&lt;table>
&lt;thead>
&lt;tr>
&lt;th>Original query&lt;/th>
&lt;th>Equivalent query&lt;/th>
&lt;/tr>
&lt;/thead>
&lt;tbody>
&lt;tr>
&lt;td>&amp;ldquo;How do I configure the agent?&amp;rdquo;&lt;/td>
&lt;td>&amp;ldquo;What is the process for configuring the agent?&amp;rdquo;&lt;/td>
&lt;/tr>
&lt;tr>
&lt;td>&amp;ldquo;error installing the dependency&amp;rdquo;&lt;/td>
&lt;td>&amp;ldquo;the dependency installation fails&amp;rdquo;&lt;/td>
&lt;/tr>
&lt;tr>
&lt;td>&amp;ldquo;what is an embedding?&amp;rdquo;&lt;/td>
&lt;td>&amp;ldquo;explain to me what embeddings are&amp;rdquo;&lt;/td>
&lt;/tr>
&lt;/tbody>
&lt;/table>
&lt;p>Running the full pipeline for each of these variants is pure waste. Empirical studies in technical support and corporate Q&amp;amp;A systems report that between 30% and 70% of a day&amp;rsquo;s queries are semantically redundant with respect to earlier queries from the same week.&lt;/p>
&lt;p>The query distribution in real systems follows a power law similar to the Zipf distribution: the 100 most frequent topics account for roughly 60% of total traffic. A well-calibrated cache captures exactly that concentration.&lt;/p>
&lt;hr>
&lt;h2 id="how-the-semantic-cache-works">How the semantic cache works&lt;/h2>
&lt;p>The full flow is shown in the diagram below. Let us describe it in prose first.&lt;/p>
&lt;p>When a new query $q$ arrives:&lt;/p>
&lt;ol>
&lt;li>
&lt;p>&lt;strong>Embedding the query&lt;/strong>: $q$ is embedded with the same model used to index the corpus. This is critical: if the corpus was indexed with &lt;code>text-embedding-3-large&lt;/code> and the cache uses a different embedder, the vector spaces are not comparable.&lt;/p>
&lt;/li>
&lt;li>
&lt;p>&lt;strong>Search in the cache store&lt;/strong>: an ANN (Approximate Nearest Neighbor) search is run over the vectors of previously cached queries. The most similar query $q^*$ and its cosine similarity $s$ are retrieved.&lt;/p>
&lt;/li>
&lt;li>
&lt;p>&lt;strong>Threshold decision&lt;/strong>:
&lt;/p>
$$
\text{answer} = \begin{cases} r^* &amp; \text{if } s(q, q^*) \geq \theta \\ \text{pipeline}(q) &amp; \text{if } s(q, q^*) &lt; \theta \end{cases}
$$
&lt;p>
where $r^*$ is the cached answer associated with $q^*$.&lt;/p>
&lt;/li>
&lt;li>
&lt;p>&lt;strong>On a miss&lt;/strong>: the full pipeline runs (retrieval + LLM). The generated answer is stored in the cache with a configurable TTL for future similar queries.&lt;/p>
&lt;/li>
&lt;/ol>
&lt;p>The cache store is not an ordinary key-value database. It is a vector index over the query embeddings, with the values being the generated answers. Each entry has the structure:&lt;/p>
&lt;pre tabindex="0">&lt;code>{vector: embed(q), response: r, ttl: T, metadata: {...}}
&lt;/code>&lt;/pre>&lt;h3 id="flow-diagram">Flow diagram&lt;/h3>
&lt;figure>
&lt;svg viewBox="0 0 760 420" xmlns="http://www.w3.org/2000/svg" role="img" aria-labelledby="sc-title sc-desc" style="width:100%;max-width:760px;font-family:system-ui,sans-serif;">
&lt;title id="sc-title">Semantic cache flow in a RAG pipeline&lt;/title>
&lt;desc id="sc-desc">Flow diagram showing how a query first passes through the semantic cache and, depending on whether there is a hit or a miss, either a cached answer is returned or the full retrieval and LLM pipeline runs.&lt;/desc>
&lt;!-- Background -->
&lt;rect width="760" height="420" fill="#f8f9fa" rx="8"/>
&lt;!-- Query input -->
&lt;rect x="20" y="180" width="110" height="52" rx="8" fill="#e3f2fd" stroke="#1565c0" stroke-width="1.5"/>
&lt;text x="75" y="202" text-anchor="middle" font-size="12" font-weight="600" fill="#0d47a1">Query&lt;/text>
&lt;text x="75" y="220" text-anchor="middle" font-size="11" fill="#1565c0">from the user&lt;/text>
&lt;!-- Arrow query → embedder -->
&lt;line x1="130" y1="206" x2="168" y2="206" stroke="#555" stroke-width="1.5" marker-end="url(#arr)"/>
&lt;!-- Embedder -->
&lt;rect x="168" y="180" width="100" height="52" rx="8" fill="#f3e5f5" stroke="#6a1b9a" stroke-width="1.5"/>
&lt;text x="218" y="202" text-anchor="middle" font-size="12" font-weight="600" fill="#4a148c">Embedder&lt;/text>
&lt;text x="218" y="220" text-anchor="middle" font-size="10" fill="#6a1b9a">same model&lt;/text>
&lt;!-- Arrow embedder → cache check -->
&lt;line x1="268" y1="206" x2="306" y2="206" stroke="#555" stroke-width="1.5" marker-end="url(#arr)"/>
&lt;!-- Cache check -->
&lt;rect x="306" y="172" width="120" height="68" rx="8" fill="#fff3e0" stroke="#e65100" stroke-width="1.5"/>
&lt;text x="366" y="196" text-anchor="middle" font-size="12" font-weight="600" fill="#bf360c">Cache check&lt;/text>
&lt;text x="366" y="212" text-anchor="middle" font-size="10" fill="#e65100">ANN search&lt;/text>
&lt;text x="366" y="226" text-anchor="middle" font-size="10" fill="#e65100">sim ≥ θ ?&lt;/text>
&lt;!-- HIT branch (top) -->
&lt;line x1="366" y1="172" x2="366" y2="120" stroke="#2e7d32" stroke-width="1.5" stroke-dasharray="5,3" marker-end="url(#arr-green)"/>
&lt;text x="380" y="148" font-size="10" fill="#2e7d32" font-weight="600">HIT&lt;/text>
&lt;rect x="296" y="68" width="140" height="48" rx="8" fill="#e8f5e9" stroke="#2e7d32" stroke-width="1.5"/>
&lt;text x="366" y="90" text-anchor="middle" font-size="12" font-weight="600" fill="#1b5e20">Answer&lt;/text>
&lt;text x="366" y="106" text-anchor="middle" font-size="11" fill="#2e7d32">cached → user&lt;/text>
&lt;!-- MISS branch (right) -->
&lt;line x1="426" y1="206" x2="466" y2="206" stroke="#c62828" stroke-width="1.5" stroke-dasharray="5,3" marker-end="url(#arr-red)"/>
&lt;text x="435" y="196" font-size="10" fill="#c62828" font-weight="600">MISS&lt;/text>
&lt;!-- Retriever -->
&lt;rect x="466" y="180" width="100" height="52" rx="8" fill="#e8eaf6" stroke="#283593" stroke-width="1.5"/>
&lt;text x="516" y="202" text-anchor="middle" font-size="12" font-weight="600" fill="#1a237e">Retriever&lt;/text>
&lt;text x="516" y="220" text-anchor="middle" font-size="10" fill="#283593">vector search&lt;/text>
&lt;!-- Arrow retriever → LLM -->
&lt;line x1="566" y1="206" x2="606" y2="206" stroke="#555" stroke-width="1.5" marker-end="url(#arr)"/>
&lt;!-- LLM -->
&lt;rect x="606" y="180" width="100" height="52" rx="8" fill="#fce4ec" stroke="#880e4f" stroke-width="1.5"/>
&lt;text x="656" y="202" text-anchor="middle" font-size="12" font-weight="600" fill="#880e4f">LLM&lt;/text>
&lt;text x="656" y="220" text-anchor="middle" font-size="10" fill="#ad1457">generation&lt;/text>
&lt;!-- Arrow LLM → new answer -->
&lt;line x1="656" y1="232" x2="656" y2="290" stroke="#555" stroke-width="1.5" marker-end="url(#arr)"/>
&lt;!-- New answer -->
&lt;rect x="596" y="290" width="120" height="48" rx="8" fill="#e8f5e9" stroke="#2e7d32" stroke-width="1.5"/>
&lt;text x="656" y="312" text-anchor="middle" font-size="12" font-weight="600" fill="#1b5e20">Answer&lt;/text>
&lt;text x="656" y="328" text-anchor="middle" font-size="11" fill="#2e7d32">new → user&lt;/text>
&lt;!-- Arrow new answer → store in cache -->
&lt;line x1="596" y1="314" x2="430" y2="314" stroke="#e65100" stroke-width="1.5" stroke-dasharray="4,3" marker-end="url(#arr-orange)"/>
&lt;text x="510" y="308" text-anchor="middle" font-size="10" fill="#e65100">store + TTL&lt;/text>
&lt;!-- Arrow from store to cache check (feedback) -->
&lt;line x1="366" y1="314" x2="366" y2="240" stroke="#e65100" stroke-width="1.5" stroke-dasharray="4,3" marker-end="url(#arr-orange)"/>
&lt;!-- Cache store label -->
&lt;rect x="296" y="340" width="140" height="48" rx="8" fill="#fff8e1" stroke="#f57f17" stroke-width="1.5"/>
&lt;text x="366" y="361" text-anchor="middle" font-size="11" font-weight="600" fill="#e65100">Cache store&lt;/text>
&lt;text x="366" y="377" text-anchor="middle" font-size="10" fill="#f57f17">Redis / Qdrant&lt;/text>
&lt;line x1="366" y1="340" x2="366" y2="314" stroke="#e65100" stroke-width="1.5" stroke-dasharray="4,3" marker-end="url(#arr-orange)"/>
&lt;!-- Legend -->
&lt;text x="20" y="390" font-size="10" fill="#555">— — — HIT path&lt;/text>
&lt;rect x="20" y="397" width="30" height="2" fill="#2e7d32"/>
&lt;text x="60" y="410" font-size="10" fill="#2e7d32">cache hit&lt;/text>
&lt;rect x="110" y="397" width="30" height="2" fill="#c62828"/>
&lt;text x="150" y="410" font-size="10" fill="#c62828">cache miss&lt;/text>
&lt;rect x="200" y="397" width="30" height="2" fill="#e65100"/>
&lt;text x="240" y="410" font-size="10" fill="#e65100">store / feedback&lt;/text>
&lt;!-- Arrow markers -->
&lt;defs>
&lt;marker id="arr" markerWidth="8" markerHeight="8" refX="6" refY="3" orient="auto">
&lt;path d="M0,0 L0,6 L8,3 z" fill="#555"/>
&lt;/marker>
&lt;marker id="arr-green" markerWidth="8" markerHeight="8" refX="6" refY="3" orient="auto">
&lt;path d="M0,0 L0,6 L8,3 z" fill="#2e7d32"/>
&lt;/marker>
&lt;marker id="arr-red" markerWidth="8" markerHeight="8" refX="6" refY="3" orient="auto">
&lt;path d="M0,0 L0,6 L8,3 z" fill="#c62828"/>
&lt;/marker>
&lt;marker id="arr-orange" markerWidth="8" markerHeight="8" refX="6" refY="3" orient="auto">
&lt;path d="M0,0 L0,6 L8,3 z" fill="#e65100"/>
&lt;/marker>
&lt;/defs>
&lt;/svg>
&lt;figcaption>The semantic cache flow as middleware between the gateway and the retriever. Cache hits skip the vector search over the corpus and the LLM generation entirely.&lt;/figcaption>
&lt;/figure>
&lt;hr>
&lt;h2 id="the-threshold-θ-and-its-trade-off">The threshold θ and its trade-off&lt;/h2>
&lt;p>The threshold θ is the most sensitive parameter in the system. It works exactly like the receptionist&amp;rsquo;s recognition threshold: if it is too demanding, it will only identify textually identical questions and the notebook will not be much use. If it is too lax, it will return the answer to &amp;ldquo;where is the gym?&amp;rdquo; to someone who asked &amp;ldquo;what time does the gym close?&amp;rdquo;.&lt;/p>
&lt;p>The cosine similarity between two vectors $\mathbf{a}$ and $\mathbf{b}$ is:&lt;/p>
$$
s(\mathbf{a}, \mathbf{b}) = \frac{\mathbf{a} \cdot \mathbf{b}}{\|\mathbf{a}\| \cdot \|\mathbf{b}\|}
$$
&lt;p>For prose text (Spanish or English), modern embedders such as &lt;code>text-embedding-3-large&lt;/code> or &lt;code>nomic-embed-text&lt;/code> assign cosine similarities of around 0.90–0.96 to semantically equivalent paraphrases and similarities of 0.75–0.88 to related but non-equivalent queries.&lt;/p>
&lt;p>The cache quality metric is not just hit rate: it is &lt;strong>precision@cache&lt;/strong>, defined as the fraction of cached answers that remain correct for the new query. A cached answer is &amp;ldquo;correct&amp;rdquo; if an evaluator (another LLM, or metrics such as BERTScore) judges it equivalent to the one the full pipeline would have generated for that specific query.&lt;/p>
&lt;table>
&lt;thead>
&lt;tr>
&lt;th>θ&lt;/th>
&lt;th>Estimated hit rate&lt;/th>
&lt;th>Estimated precision@cache&lt;/th>
&lt;th>Effective saving&lt;/th>
&lt;/tr>
&lt;/thead>
&lt;tbody>
&lt;tr>
&lt;td>0.85&lt;/td>
&lt;td>~65%&lt;/td>
&lt;td>~72%&lt;/td>
&lt;td>~47%&lt;/td>
&lt;/tr>
&lt;tr>
&lt;td>0.90&lt;/td>
&lt;td>~55%&lt;/td>
&lt;td>~85%&lt;/td>
&lt;td>~47%&lt;/td>
&lt;/tr>
&lt;tr>
&lt;td>0.92&lt;/td>
&lt;td>~48%&lt;/td>
&lt;td>~91%&lt;/td>
&lt;td>~44%&lt;/td>
&lt;/tr>
&lt;tr>
&lt;td>&lt;strong>0.93&lt;/strong>&lt;/td>
&lt;td>&lt;strong>~45%&lt;/strong>&lt;/td>
&lt;td>&lt;strong>~94%&lt;/strong>&lt;/td>
&lt;td>&lt;strong>~42%&lt;/strong>&lt;/td>
&lt;/tr>
&lt;tr>
&lt;td>0.95&lt;/td>
&lt;td>~35%&lt;/td>
&lt;td>~98%&lt;/td>
&lt;td>~34%&lt;/td>
&lt;/tr>
&lt;tr>
&lt;td>0.97&lt;/td>
&lt;td>~18%&lt;/td>
&lt;td>~99.5%&lt;/td>
&lt;td>~18%&lt;/td>
&lt;/tr>
&lt;/tbody>
&lt;/table>
&lt;p>The effective saving is defined as $\text{hit rate} \times \text{precision@cache}$, since a hit with an incorrect answer is not a saving: it is an error that can cost more in lost trust than what was saved in GPU.&lt;/p>
&lt;p>The &lt;strong>empirical sweet spot&lt;/strong> for most corporate Q&amp;amp;A applications in Spanish or English lies between θ = 0.92 and θ = 0.95. In highly specialised domains where small nuances change the answer (medicine, law, finance), θ ≥ 0.95 is advisable.&lt;/p>
&lt;hr>
&lt;h2 id="the-arithmetic-of-the-saving">The arithmetic of the saving&lt;/h2>
&lt;p>Let us put concrete numbers on a real system.&lt;/p>
&lt;p>&lt;strong>Base configuration:&lt;/strong>&lt;/p>
&lt;ul>
&lt;li>10,000 requests/day&lt;/li>
&lt;li>Technical corpus of 1 million chunks in a Qdrant index&lt;/li>
&lt;li>LLM: Llama-3.1-70B on 4×H100 SXM (320 GB, NVLink)&lt;/li>
&lt;li>Average answer: 200 output tokens&lt;/li>
&lt;li>LLM throughput on this hardware: ~400 tokens/s/GPU with batching (continuous batching enabled, see &lt;a href="https://blog.lo0.es/en/posts/continuous-batching-orca-vllm-chunked-prefill-goodput/">continuous-batching-fundamentos&lt;/a>)&lt;/li>
&lt;/ul>
&lt;p>&lt;strong>Cost of a request without cache:&lt;/strong>&lt;/p>
&lt;p>Embedding the query takes ~2 ms on a GPU. The ANN vector search over 1 M chunks in Qdrant takes ~5 ms (measured empirically with HNSW, ef=128). Generating 200 tokens at 400 tok/s in total (4 GPUs) comes to:&lt;/p>
$$
t_{\text{LLM}} = \frac{200 \text{ tokens}}{400 \text{ tok/s}} = 0.5 \text{ s per request}
$$
&lt;p>If 10,000 requests reach the LLM in a day, the total GPU time spent on generation is:&lt;/p>
$$
T_{\text{GPU}} = 10{,}000 \times 0.5 \text{ s} = 5{,}000 \text{ s} \approx 1.38 \text{ GPU hours per day}
$$
&lt;p>&lt;strong>With a semantic cache at θ = 0.93 and a hit rate of ~45%:&lt;/strong>&lt;/p>
&lt;p>Only 5,500 requests (55%) reach the LLM:&lt;/p>
$$
T_{\text{GPU,cache}} = 5{,}500 \times 0.5 \text{ s} = 2{,}750 \text{ s} \approx 0.76 \text{ GPU hours per day}
$$
&lt;p>&lt;strong>Saving:&lt;/strong>&lt;/p>
$$
\Delta T_{\text{GPU}} = 1.38 - 0.76 = 0.62 \text{ GPU hours/day}
$$
&lt;p>In inference compute, this amounts roughly to being able to serve 45% more users without adding hardware, or cutting inference costs by 45% if you work with external APIs billed per token.&lt;/p>
&lt;p>The cost of the semantic cache itself (embedding the query + ANN search over the cache store) is ~7 ms per request, negligible against the 500 ms of generation avoided on hits.&lt;/p>
&lt;p>&lt;strong>Zipf distribution of topics:&lt;/strong>&lt;/p>
&lt;p>The reason it works is the Zipf distribution of traffic. If we number topics by frequency (topic 1 = most frequent), the frequency of topic $k$ is proportional to $1/k$. With 1,000 distinct topics:&lt;/p>
$$
\text{fraction of traffic covered by top-}N = \frac{\sum_{k=1}^{N} 1/k}{\sum_{k=1}^{1000} 1/k} \approx \frac{\ln N}{\ln 1000} = \frac{\ln N}{6.9}
$$
&lt;p>For the top-100 topics: $\ln(100)/6.9 \approx 4.6/6.9 \approx 67\%$ of traffic. The cache does not need to cover every topic: it captures 67% of traffic while covering only 10% of the topics.&lt;/p>
&lt;hr>
&lt;h2 id="oss-stack-2026">OSS stack 2026&lt;/h2>
&lt;h3 id="gptcache">GPTCache&lt;/h3>
&lt;p>&lt;a href="https://github.com/zilliztech/GPTCache">GPTCache&lt;/a> is the reference library for a standalone semantic cache. Its architecture is modular:&lt;/p>
&lt;ul>
&lt;li>&lt;strong>Embedder&lt;/strong>: ONNX Runtime with converted models (&lt;code>onnx/all-MiniLM-L6-v2&lt;/code> by default), with no GPU dependency for the cache layer.&lt;/li>
&lt;li>&lt;strong>Vector store&lt;/strong>: Faiss (local), Milvus, or Qdrant.&lt;/li>
&lt;li>&lt;strong>Scalar store&lt;/strong>: SQLite (development) or Redis (production) for metadata, TTL, and answers.&lt;/li>
&lt;li>&lt;strong>Similarity evaluation&lt;/strong>: cosine by default, configurable.&lt;/li>
&lt;/ul>
&lt;p>Minimal configuration in Python:&lt;/p>
&lt;div class="highlight">&lt;pre tabindex="0" class="chroma">&lt;code class="language-python" data-lang="python">&lt;span class="line">&lt;span class="cl">&lt;span class="kn">from&lt;/span> &lt;span class="nn">gptcache&lt;/span> &lt;span class="kn">import&lt;/span> &lt;span class="n">cache&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl">&lt;span class="kn">from&lt;/span> &lt;span class="nn">gptcache.adapter&lt;/span> &lt;span class="kn">import&lt;/span> &lt;span class="n">openai&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl">&lt;span class="kn">from&lt;/span> &lt;span class="nn">gptcache.embedding&lt;/span> &lt;span class="kn">import&lt;/span> &lt;span class="n">Onnx&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl">&lt;span class="kn">from&lt;/span> &lt;span class="nn">gptcache.manager&lt;/span> &lt;span class="kn">import&lt;/span> &lt;span class="n">CacheBase&lt;/span>&lt;span class="p">,&lt;/span> &lt;span class="n">VectorBase&lt;/span>&lt;span class="p">,&lt;/span> &lt;span class="n">get_data_manager&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl">&lt;span class="kn">from&lt;/span> &lt;span class="nn">gptcache.similarity_evaluation.distance&lt;/span> &lt;span class="kn">import&lt;/span> &lt;span class="n">SearchDistanceEvaluation&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl">
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl">&lt;span class="n">onnx&lt;/span> &lt;span class="o">=&lt;/span> &lt;span class="n">Onnx&lt;/span>&lt;span class="p">()&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl">&lt;span class="n">data_manager&lt;/span> &lt;span class="o">=&lt;/span> &lt;span class="n">get_data_manager&lt;/span>&lt;span class="p">(&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl"> &lt;span class="n">CacheBase&lt;/span>&lt;span class="p">(&lt;/span>&lt;span class="s2">&amp;#34;redis&amp;#34;&lt;/span>&lt;span class="p">,&lt;/span> &lt;span class="n">url&lt;/span>&lt;span class="o">=&lt;/span>&lt;span class="s2">&amp;#34;redis://localhost:6379&amp;#34;&lt;/span>&lt;span class="p">),&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl"> &lt;span class="n">VectorBase&lt;/span>&lt;span class="p">(&lt;/span>&lt;span class="s2">&amp;#34;qdrant&amp;#34;&lt;/span>&lt;span class="p">,&lt;/span> &lt;span class="n">host&lt;/span>&lt;span class="o">=&lt;/span>&lt;span class="s2">&amp;#34;localhost&amp;#34;&lt;/span>&lt;span class="p">,&lt;/span> &lt;span class="n">collection_name&lt;/span>&lt;span class="o">=&lt;/span>&lt;span class="s2">&amp;#34;query_cache&amp;#34;&lt;/span>&lt;span class="p">)&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl">&lt;span class="p">)&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl">&lt;span class="n">cache&lt;/span>&lt;span class="o">.&lt;/span>&lt;span class="n">init&lt;/span>&lt;span class="p">(&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl"> &lt;span class="n">embedding_func&lt;/span>&lt;span class="o">=&lt;/span>&lt;span class="n">onnx&lt;/span>&lt;span class="o">.&lt;/span>&lt;span class="n">to_embeddings&lt;/span>&lt;span class="p">,&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl"> &lt;span class="n">data_manager&lt;/span>&lt;span class="o">=&lt;/span>&lt;span class="n">data_manager&lt;/span>&lt;span class="p">,&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl"> &lt;span class="n">similarity_evaluation&lt;/span>&lt;span class="o">=&lt;/span>&lt;span class="n">SearchDistanceEvaluation&lt;/span>&lt;span class="p">(),&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl">&lt;span class="p">)&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl">&lt;span class="n">cache&lt;/span>&lt;span class="o">.&lt;/span>&lt;span class="n">set_openai_key&lt;/span>&lt;span class="p">()&lt;/span>
&lt;/span>&lt;/span>&lt;/code>&lt;/pre>&lt;/div>&lt;p>GPTCache intercepts calls to the OpenAI API (or to compatible proxies) transparently. The TTL is configured at the &lt;code>data_manager&lt;/code> level.&lt;/p>
&lt;h3 id="meancache">MeanCache&lt;/h3>
&lt;p>&lt;a href="https://arxiv.org/abs/2403.02694">MeanCache&lt;/a> (2024) extends GPTCache to multi-turn conversations. The problem with standard GPTCache is that in dialogue the &amp;ldquo;relevant&amp;rdquo; query is not just the last message but the whole context window. MeanCache computes the query embedding as the weighted mean of the embeddings of the last $k$ turns:&lt;/p>
$$
\mathbf{e}_{\text{query}} = \frac{\sum_{i=1}^{k} w_i \cdot \mathbf{e}_{q_i}}{\sum_{i=1}^{k} w_i}
$$
&lt;p>where $w_i$ decreases with the age of the turn. This reduces false positives in dialogues where the topic keeps shifting.&lt;/p>
&lt;h3 id="qdrant-as-a-dual-cache-store">Qdrant as a dual cache store&lt;/h3>
&lt;p>If the RAG corpus is already in Qdrant, you can use the same instance with a &lt;strong>separate collection&lt;/strong> for the cache. The advantages are operational: a single service to manage, the same backup and monitoring infrastructure.&lt;/p>
&lt;p>The cache collection uses &lt;code>payload filters&lt;/code> to implement TTL:&lt;/p>
&lt;div class="highlight">&lt;pre tabindex="0" class="chroma">&lt;code class="language-python" data-lang="python">&lt;span class="line">&lt;span class="cl">&lt;span class="kn">from&lt;/span> &lt;span class="nn">qdrant_client&lt;/span> &lt;span class="kn">import&lt;/span> &lt;span class="n">QdrantClient&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl">&lt;span class="kn">from&lt;/span> &lt;span class="nn">qdrant_client.models&lt;/span> &lt;span class="kn">import&lt;/span> &lt;span class="n">Filter&lt;/span>&lt;span class="p">,&lt;/span> &lt;span class="n">FieldCondition&lt;/span>&lt;span class="p">,&lt;/span> &lt;span class="n">Range&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl">&lt;span class="kn">import&lt;/span> &lt;span class="nn">time&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl">
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl">&lt;span class="n">client&lt;/span> &lt;span class="o">=&lt;/span> &lt;span class="n">QdrantClient&lt;/span>&lt;span class="p">(&lt;/span>&lt;span class="s2">&amp;#34;localhost&amp;#34;&lt;/span>&lt;span class="p">,&lt;/span> &lt;span class="n">port&lt;/span>&lt;span class="o">=&lt;/span>&lt;span class="mi">6333&lt;/span>&lt;span class="p">)&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl">
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl">&lt;span class="c1"># Search the cache with a TTL filter&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl">&lt;span class="n">hits&lt;/span> &lt;span class="o">=&lt;/span> &lt;span class="n">client&lt;/span>&lt;span class="o">.&lt;/span>&lt;span class="n">search&lt;/span>&lt;span class="p">(&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl"> &lt;span class="n">collection_name&lt;/span>&lt;span class="o">=&lt;/span>&lt;span class="s2">&amp;#34;semantic_cache&amp;#34;&lt;/span>&lt;span class="p">,&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl"> &lt;span class="n">query_vector&lt;/span>&lt;span class="o">=&lt;/span>&lt;span class="n">query_embedding&lt;/span>&lt;span class="p">,&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl"> &lt;span class="n">query_filter&lt;/span>&lt;span class="o">=&lt;/span>&lt;span class="n">Filter&lt;/span>&lt;span class="p">(&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl"> &lt;span class="n">must&lt;/span>&lt;span class="o">=&lt;/span>&lt;span class="p">[&lt;/span>&lt;span class="n">FieldCondition&lt;/span>&lt;span class="p">(&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl"> &lt;span class="n">key&lt;/span>&lt;span class="o">=&lt;/span>&lt;span class="s2">&amp;#34;expires_at&amp;#34;&lt;/span>&lt;span class="p">,&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl"> &lt;span class="nb">range&lt;/span>&lt;span class="o">=&lt;/span>&lt;span class="n">Range&lt;/span>&lt;span class="p">(&lt;/span>&lt;span class="n">gt&lt;/span>&lt;span class="o">=&lt;/span>&lt;span class="n">time&lt;/span>&lt;span class="o">.&lt;/span>&lt;span class="n">time&lt;/span>&lt;span class="p">())&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl"> &lt;span class="p">)]&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl"> &lt;span class="p">),&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl"> &lt;span class="n">limit&lt;/span>&lt;span class="o">=&lt;/span>&lt;span class="mi">1&lt;/span>&lt;span class="p">,&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl"> &lt;span class="n">score_threshold&lt;/span>&lt;span class="o">=&lt;/span>&lt;span class="mf">0.93&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl">&lt;span class="p">)&lt;/span>
&lt;/span>&lt;/span>&lt;/code>&lt;/pre>&lt;/div>&lt;p>You have to run a periodic cleanup of expired entries, since Qdrant has no native TTL (unlike Redis).&lt;/p>
&lt;h3 id="langfuse-for-traceability">Langfuse for traceability&lt;/h3>
&lt;p>&lt;a href="https://langfuse.com">Langfuse&lt;/a> is the OSS standard for LLM pipeline observability (see &lt;a href="https://blog.lo0.es/en/posts/llm-tracing-opentelemetry-genai/">tracing-llm-otel-genai&lt;/a>). Every request should be tagged with whether it was a cache hit or a miss:&lt;/p>
&lt;div class="highlight">&lt;pre tabindex="0" class="chroma">&lt;code class="language-python" data-lang="python">&lt;span class="line">&lt;span class="cl">&lt;span class="kn">from&lt;/span> &lt;span class="nn">langfuse&lt;/span> &lt;span class="kn">import&lt;/span> &lt;span class="n">Langfuse&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl">&lt;span class="kn">from&lt;/span> &lt;span class="nn">langfuse.decorators&lt;/span> &lt;span class="kn">import&lt;/span> &lt;span class="n">observe&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl">
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl">&lt;span class="n">langfuse&lt;/span> &lt;span class="o">=&lt;/span> &lt;span class="n">Langfuse&lt;/span>&lt;span class="p">()&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl">
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl">&lt;span class="nd">@observe&lt;/span>&lt;span class="p">()&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl">&lt;span class="k">def&lt;/span> &lt;span class="nf">process_query&lt;/span>&lt;span class="p">(&lt;/span>&lt;span class="n">query&lt;/span>&lt;span class="p">:&lt;/span> &lt;span class="nb">str&lt;/span>&lt;span class="p">)&lt;/span> &lt;span class="o">-&amp;gt;&lt;/span> &lt;span class="nb">dict&lt;/span>&lt;span class="p">:&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl"> &lt;span class="n">cache_result&lt;/span> &lt;span class="o">=&lt;/span> &lt;span class="n">semantic_cache&lt;/span>&lt;span class="o">.&lt;/span>&lt;span class="n">lookup&lt;/span>&lt;span class="p">(&lt;/span>&lt;span class="n">query&lt;/span>&lt;span class="p">)&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl"> &lt;span class="k">if&lt;/span> &lt;span class="n">cache_result&lt;/span>&lt;span class="p">:&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl"> &lt;span class="n">langfuse&lt;/span>&lt;span class="o">.&lt;/span>&lt;span class="n">update_current_observation&lt;/span>&lt;span class="p">(&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl"> &lt;span class="n">metadata&lt;/span>&lt;span class="o">=&lt;/span>&lt;span class="p">{&lt;/span>&lt;span class="s2">&amp;#34;cache_hit&amp;#34;&lt;/span>&lt;span class="p">:&lt;/span> &lt;span class="kc">True&lt;/span>&lt;span class="p">,&lt;/span> &lt;span class="s2">&amp;#34;cache_score&amp;#34;&lt;/span>&lt;span class="p">:&lt;/span> &lt;span class="n">cache_result&lt;/span>&lt;span class="o">.&lt;/span>&lt;span class="n">score&lt;/span>&lt;span class="p">}&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl"> &lt;span class="p">)&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl"> &lt;span class="k">return&lt;/span> &lt;span class="n">cache_result&lt;/span>&lt;span class="o">.&lt;/span>&lt;span class="n">response&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl"> &lt;span class="c1"># full pipeline...&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl"> &lt;span class="n">langfuse&lt;/span>&lt;span class="o">.&lt;/span>&lt;span class="n">update_current_observation&lt;/span>&lt;span class="p">(&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl"> &lt;span class="n">metadata&lt;/span>&lt;span class="o">=&lt;/span>&lt;span class="p">{&lt;/span>&lt;span class="s2">&amp;#34;cache_hit&amp;#34;&lt;/span>&lt;span class="p">:&lt;/span> &lt;span class="kc">False&lt;/span>&lt;span class="p">}&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl"> &lt;span class="p">)&lt;/span>
&lt;/span>&lt;/span>&lt;/code>&lt;/pre>&lt;/div>&lt;p>With this metadata, Langfuse lets you compute the real hit rate, the distribution of similarity scores, and detect whether the threshold θ needs adjusting.&lt;/p>
&lt;hr>
&lt;h2 id="on-premise-hardware-a-reference-configuration">On-premise hardware: a reference configuration&lt;/h2>
&lt;p>For an on-premise deployment with this stack, a suitable configuration for RAG with a semantic cache is:&lt;/p>
&lt;p>&lt;strong>Inference node:&lt;/strong> 4×H100 SXM (320 GB NVLink in total) for Llama-3.1-70B in FP8. Throughput ~400 tok/s in generation with continuous batching (vLLM or TGI).&lt;/p>
&lt;p>&lt;strong>Vector services node:&lt;/strong> CPU with 256 GB RAM. Qdrant for the corpus (1–10 M chunks) and for the cache store (up to 500K entries in memory). Redis 7.x for metadata and an exact-match cache as a first layer.&lt;/p>
&lt;p>&lt;strong>Embedding node:&lt;/strong> CPU or a mid-range GPU (A10G). The cache embedder can run on ONNX Runtime on CPU with no perceptible impact on latency (~2 ms per embedding).&lt;/p>
&lt;p>Separating the cache store from the corpus matters: the corpus holds millions of chunks with large HNSW indexes; the cache store holds at most tens of thousands of queries with a much smaller index and search times of 1–2 ms.&lt;/p>
&lt;hr>
&lt;h2 id="cases-where-the-cache-fails">Cases where the cache fails&lt;/h2>
&lt;p>The receptionist with a notebook fails in three well-defined scenarios:&lt;/p>
&lt;h3 id="1-queries-with-a-temporal-context">1. Queries with a temporal context&lt;/h3>
&lt;p>&amp;ldquo;What is the current status of the incident?&amp;rdquo; or &amp;ldquo;What changed in the latest release?&amp;rdquo; are questions whose correct answer changes over time. A cache with a 24-hour TTL could return stale information.&lt;/p>
&lt;p>The solution is to detect temporal markers in the query (regular expressions over &amp;ldquo;today&amp;rdquo;, &amp;ldquo;now&amp;rdquo;, &amp;ldquo;current&amp;rdquo;, &amp;ldquo;latest&amp;rdquo;, &amp;ldquo;yesterday&amp;rdquo;, and their Spanish equivalents) and force a cache miss for these queries, whatever the similarity score.&lt;/p>
&lt;h3 id="2-personalised-queries-over-private-data">2. Personalised queries over private data&lt;/h3>
&lt;p>If the RAG has access to user data (account history, private documents), two different users asking the same question must get different answers. A shared cache that ignores user context is a privacy risk.&lt;/p>
&lt;p>The solution is a cache partitioned by &lt;code>user_id&lt;/code> or &lt;code>tenant_id&lt;/code>. This lowers the hit rate (each user&amp;rsquo;s cache is smaller) but it is the only safe option in multi-tenant architectures.&lt;/p>
&lt;h3 id="3-ttl-and-a-stale-corpus">3. TTL and a stale corpus&lt;/h3>
&lt;p>When the corpus is updated (new documents are ingested, errors are corrected), cached answers can go out of date. A fixed TTL (24–48 hours) mitigates the problem but does not remove it.&lt;/p>
&lt;p>For corpora with frequent updates, the solution is an active invalidation mechanism: when the corpus is updated in Qdrant, a job runs that identifies which cache entries might be affected (by semantic overlap with the updated chunks) and deletes them. This is the &amp;ldquo;selective cache invalidation&amp;rdquo; mentioned in the section on topics not covered.&lt;/p>
&lt;hr>
&lt;h2 id="integration-into-the-pipeline-as-middleware">Integration into the pipeline as middleware&lt;/h2>
&lt;p>The semantic cache is implemented as middleware between the API gateway and the retriever. It does not change the API contract: the client still sends queries and receives answers in the same format.&lt;/p>
&lt;div class="highlight">&lt;pre tabindex="0" class="chroma">&lt;code class="language-python" data-lang="python">&lt;span class="line">&lt;span class="cl">&lt;span class="k">class&lt;/span> &lt;span class="nc">SemanticCacheMiddleware&lt;/span>&lt;span class="p">:&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl"> &lt;span class="k">def&lt;/span> &lt;span class="fm">__init__&lt;/span>&lt;span class="p">(&lt;/span>&lt;span class="bp">self&lt;/span>&lt;span class="p">,&lt;/span> &lt;span class="n">cache_store&lt;/span>&lt;span class="p">,&lt;/span> &lt;span class="n">retriever&lt;/span>&lt;span class="p">,&lt;/span> &lt;span class="n">llm&lt;/span>&lt;span class="p">,&lt;/span> &lt;span class="n">threshold&lt;/span>&lt;span class="o">=&lt;/span>&lt;span class="mf">0.93&lt;/span>&lt;span class="p">):&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl"> &lt;span class="bp">self&lt;/span>&lt;span class="o">.&lt;/span>&lt;span class="n">cache&lt;/span> &lt;span class="o">=&lt;/span> &lt;span class="n">cache_store&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl"> &lt;span class="bp">self&lt;/span>&lt;span class="o">.&lt;/span>&lt;span class="n">retriever&lt;/span> &lt;span class="o">=&lt;/span> &lt;span class="n">retriever&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl"> &lt;span class="bp">self&lt;/span>&lt;span class="o">.&lt;/span>&lt;span class="n">llm&lt;/span> &lt;span class="o">=&lt;/span> &lt;span class="n">llm&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl"> &lt;span class="bp">self&lt;/span>&lt;span class="o">.&lt;/span>&lt;span class="n">threshold&lt;/span> &lt;span class="o">=&lt;/span> &lt;span class="n">threshold&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl">
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl"> &lt;span class="k">async&lt;/span> &lt;span class="k">def&lt;/span> &lt;span class="nf">process&lt;/span>&lt;span class="p">(&lt;/span>&lt;span class="bp">self&lt;/span>&lt;span class="p">,&lt;/span> &lt;span class="n">query&lt;/span>&lt;span class="p">:&lt;/span> &lt;span class="nb">str&lt;/span>&lt;span class="p">,&lt;/span> &lt;span class="n">context&lt;/span>&lt;span class="p">:&lt;/span> &lt;span class="nb">dict&lt;/span>&lt;span class="p">)&lt;/span> &lt;span class="o">-&amp;gt;&lt;/span> &lt;span class="nb">dict&lt;/span>&lt;span class="p">:&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl"> &lt;span class="c1"># First layer: exact-match cache (Redis GET, O(1))&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl"> &lt;span class="n">exact&lt;/span> &lt;span class="o">=&lt;/span> &lt;span class="k">await&lt;/span> &lt;span class="bp">self&lt;/span>&lt;span class="o">.&lt;/span>&lt;span class="n">cache&lt;/span>&lt;span class="o">.&lt;/span>&lt;span class="n">exact_lookup&lt;/span>&lt;span class="p">(&lt;/span>&lt;span class="n">query&lt;/span>&lt;span class="p">)&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl"> &lt;span class="k">if&lt;/span> &lt;span class="n">exact&lt;/span>&lt;span class="p">:&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl"> &lt;span class="k">return&lt;/span> &lt;span class="p">{&lt;/span>&lt;span class="o">**&lt;/span>&lt;span class="n">exact&lt;/span>&lt;span class="p">,&lt;/span> &lt;span class="s2">&amp;#34;cache_type&amp;#34;&lt;/span>&lt;span class="p">:&lt;/span> &lt;span class="s2">&amp;#34;exact&amp;#34;&lt;/span>&lt;span class="p">}&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl">
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl"> &lt;span class="c1"># Second layer: semantic cache (ANN search)&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl"> &lt;span class="n">query_embedding&lt;/span> &lt;span class="o">=&lt;/span> &lt;span class="k">await&lt;/span> &lt;span class="bp">self&lt;/span>&lt;span class="o">.&lt;/span>&lt;span class="n">embed&lt;/span>&lt;span class="p">(&lt;/span>&lt;span class="n">query&lt;/span>&lt;span class="p">)&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl"> &lt;span class="n">semantic&lt;/span> &lt;span class="o">=&lt;/span> &lt;span class="k">await&lt;/span> &lt;span class="bp">self&lt;/span>&lt;span class="o">.&lt;/span>&lt;span class="n">cache&lt;/span>&lt;span class="o">.&lt;/span>&lt;span class="n">semantic_lookup&lt;/span>&lt;span class="p">(&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl"> &lt;span class="n">query_embedding&lt;/span>&lt;span class="p">,&lt;/span> &lt;span class="n">threshold&lt;/span>&lt;span class="o">=&lt;/span>&lt;span class="bp">self&lt;/span>&lt;span class="o">.&lt;/span>&lt;span class="n">threshold&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl"> &lt;span class="p">)&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl"> &lt;span class="k">if&lt;/span> &lt;span class="n">semantic&lt;/span>&lt;span class="p">:&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl"> &lt;span class="k">return&lt;/span> &lt;span class="p">{&lt;/span>&lt;span class="o">**&lt;/span>&lt;span class="n">semantic&lt;/span>&lt;span class="p">,&lt;/span> &lt;span class="s2">&amp;#34;cache_type&amp;#34;&lt;/span>&lt;span class="p">:&lt;/span> &lt;span class="s2">&amp;#34;semantic&amp;#34;&lt;/span>&lt;span class="p">}&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl">
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl"> &lt;span class="c1"># Miss: full pipeline&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl"> &lt;span class="n">chunks&lt;/span> &lt;span class="o">=&lt;/span> &lt;span class="k">await&lt;/span> &lt;span class="bp">self&lt;/span>&lt;span class="o">.&lt;/span>&lt;span class="n">retriever&lt;/span>&lt;span class="o">.&lt;/span>&lt;span class="n">retrieve&lt;/span>&lt;span class="p">(&lt;/span>&lt;span class="n">query_embedding&lt;/span>&lt;span class="p">)&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl"> &lt;span class="n">response&lt;/span> &lt;span class="o">=&lt;/span> &lt;span class="k">await&lt;/span> &lt;span class="bp">self&lt;/span>&lt;span class="o">.&lt;/span>&lt;span class="n">llm&lt;/span>&lt;span class="o">.&lt;/span>&lt;span class="n">generate&lt;/span>&lt;span class="p">(&lt;/span>&lt;span class="n">query&lt;/span>&lt;span class="p">,&lt;/span> &lt;span class="n">chunks&lt;/span>&lt;span class="p">)&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl">
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl"> &lt;span class="c1"># Store for future queries&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl"> &lt;span class="k">await&lt;/span> &lt;span class="bp">self&lt;/span>&lt;span class="o">.&lt;/span>&lt;span class="n">cache&lt;/span>&lt;span class="o">.&lt;/span>&lt;span class="n">store&lt;/span>&lt;span class="p">(&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl"> &lt;span class="n">embedding&lt;/span>&lt;span class="o">=&lt;/span>&lt;span class="n">query_embedding&lt;/span>&lt;span class="p">,&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl"> &lt;span class="n">query&lt;/span>&lt;span class="o">=&lt;/span>&lt;span class="n">query&lt;/span>&lt;span class="p">,&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl"> &lt;span class="n">response&lt;/span>&lt;span class="o">=&lt;/span>&lt;span class="n">response&lt;/span>&lt;span class="p">,&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl"> &lt;span class="n">ttl&lt;/span>&lt;span class="o">=&lt;/span>&lt;span class="n">context&lt;/span>&lt;span class="o">.&lt;/span>&lt;span class="n">get&lt;/span>&lt;span class="p">(&lt;/span>&lt;span class="s2">&amp;#34;ttl&amp;#34;&lt;/span>&lt;span class="p">,&lt;/span> &lt;span class="mi">86400&lt;/span>&lt;span class="p">)&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl"> &lt;span class="p">)&lt;/span>
&lt;/span>&lt;/span>&lt;span class="line">&lt;span class="cl"> &lt;span class="k">return&lt;/span> &lt;span class="p">{&lt;/span>&lt;span class="o">**&lt;/span>&lt;span class="n">response&lt;/span>&lt;span class="p">,&lt;/span> &lt;span class="s2">&amp;#34;cache_type&amp;#34;&lt;/span>&lt;span class="p">:&lt;/span> &lt;span class="s2">&amp;#34;miss&amp;#34;&lt;/span>&lt;span class="p">}&lt;/span>
&lt;/span>&lt;/span>&lt;/code>&lt;/pre>&lt;/div>&lt;p>The first exact-match layer (Redis GET) is an extra optimisation: for textually identical queries, the embedding is not even computed. The cost is a Redis operation taking microseconds. Only if there is no exact match does it fall through to the semantic lookup.&lt;/p>
&lt;hr>
&lt;h2 id="what-we-have-not-covered">What we have not covered&lt;/h2>
&lt;ul>
&lt;li>
&lt;p>&lt;strong>Selective cache invalidation&lt;/strong>: when a subset of the corpus is updated (for example, the documents for a specific product are reindexed), you would need to identify which cache entries overlap semantically with the updated chunks and mark them stale. The mechanism involves computing similarity between the embeddings of the updated chunks and the embeddings of the cached queries, which is expensive at scale.&lt;/p>
&lt;/li>
&lt;li>
&lt;p>&lt;strong>Multi-tenant cache: isolation vs sharing&lt;/strong>: in a SaaS product with multiple customers, a shared cache maximises the hit rate but can expose one tenant&amp;rsquo;s answers to another if filtering is not done correctly. A cache partitioned by tenant is safe but has much lower hit rates. The middle ground is a shared cache with ACL filtering applied over Qdrant&amp;rsquo;s payload filters.&lt;/p>
&lt;/li>
&lt;li>
&lt;p>&lt;strong>Semantic cache for streaming responses&lt;/strong>: when the LLM emits tokens in streaming mode (SSE), the cache cannot easily intercept the complete answer. The options are: cache on the first miss and return the whole answer at once on hits (breaking the streaming experience), or implement a &amp;ldquo;fake streaming&amp;rdquo; that emits the tokens of the cached answer at a controlled rate.&lt;/p>
&lt;/li>
&lt;li>
&lt;p>&lt;strong>Exact-match cache as a first layer&lt;/strong>: ahead of the semantic cache, an O(1) lookup in Redis with the query as the key can catch textually identical queries at negligible cost. The code in the previous section already shows this two-layer architecture.&lt;/p>
&lt;/li>
&lt;/ul>
&lt;hr>
&lt;h2 id="see-also">See also&lt;/h2>
&lt;ul>
&lt;li>&lt;a href="https://blog.lo0.es/en/posts/reranker-hybrid-retrieval-five-chunks-llm-reads/">RAG with reranker and hybrid retrieval&lt;/a> — the retrieval that the semantic cache avoids running on hits; understanding how the vector search you are saving works&lt;/li>
&lt;li>&lt;a href="https://blog.lo0.es/en/posts/postgresql-qdrant-rag-ingestion-postman-syncing-two-worlds/">PostgreSQL + Qdrant: document ingestion in microservices&lt;/a> — the vector store that can double as a cache store, with the same Qdrant instance for corpus and cache&lt;/li>
&lt;li>&lt;a href="https://blog.lo0.es/en/posts/kv-cache-working-memory-llm-inference/">KV cache in transformers&lt;/a> — caching at the transformer&amp;rsquo;s attention level; different from the semantic cache at the RAG system&amp;rsquo;s query level, but complementary&lt;/li>
&lt;li>&lt;a href="https://blog.lo0.es/en/posts/continuous-batching-orca-vllm-chunked-prefill-goodput/">Continuous batching in LLM inference&lt;/a> — the batching that processes cache misses; the semantic cache reduces the pressure of requests reaching the inference engine&lt;/li>
&lt;li>&lt;a href="https://blog.lo0.es/en/posts/llm-tracing-opentelemetry-genai/">Tracing LLMs with OTel and GenAI&lt;/a> — how to instrument cache hits vs misses with OpenTelemetry to measure the real saving in production&lt;/li>
&lt;/ul>
&lt;hr>
&lt;h2 id="references">References&lt;/h2>
&lt;ol>
&lt;li>Bang, J. et al. (2024). &lt;em>MeanCache: User-Centric Semantic Cache for Large Language Model Based Web Applications&lt;/em>. arXiv:2403.02694.&lt;/li>
&lt;li>Zilliz. (2023). &lt;em>GPTCache: A Library for Creating Semantic Cache for LLM Queries&lt;/em>. GitHub: &lt;a href="https://github.com/zilliztech/GPTCache">zilliztech/GPTCache&lt;/a>.&lt;/li>
&lt;li>Qdrant Team. (2024). &lt;em>Qdrant Documentation: Filtering with payload&lt;/em>. &lt;a href="https://qdrant.tech/documentation/concepts/filtering/">qdrant.tech/documentation&lt;/a>.&lt;/li>
&lt;li>Manning, C. D., Raghavan, P., Schütze, H. (2008). &lt;em>Introduction to Information Retrieval&lt;/em>. Cambridge University Press. Cap. 19: Web search (distribución Zipf).&lt;/li>
&lt;li>Langfuse. (2024). &lt;em>Observability for LLM Applications&lt;/em>. &lt;a href="https://langfuse.com/docs">langfuse.com/docs&lt;/a>.&lt;/li>
&lt;li>Meta AI. (2024). &lt;em>Llama 3.1 Model Card&lt;/em>. &lt;a href="https://ai.meta.com/blog/meta-llama-3-1/">ai.meta.com&lt;/a>.&lt;/li>
&lt;li>Guo, Y. et al. (2023). &lt;em>Evaluating the Factual Consistency of Large Language Models Through Summarization&lt;/em>. Referencia para BERTScore como métrica de evaluación de respuestas cacheadas.&lt;/li>
&lt;/ol></description></item></channel></rss>