<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/"><channel><title>MongoDB on Oleksii M.</title><link>https://welldonesoftware.dev/tags/mongodb/</link><description>Recent content in MongoDB on Oleksii M.</description><generator>Hugo -- 0.167.0</generator><language>en</language><lastBuildDate>Wed, 11 Nov 2026 00:00:00 +0000</lastBuildDate><atom:link href="https://welldonesoftware.dev/tags/mongodb/index.xml" rel="self" type="application/rss+xml"/><item><title>Beyond TTL: Keeping Your Cache in Sync with the Database</title><link>https://welldonesoftware.dev/posts/pymongo-client-side-caching/</link><pubDate>Wed, 11 Nov 2026 00:00:00 +0000</pubDate><author>Oleksii M.</author><guid>https://welldonesoftware.dev/posts/pymongo-client-side-caching/</guid><description>&amp;lt;no value&amp;gt;</description><content type="text/html" mode="escaped"><![CDATA[<p>Consider a backend that caches flight route data with a time-to-live (TTL). Routes change at irregular intervals, so a TTL value that matches how long the data stays relevant may not exist at all.</p>
<p>An alternative is to keep the cache in sync with the database instead of guessing how long each record stays valid.</p>
<h2 id="ttl-is-a-guess-about-the-future">TTL is a guess about the future<a href="#ttl-is-a-guess-about-the-future" class="anchor" aria-hidden="true"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
      stroke-linecap="round" stroke-linejoin="round" class="feather">
      <path d="M15 7h3a5 5 0 0 1 5 5 5 5 0 0 1-5 5h-3m-6 0H6a5 5 0 0 1-5-5 5 5 0 0 1 5-5h3"></path>
      <line x1="8" y1="12" x2="16" y2="12"></line>
   </svg></a></h2>
<p>A TTL encodes an assumption: this data stays valid for N seconds. Most data does not change on a schedule. A record can stay the same for weeks and then change several times in an hour.</p>
<p>Any single TTL value is therefore a trade-off between two failures:</p>
<ul>
<li><strong>Too short:</strong> valid entries expire, and the database serves the same reads again.</li>
<li><strong>Too long:</strong> changed entries stay cached, and the application serves stale data.</li>
</ul>
<p>Shortening the TTL reduces staleness only by giving up reuse. Neither setting tells the cache what actually changed.</p>
<h2 id="invalidate-when-the-data-changes">Invalidate when the data changes<a href="#invalidate-when-the-data-changes" class="anchor" aria-hidden="true"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
      stroke-linecap="round" stroke-linejoin="round" class="feather">
      <path d="M15 7h3a5 5 0 0 1 5 5 5 5 0 0 1-5 5h-3m-6 0H6a5 5 0 0 1-5-5 5 5 0 0 1 5-5h3"></path>
      <line x1="8" y1="12" x2="16" y2="12"></line>
   </svg></a></h2>
<p>MongoDB <a href="https://www.mongodb.com/docs/manual/changestreams/" target="_blank" >change streams</a> let an application subscribe to inserts, updates, deletes, and other changes. A cache that follows the stream can drop an entry when the database reports a relevant change, rather than when a timer expires. Entries need no age limit: they stay cached until a change invalidates them or memory limits evict them.</p>
<p>Because the stream comes from the database itself, writes from other services, scripts, and manual fixes also invalidate the cache. In a cache relying solely on TTL, those writes remain invisible until the entry expires.</p>
<p><a href="https://github.com/alessio-locatelli/client-query-cache" target="_blank" >client-query-cache</a> implements this approach for PyMongo. It caches eligible reads in memory and uses one change stream per active database for invalidation.</p>
<h2 id="where-it-fits">Where it fits<a href="#where-it-fits" class="anchor" aria-hidden="true"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
      stroke-linecap="round" stroke-linejoin="round" class="feather">
      <path d="M15 7h3a5 5 0 0 1 5 5 5 5 0 0 1-5 5h-3m-6 0H6a5 5 0 0 1-5-5 5 5 0 0 1 5-5h3"></path>
      <line x1="8" y1="12" x2="16" y2="12"></line>
   </svg></a></h2>
