<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sampreetha D Dixith on Medium]]></title>
        <description><![CDATA[Stories by Sampreetha D Dixith on Medium]]></description>
        <link>https://medium.com/@sampreethaddixith?source=rss-43106b919190------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*KHMBOR1hgkButK6IjD9afg.jpeg</url>
            <title>Stories by Sampreetha D Dixith on Medium</title>
            <link>https://medium.com/@sampreethaddixith?source=rss-43106b919190------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 10:46:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sampreethaddixith/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Real-Time Cache Invalidation Using PostgreSQL CDC (Triggers + NOTIFY)]]></title>
            <link>https://medium.com/@sampreethaddixith/real-time-cache-invalidation-using-postgresql-cdc-triggers-notify-240eaf9e148b?source=rss-43106b919190------2</link>
            <guid isPermaLink="false">https://medium.com/p/240eaf9e148b</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[cache-invalidation]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Sampreetha D Dixith]]></dc:creator>
            <pubDate>Wed, 31 Dec 2025 08:02:20 GMT</pubDate>
            <atom:updated>2025-12-31T08:02:20.416Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>“There are only two hard problems in Computer Science: cache invalidation and naming things.”<br> — Phil Karlton</em></blockquote><h3><strong>Introduction</strong></h3><p>Cache invalidation becomes especially tricky in read-heavy microservices where performance is paramount and data changes are rare but critical. In this article, we’ll explore a simple, effective, near real-time cache invalidation strategy using <strong>PostgreSQL Triggers</strong>, <strong>LISTEN/NOTIFY</strong>, and <strong>Spring Boot in-memory caching</strong>.</p><p><strong>The goal?</strong> High performance with:</p><ul><li>❌ No Kafka.</li><li>❌ No Redis.</li><li>❌ No Polling.</li></ul><h3>1. Problem Overview</h3><p>Consider a standard Spring Boot microservice environment where:</p><ul><li><strong>Read-Heavy:</strong> Almost every request hits the same dataset.</li><li><strong>Rare Updates:</strong> Data (like configuration or thresholds) changes once a day or week.</li><li><strong>Small Footprint:</strong> The number of cached values fits easily in memory.</li><li><strong>Latency Sensitive:</strong> Every millisecond counts.</li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Ftenor.com%2Fembed%2F14223589&amp;display_name=Tenor&amp;url=https%3A%2F%2Ftenor.com%2Fview%2Fkit-harrington-jon-snow-game-of-thrones-nope-dont-gif-14223589&amp;image=https%3A%2F%2Fmedia.tenor.com%2F0Uc-QP4QDP4AAAAN%2Fkit-harrington-jon-snow.png&amp;type=text%2Fhtml&amp;schema=tenor" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/a3432f4fa6642052dc909cc58e1af756/href">https://medium.com/media/a3432f4fa6642052dc909cc58e1af756/href</a></iframe><p>Using Spring’s in-memory cache optimizes reads, but when data changes directly in PostgreSQL, your application nodes become stale. We need a way to capture that change and react instantly.</p><h4>The Solution in One Line:</h4><blockquote><em>Capture Data Change (PostgreSQL Trigger + NOTIFY) → Evict Application Cache.</em></blockquote><h3>2. Key Concepts</h3><p>Before we dive into the “How,” let’s define the “What.”</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Ftenor.com%2Fembed%2F1779417987913461382&amp;display_name=Tenor&amp;url=https%3A%2F%2Ftenor.com%2Fview%2Fjon-snow-gif-1779417987913461382&amp;image=https%3A%2F%2Fmedia.tenor.com%2FGLHDO3SFroYAAAAN%2Fjon-snow.png&amp;type=text%2Fhtml&amp;schema=tenor" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef68eb0bcc11c27eb9a739af17edbff6/href">https://medium.com/media/ef68eb0bcc11c27eb9a739af17edbff6/href</a></iframe><h4>2.1 Change Data Capture (CDC)</h4><p>CDC is a pattern for capturing <strong>INSERT / UPDATE / DELETE</strong> events from a source database and reacting to them in downstream systems.</p><p>Unlike batch polling, CDC provides <strong>low-latency change propagation</strong>.</p><p>📖 Further reading:<br> <a href="https://blog.algomaster.io/p/change-data-capture-cdc">https://blog.algomaster.io/p/change-data-capture-cdc</a></p><h4>2.2 Cache Invalidation</h4><p>Cache invalidation ensures cached data stays consistent with the source of truth by removing or updating stale entries when underlying data changes. It is notoriously “simple in theory, painful in practice”.</p><h4>The “Why” Behind the Pain</h4><ul><li><strong>Strong Consistency:</strong> The cache is always 100% accurate, but this slows down writes as both systems must stay in sync.</li><li><strong>Eventual Consistency:</strong> The system stays fast by accepting that the cache might be “wrong” for a few seconds.</li></ul><h4>Common Strategies</h4><p>Beyond standard <strong>Write-Through</strong> (writing to both) and <strong>Write-Back</strong> (writing to cache first), these three are essential:</p><ul><li><strong>Cache-Aside (Lazy Loading):</strong> The application checks the cache; on a “miss,” it pulls from the DB and updates the cache for next time.</li><li><strong>Write-Around:</strong> Data is written directly to the DB, bypassing the cache to avoid flooding it with rarely-read data.</li><li><strong>TTL (Time to Live):</strong> A “safety net” where entries automatically expire after a set time — the simplest way to handle non-real-time data.</li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Ftenor.com%2Fembed%2F7572577&amp;display_name=Tenor&amp;url=https%3A%2F%2Ftenor.com%2Fview%2Freading-gif-7572577&amp;image=https%3A%2F%2Fmedia.tenor.com%2Fr_A5-DuGFIMAAAAN%2Freading.png&amp;type=text%2Fhtml&amp;schema=tenor" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/11a46ce8fa903932bb3e502f72fc39f3/href">https://medium.com/media/11a46ce8fa903932bb3e502f72fc39f3/href</a></iframe><h4>2.3. PostgreSQL Triggers</h4><p>Triggers are database hooks that automatically execute a function when a table changes.</p><p>They are:</p><ul><li>Declarative</li><li>Reliable</li><li>Executed inside the database</li></ul><p>📖 Further reading:<br> <a href="https://www.postgresql.org/docs/8.1/triggers.html">https://www.postgresql.org/docs/8.1/triggers.html</a></p><h4>2.4. PostgreSQL LISTEN / NOTIFY</h4><p>PostgreSQL supports asynchronous notifications using:</p><ul><li><strong>NOTIFY</strong> → publish an event</li><li><strong>LISTEN</strong> → subscribe to a channel</li></ul><p>This acts as a <strong>lightweight pub/sub system inside PostgreSQL</strong>.</p><p>📖 Further reading:</p><p><a href="https://www.postgresql.org/docs/current/sql-notify.html">https://www.postgresql.org/docs/current/sql-notify.html</a></p><p><a href="https://www.postgresql.org/docs/current/sql-listen.html">https://www.postgresql.org/docs/current/sql-listen.html</a></p><blockquote><strong><em>By combining these four concepts, we can turn PostgreSQL from a passive data store into an active event broadcaster that keeps our application’s memory perfectly in sync.</em></strong></blockquote><h3>3. Architecture Overview</h3><p>Before we dive into the implementation, let’s pause for a moment.</p><p>If all these concepts still feel disconnected, that’s okay.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Ftenor.com%2Fembed%2F18564553&amp;display_name=Tenor&amp;url=https%3A%2F%2Ftenor.com%2Fview%2Fcharlie-day-gif-18564553&amp;image=https%3A%2F%2Fmedia.tenor.com%2F4LvAD8hD5tcAAAAN%2Fcharlie-day.png&amp;type=text%2Fhtml&amp;schema=tenor" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/9b7762af3eac924f54ff54c2b294aabb/href">https://medium.com/media/9b7762af3eac924f54ff54c2b294aabb/href</a></iframe><blockquote><strong>As Steve Jobs once said, “You can’t connect the dots looking forward; you can only connect them looking backwards.”</strong></blockquote><p>🎧 Prefer watching instead :Here’s the full talk: <a href="https://www.youtube.com/watch?v=UF8uR6Z6KLc">Steve Jobs’ 2005 Stanford</a>)</p><p>Now, let’s do the engineering version of that.</p><p><strong>Let’s connect these technical dots.</strong></p><p>Following sequence is our solution :</p><ol><li><strong>Data Update:</strong> An update occurs in a PostgreSQL table.</li><li><strong>Trigger Fires:</strong> A database hook executes pg_notify.</li><li><strong>Event Broadcast:</strong> PostgreSQL broadcasts the event to all active listeners.</li><li><strong>Spring Boot Reacts:</strong> The listener receives the signal and calls @CacheEvict.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vt8_EEVRAl2cfOM2t8B9xA.png" /><figcaption>Lightweight, broker-less CDC flow where PostgreSQL acts as the event dispatcher to synchronize local in-memory caches across multiple service instances</figcaption></figure><h3>4. Implementation Walkthrough</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Ftenor.com%2Fembed%2F25012067&amp;display_name=Tenor&amp;url=https%3A%2F%2Ftenor.com%2Fview%2Fscaler-create-impact-code-coding-programming-gif-25012067&amp;image=https%3A%2F%2Fmedia.tenor.com%2FZIGKznVg44YAAAAN%2Fscaler-create-impact.png&amp;type=text%2Fhtml&amp;schema=tenor" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/904ade016c5d01dc8b0574d0a381547c/href">https://medium.com/media/904ade016c5d01dc8b0574d0a381547c/href</a></iframe><h4>4.1. Spring Boot Cache Setup</h4><p>We use Spring’s @Cacheable abstraction.</p><pre>@Service<br>public class ThresholdServiceImpl {<br><br>    @Autowired<br>    private ThresholdRepository thresholdRepo;<br><br>    private static final Logger logger =<br>        LoggerFactory.getLogger(ThresholdServiceImpl.class);<br><br>    @Cacheable(value = &quot;threshold&quot;, key = &quot;#event&quot;)<br>    public Integer getThresholdValue(String event) {<br>        return thresholdRepo.getEventThreshold(event);<br>    }<br><br>    @CacheEvict(value = &quot;threshold&quot;, allEntries = true)<br>    public void evictThresholdValues() {<br>        logger.info(&quot;Threshold cache invalidated&quot;);<br>    }<br>}</pre><h4>4.2. PostgreSQL Trigger + Notification</h4><p>We create a function that sends a notification and attach it to the table.</p><pre>-- Trigger Function<br>CREATE OR REPLACE FUNCTION event_threshold_trigger()<br>RETURNS TRIGGER AS $$<br>BEGIN<br>    PERFORM pg_notify(&#39;event_threshold_channel&#39;, &#39;threshold_updated&#39;);<br>    RETURN NEW;<br>END;<br>$$ LANGUAGE plpgsql;<br><br>-- Trigger Definition<br>CREATE TRIGGER event_threshold_changes<br>AFTER UPDATE ON event_threshold<br>FOR EACH ROW EXECUTE PROCEDURE event_threshold_trigger();</pre><h4>4.3. Spring Boot PostgreSQL Listener Configuration</h4><p>This sets up a persistent listener on the PostgreSQL notification channel.</p><pre>@Configuration<br>public class PgNotificationConfiguration {<br><br>    @Bean<br>    List&lt;SubscribableChannel&gt; subscribableChannel(<br>            PgEventMessageHandler handler,<br>            DataSource dataSource) {<br><br>        Supplier&lt;Connection&gt; connectionSupplier = () -&gt; {<br>            try {<br>                return dataSource.getConnection();<br>            } catch (SQLException e) {<br>                throw new RuntimeException(e);<br>            }<br>        };<br><br>        SubscribableChannel channel =<br>            new PgEventListener(<br>                &quot;event_threshold_channel&quot;,<br>                connectionSupplier,<br>                dataSource,<br>                1L<br>            );<br><br>        channel.subscribe(handler);<br>        return List.of(channel);<br>    }<br>}</pre><h4>4.4. Processing the Event</h4><p>As soon as the notification arrives, the cache is invalidated.</p><pre>@Component<br>public class PgEventMessageHandler implements MessageHandler {<br><br>    @Autowired<br>    private ThresholdService thresholdService;<br><br>    private static final Logger logger =<br>        LoggerFactory.getLogger(PgEventMessageHandler.class);<br><br>    @Override<br>    public void handleMessage(Message&lt;?&gt; message) {<br>        logger.debug(&quot;Received PG notification: {}&quot;,<br>                     message.getPayload());<br>        thresholdService.evictThresholdValues();<br>    }<br>}</pre><h3>5. Scaling Up: The Multi-Instance “Superpower”</h3><p>In a Kubernetes or clustered environment, this approach shines because of the <strong>Broadcast Effect</strong>.</p><ul><li><strong>The Broadcast Effect:</strong> Unlike a message queue (where only one instance might consume a message), a PostgreSQL NOTIFY is broadcast to <strong>all</strong> active listeners on that channel.</li><li><strong>Synchronized Invalidation:</strong> This means every pod/instance of your Spring Boot service will receive the event and clear its own local in-memory cache simultaneously.</li><li><strong>Result:</strong> You achieve cluster-wide cache consistency without needing a distributed cache like Redis.</li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Ftenor.com%2Fembed%2F21026909&amp;display_name=Tenor&amp;url=https%3A%2F%2Ftenor.com%2Fview%2Fcome-at-me-bro-gif-21026909&amp;image=https%3A%2F%2Fmedia.tenor.com%2F4ZKncbnXODEAAAAN%2Fcome-at-me-bro.png&amp;type=text%2Fhtml&amp;schema=tenor" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/0930f34a23c68422f4f11980b71b2133/href">https://medium.com/media/0930f34a23c68422f4f11980b71b2133/href</a></iframe><h3>6. Why This Works Well</h3><p>✅ Near real-time invalidation<br> ✅ Zero polling<br> ✅ No external infrastructure<br> ✅ Simple mental model</p><p>Perfect for:</p><ul><li>Small datasets</li><li>Read-heavy workloads</li><li>Non-distributed caches</li><li>Internal microservices</li></ul><h3>7. Important Caveats</h3><ul><li><strong>Fire and Forget:</strong> PostgreSQL notifications are not durable. If a service is down when the event is sent, it’s lost. <strong>Solution:</strong> Always set a TTL (Time-To-Live) on your cache as a fallback.</li><li><strong>Connection Overhead:</strong> Each listener requires a dedicated DB connection.</li><li><strong>Transaction Awareness:</strong> NOTIFY only sends <em>after</em> a transaction commits. This is a feature, not a bug—it prevents invalidating your cache for changes that were rolled back!</li></ul><h3>8. Final Thoughts</h3><p>By leveraging PostgreSQL’s built-in pub/sub, you can achieve near-real-time consistency without the operational overhead of a full-blown streaming platform.</p><p>This approach is a <strong>clean, pragmatic solution</strong> when your constraints are:</p><ul><li>Small data</li><li>High read volume</li><li>Rare writes</li><li>Low operational overhead</li></ul><p>Sometimes, <strong>the simplest CDC is the best CDC</strong>.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Ftenor.com%2Fembed%2F4320623434559332556&amp;display_name=Tenor&amp;url=https%3A%2F%2Ftenor.com%2Fview%2Fahaha-wave-bye-fearless-imout-gif-4320623434559332556&amp;image=https%3A%2F%2Fmedia.tenor.com%2FO_XwH0EjIMwAAAAN%2Fahaha-wave.png&amp;type=text%2Fhtml&amp;schema=tenor" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/5074a0b2ed31467efa8f644d3f5d63e3/href">https://medium.com/media/5074a0b2ed31467efa8f644d3f5d63e3/href</a></iframe><p>PS: This approach was born out of a need to provide real-time consistency without the overhead of additional infrastructure. I’d love to hear how others are solving the ‘lightweight’ invalidation challenge in their own stacks!</p><p>#firstArticle #yearEndGoal2025</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=240eaf9e148b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>