<p>The approach suits data that is read far more often than it changes and that can be displayed slightly late after a write:</p>
<ul>
<li><strong>Reference data:</strong> flight routes, destination descriptions, product descriptions, or depot addresses that many requests read between edits.</li>
<li><strong>Status polling:</strong> a report or export status that clients refresh repeatedly while nothing changes.</li>
<li><strong>Data written elsewhere:</strong> documents that another service updates, where the reading application cannot invalidate its cache on write.</li>
</ul>
<p>It is a poor fit for values that must be current when an action depends on them, such as the price accepted at booking, available stock, or an access decision. It also helps little when every request reads different data, or when writes are so frequent that entries are invalidated before they are reused.</p>
<h2 id="gotchas">Gotchas<a href="#gotchas" class="anchor" aria-hidden="true"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
      stroke-linecap="round" stroke-linejoin="round" class="feather">
      <path d="M15 7h3a5 5 0 0 1 5 5 5 5 0 0 1-5 5h-3m-6 0H6a5 5 0 0 1-5-5 5 5 0 0 1 5-5h3"></path>
      <line x1="8" y1="12" x2="16" y2="12"></line>
   </svg></a></h2>
<h3 id="invalidation-is-asynchronous">Invalidation is asynchronous<a href="#invalidation-is-asynchronous" class="anchor" aria-hidden="true"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
      stroke-linecap="round" stroke-linejoin="round" class="feather">
      <path d="M15 7h3a5 5 0 0 1 5 5 5 5 0 0 1-5 5h-3m-6 0H6a5 5 0 0 1-5-5 5 5 0 0 1 5-5h3"></path>
      <line x1="8" y1="12" x2="16" y2="12"></line>
   </svg></a></h3>
<p>A completed write does not guarantee that an immediately following cached read sees the new value. The cache learns about the change only after it processes the change event. Reads requiring read-after-write consistency should use PyMongo directly with the appropriate session and <a href="https://alessio-locatelli.github.io/client-query-cache/usage/consistency/" target="_blank" >consistency controls</a>.</p>
<h3 id="invalidation-is-not-always-precise">Invalidation is not always precise<a href="#invalidation-is-not-always-precise" class="anchor" aria-hidden="true"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
      stroke-linecap="round" stroke-linejoin="round" class="feather">
      <path d="M15 7h3a5 5 0 0 1 5 5 5 5 0 0 1-5 5h-3m-6 0H6a5 5 0 0 1-5-5 5 5 0 0 1 5-5h3"></path>
      <line x1="8" y1="12" x2="16" y2="12"></line>
   </svg></a></h3>
<p>Single-document lookups by exact <code>_id</code>, or in a process-local cache by a unique index, can survive writes to other documents. Other cached queries generally use collection-wide invalidation, even when the write does not change their results.</p>
<p>Document design matters too. If a frequently updated field, such as a view counter, lives in the same document as rarely edited content, every counter update invalidates the cached content.</p>
<h3 id="caching-depends-on-the-stream">Caching depends on the stream<a href="#caching-depends-on-the-stream" class="anchor" aria-hidden="true"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
      stroke-linecap="round" stroke-linejoin="round" class="feather">
      <path d="M15 7h3a5 5 0 0 1 5 5 5 5 0 0 1-5 5h-3m-6 0H6a5 5 0 0 1-5-5 5 5 0 0 1 5-5h3"></path>
      <line x1="8" y1="12" x2="16" y2="12"></line>
   </svg></a></h3>
<p>Change streams require a replica set or a sharded cluster, and the library additionally requires MongoDB 8.0 or newer. On a standalone server, reads run through PyMongo without caching. The <a href="https://alessio-locatelli.github.io/client-query-cache/getting-started/installation/#requirements" target="_blank" >installation guide</a> lists the remaining Python, platform, and permission requirements.</p>
<p>Detected change-stream interruptions cause affected reads to bypass the cache rather than rely on entries whose validity can no longer be tracked.</p>
<h3 id="multiple-worker-processes-multiply-the-cache">Multiple worker processes multiply the cache<a href="#multiple-worker-processes-multiply-the-cache" class="anchor" aria-hidden="true"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
      stroke-linecap="round" stroke-linejoin="round" class="feather">
      <path d="M15 7h3a5 5 0 0 1 5 5 5 5 0 0 1-5 5h-3m-6 0H6a5 5 0 0 1-5-5 5 5 0 0 1 5-5h3"></path>
      <line x1="8" y1="12" x2="16" y2="12"></line>
   </svg></a></h3>
<p>This cost is easy to miss when designing a cache for a single process. Python web applications commonly run several worker processes, and each process-local cache keeps its own copy of the same documents and opens its own change stream.</p>
<p>The library therefore also offers a <a href="https://alessio-locatelli.github.io/client-query-cache/operations/shared-cache/" target="_blank" >shared cache</a>: the application&rsquo;s parent process starts a separate cache-owner process, which maintains a Rust-backed shared-memory cache and one change stream per active database, and trusted workers on the same Linux host attach to it. If the owner silently stalls, a safeguard stops cached hits within three seconds of its last successful stream poll. That is an outage safeguard, not a bound on how long invalidation takes after a write.</p>
<h2 id="measure-instead-of-guessing">Measure instead of guessing<a href="#measure-instead-of-guessing" class="anchor" aria-hidden="true"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
      stroke-linecap="round" stroke-linejoin="round" class="feather">
      <path d="M15 7h3a5 5 0 0 1 5 5 5 5 0 0 1-5 5h-3m-6 0H6a5 5 0 0 1-5-5 5 5 0 0 1 5-5h3"></path>
      <line x1="8" y1="12" x2="16" y2="12"></line>
   </svg></a></h2>
<p>Sharing one cache across workers sounds like an obvious win: less duplicated memory and fewer change streams. The <a href="https://alessio-locatelli.github.io/client-query-cache/benchmarks/shared-cache/" target="_blank" >project&rsquo;s October 2026 benchmark of version 0.8.0</a> with four workers showed a more nuanced result:</p>
<ul>
<li>Shared caching substantially reduced warm-read latency compared with direct database reads, but did not consistently outperform independent caches.</li>
<li>Total memory was nearly equal once the shared cache&rsquo;s owner process was included.</li>
<li>Cold reads cost more CPU and had higher tail latency than with independent caches.</li>
</ul>
<p>Intuition is a poor guide to caching performance: the expected benefits of sharing only partly materialized in this benchmark. Hit rate, read/write ratio, document size, worker count, and total CPU and memory decide whether a cache pays off, and only measurements under the application&rsquo;s real workload show which option wins: direct MongoDB reads, independent process caches, or a shared cache.</p>
<h2 id="a-small-example">A small example<a href="#a-small-example" class="anchor" aria-hidden="true"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
      stroke-linecap="round" stroke-linejoin="round" class="feather">
      <path d="M15 7h3a5 5 0 0 1 5 5 5 5 0 0 1-5 5h-3m-6 0H6a5 5 0 0 1-5-5 5 5 0 0 1 5-5h3"></path>
      <line x1="8" y1="12" x2="16" y2="12"></line>
   </svg></a></h2>
<p>A process-local cache wraps an existing PyMongo collection. Writes still go through the original collection:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-python" data-lang="python"><span style="display:flex;"><span><span style="color:#f92672">from</span> pymongo <span style="color:#f92672">import</span> MongoClient
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#f92672">from</span> client_query_cache <span style="color:#f92672">import</span> CacheManager
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">with</span> (
</span></span><span style="display:flex;"><span>    MongoClient(<span style="color:#e6db74">&#34;mongodb://localhost:27017&#34;</span>) <span style="color:#66d9ef">as</span> client,
</span></span><span style="display:flex;"><span>    CacheManager(client) <span style="color:#66d9ef">as</span> cache_manager,
</span></span><span style="display:flex;"><span>):
</span></span><span style="display:flex;"><span>    routes <span style="color:#f92672">=</span> client[<span style="color:#e6db74">&#34;flights&#34;</span>][<span style="color:#e6db74">&#34;routes&#34;</span>]
</span></span><span style="display:flex;"><span>    cached_routes <span style="color:#f92672">=</span> cache_manager<span style="color:#f92672">.</span>get_cached_collection(routes)
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    route <span style="color:#f92672">=</span> cached_routes<span style="color:#f92672">.</span>find_one({<span style="color:#e6db74">&#34;_id&#34;</span>: <span style="color:#e6db74">&#34;LIS-AMS&#34;</span>})
</span></span></code></pre></div><p>Repeated eligible reads of the same route can be served from memory until a change to that document invalidates the entry. The <a href="https://alessio-locatelli.github.io/client-query-cache/examples/fastapi-shared/" target="_blank" >shared FastAPI example</a> shows the multi-worker setup.</p>
]]></content></item></channel></rss>