<?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 Sarfaraz on Medium]]></title>
        <description><![CDATA[Stories by Sarfaraz on Medium]]></description>
        <link>https://medium.com/@sarfaraz_alam?source=rss-e4ea22b08fc5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*ViFWV_x149ofOYbA</url>
            <title>Stories by Sarfaraz on Medium</title>
            <link>https://medium.com/@sarfaraz_alam?source=rss-e4ea22b08fc5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 09:17:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sarfaraz_alam/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[Caching! Everything You need to know Part: 5]]></title>
            <link>https://medium.com/@sarfaraz_alam/caching-everything-you-need-to-know-part-5-83c135c61e9b?source=rss-e4ea22b08fc5------2</link>
            <guid isPermaLink="false">https://medium.com/p/83c135c61e9b</guid>
            <category><![CDATA[caching-memory]]></category>
            <category><![CDATA[cache]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[caching]]></category>
            <category><![CDATA[cache-eviction-policies]]></category>
            <dc:creator><![CDATA[Sarfaraz]]></dc:creator>
            <pubDate>Sun, 04 Oct 2026 14:25:05 GMT</pubDate>
            <atom:updated>2026-10-04T14:27:19.078Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://medium.com/@sarfaraz_alam/caching-everything-you-need-to-know-part-4-877430e5c518">Caching! Everything you need to know Part:4</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LcYGspiB7m1jOhlNQwJSig.png" /></figure><h3>Cache Eviction Policies</h3><p>A cache keeps useful data close to the application, usually in fast memory. Memory is limited, so the cache cannot keep every value forever.</p><p><strong>Cache eviction</strong> means removing an entry to make room or enforce a storage rule. Eviction may occur because the cache reached its memory limit, an entry expired, or the system decided that another entry would be more valuable to keep.</p><p>An <strong>eviction policy</strong> answers this question:</p><p><em>“</em><strong><em>When space is needed, which entry should leave the cache?</em></strong><em>”</em></p><p>There is no perfect policy for every workload. A rule that works well for popular product pages may perform badly for analytics scans, search results, or one-time background jobs. The choice affects hit rate, response time, database traffic, and infrastructure cost.</p><h3>Important Terms</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*nuQdE1CvHDc2tq3xgQ-LUA.png" /></figure><h3>Eviction, Expiration, and Invalidation Are Different</h3><p>These terms are related but should not be mixed together:</p><pre>Eviction     → removed because the cache needs to manage capacity<br>Expiration   → removed or rejected because its TTL ended<br>Invalidation → removed because the application knows the value changed</pre><p>An entry can be a good eviction candidate even when it has not expired. An entry can also expire while plenty of memory remains. Most production caches use both a freshness rule such as TTL and a memory-pressure eviction policy such as LRU or LFU.</p><h3>1. When the Cache Fills Up</h3><p>When a new entry arrives and there is not enough space, the cache has several possible responses:</p><ul><li>Evict one or more existing entries.</li><li>Reject the new entry.</li><li>Reject the write with an out-of-memory error.</li><li>Store the value in a slower storage tier, if supported.</li><li>Ask the application to reduce value size or add capacity.</li></ul><p>The normal eviction flow looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bw7WPUkZdZjDQ4h23gUd4A.png" /></figure><h3>1.1 Why the victim choice matters</h3><p>If the cache removes an entry that would have been requested again soon, the next request becomes a miss. The application then performs the slow source read and may insert the same value again.</p><pre>Evict useful key → request it again → database read → insert again → evict another key</pre><p>When this cycle repeats rapidly, the cache is <strong>churning</strong>. Churn consumes CPU and network capacity while providing few useful hits.</p><h3>1.2 The working set</h3><p>The <strong>working set</strong> is the collection of data the application is likely to reuse during a relevant time window.</p><p>For example:</p><pre>Application has 10 million products<br>Users repeatedly access 100,000 popular products this hour<br>Current working set ≈ those 100,000 products and related data</pre><p>The entire database does not need to fit in memory. The cache is effective when its capacity can hold most of the useful working set.</p><p>Each eviction policy makes a different prediction:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*k2i0-OVlB5CB77hH08_T_w.png" /></figure><h3>1.3 Capacity by count versus capacity by bytes</h3><p>A cache with room for 10,000 entries may still use unpredictable memory if values have very different sizes.</p><pre>1 large report = 50 MB<br>1 small profile = 5 KB<br><br>One report uses the same space as roughly 10,000 small profiles.</pre><p>For mixed-size values, configure or implement a byte-based or weighted limit where possible. Also account for keys, metadata, indexes, allocator fragmentation, replication buffers, and network buffers — not only serialized value bytes.</p><h3>Cross-questions</h3><p><strong>Does a full cache mean the system is unhealthy?</strong><br> Not necessarily. Many caches are designed to operate near a configured capacity and evict selectively. Constant high-value eviction and falling hit rate are the stronger warning signs.</p><p><strong>Should every new entry be admitted?</strong><br> No. An admission policy can reject one-time or low-value data so it does not displace useful cached entries.</p><p><strong>What happens if the working set is larger than the cache?</strong><br> Some useful data will repeatedly leave and return. Increasing capacity, narrowing what is cached, compressing values, or improving admission and eviction may help.</p><h3>2. Least Recently Used (LRU)</h3><p><strong>Least Recently Used (LRU)</strong> removes the entry that has gone the longest without being accessed.</p><p>Its guiding idea is:</p><p><em>“If an entry was used recently, it is more likely to be used again soon.”</em></p><h3>2.1 How LRU works</h3><p>The cache maintains an order from most recently used to least recently used.</p><pre>Most recent → D → C → A → B → Least recent<br>                                      ↑<br>                              first eviction candidate</pre><p>On every hit or write, the accessed entry moves to the most-recent end. When space is required, the entry at the least-recent end is removed.</p><h3>2.2 Worked example: capacity 3</h3><p>Access stream:</p><pre>A, B, C, A, D, A, E</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/583/1*ohmwfpn4uc8blXvbKdgJ6g.png" /></figure><p>Totals:</p><pre>Hits: 2<br>Misses: 5<br>Evictions: 2<br>Hit rate: 2 / 7 ≈ 28.6%</pre><p>The small example is intended to show movement, not to represent a good production hit rate.</p><h3>2.3 Implementation idea</h3><p>An exact LRU implementation commonly combines:</p><ul><li>A hash map for fast lookup by key.</li><li>A doubly linked list for fast movement and victim selection.</li></ul><p>Some large distributed caches use <strong>approximate LRU</strong> rather than maintaining a perfect global list. They sample entries or store compact recency metadata to reduce bookkeeping cost.</p><h3>2.4 Benefits</h3><ul><li>Easy to understand.</li><li>Adapts quickly when active data changes.</li><li>Often effective for web pages, API responses, sessions, and recently viewed objects.</li><li>Does not allow an item to stay forever merely because it was popular long ago.</li></ul><h3>2.5 Costs and weaknesses</h3><ul><li>Every hit changes recency metadata.</li><li>A large one-time scan can make cold scan entries look recent.</li><li>It ignores how often an entry was used before its last access.</li><li>In a distributed cache, exact global ordering may be expensive.</li></ul><h3>2.6 Scan pollution</h3><p>Suppose a cache holds popular keys A, B, and C. A background job then reads X1, X2, X3, and millions more exactly once. Pure LRU treats each scan key as recent and may evict A, B, and C.</p><p>Possible protections include:</p><ul><li>Bypass the cache for known scans.</li><li>Use a separate cache for background jobs.</li><li>Require a key to be requested more than once before admission.</li><li>Use a scan-resistant policy such as segmented LRU or TinyLFU-style admission.</li></ul><h3>Best fit</h3><p>LRU is a strong starting point for general web and API workloads where recent reuse is a good prediction of future reuse.</p><h3>Cross-questions</h3><p><strong>Does writing a key count as recent use?</strong><br> Usually yes, but exact behavior depends on the cache implementation and configuration.</p><p><strong>Why can a hot key still be evicted under LRU?</strong><br> If it is not accessed for long enough while many other keys are touched, it eventually becomes the least recent.</p><p><strong>Is exact LRU always better than approximate LRU?</strong><br> No. Approximation may produce nearly the same hit rate with much lower metadata and coordination cost.</p><h3>3. Least Frequently Used (LFU)</h3><p><strong>Least Frequently Used (LFU)</strong> removes an entry with the lowest access frequency.</p><p>Its guiding idea is:</p><p><em>“Data requested many times is more valuable than data requested only once.”</em></p><h3>3.1 How LFU works</h3><p>The cache tracks a count or estimate for each entry. Every hit increases that frequency. When space is required, an entry with the smallest count is selected.</p><p>If several entries have the same frequency, recency is commonly used as a tie-breaker.</p><h3>3.2 Worked example: capacity 3</h3><p>Access stream:</p><pre>A, A, A, B, C, D, A, E</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*lnGnciZXNKdI6yzMRXYWCg.png" /></figure><p>The popular key A survives because its frequency remains higher.</p><h3>3.3 Frequency aging or decay</h3><p>Pure lifetime counts create a problem:</p><pre>Yesterday: A received 1,000 requests<br>Today:     nobody requests A</pre><p>Without aging, A may remain protected long after it becomes cold.</p><p><strong>Frequency decay</strong> gradually reduces old counts so recent traffic eventually matters more than historical traffic. Practical LFU implementations often use approximate counters and decay rather than unlimited exact integers.</p><h3>3.4 Cache pollution resistance</h3><p>An item read once receives a low frequency, so LFU is generally more resistant than LRU to one-time scans. However, if all new entries start at the same frequency and capacity is tight, admission and tie-breaking rules still matter.</p><h3>3.5 Benefits</h3><ul><li>Protects long-term popular keys.</li><li>Works well when a small hot set remains popular.</li><li>Can resist one-time scans better than simple LRU.</li><li>Useful for catalogs, common lookups, configuration, and widely read profiles.</li></ul><h3>3.6 Costs and weaknesses</h3><ul><li>Requires frequency metadata and updates.</li><li>Old popularity can remain influential without decay.</li><li>Adapts more slowly than LRU when popularity changes suddenly.</li><li>New valuable items can struggle against old high-count items unless admission and aging are designed well.</li></ul><h3>Best fit</h3><p>LFU works well when stable popularity is a stronger signal than very recent use.</p><h3>Cross-questions</h3><p><strong>What happens when two keys have the same frequency?</strong><br> The cache needs another rule, often least recent use among the tied keys or random selection.</p><p><strong>Why not keep exact counters forever?</strong><br> They consume metadata, can grow indefinitely, and allow old popularity to dominate. Approximation and decay are usually more adaptive.</p><p><strong>Is LFU automatically better for hot keys?</strong><br> It often protects them well, but workload changes, value size, admission, and counter tuning still affect the result.</p><h3>4. First In, First Out (FIFO)</h3><p><strong>First In, First Out (FIFO)</strong> removes the entry that was inserted earliest.</p><p>It cares about insertion age, not about reads.</p><h3>4.1 How FIFO works</h3><p>Entries form a queue:</p><pre>Evict next → A → B → C → D ← Newest insertion</pre><p>A cache hit does not move an entry. When E arrives at full capacity, A leaves even if A was requested one moment ago.</p><h3>4.2 Worked example: capacity 3</h3><p>Access stream:</p><pre>A, B, C, A, A, D, A</pre><p>RequestResultFIFO queue from oldest to newestEvictedAMissA — BMissA, B — CMissA, B, C — AHitA, B, C — AHitA, B, C — DMissB, C, DAAMissC, D, AB</p><p>Repeated hits did not protect A because FIFO ignores access behavior.</p><h3>4.3 Benefits</h3><ul><li>Very simple and predictable.</li><li>Low metadata overhead.</li><li>Insert and eviction operations can be efficient.</li><li>Reasonable when items have similar value and access patterns.</li></ul><h3>4.4 Costs and weaknesses</h3><ul><li>Can evict a very hot entry merely because it is old.</li><li>Does not learn from traffic.</li><li>Often produces a lower hit rate than LRU or LFU for uneven web workloads.</li><li>Insertion order is not necessarily related to future usefulness.</li></ul><h3>Best fit</h3><p>FIFO can be useful when simplicity and predictable residence order matter more than maximum hit rate, or when entries have roughly equal reuse.</p><h3>Cross-questions</h3><p><strong>Does reading an entry reset its FIFO position?</strong><br> No. If reads change the order, the behavior is no longer pure FIFO.</p><p><strong>Is FIFO the same as TTL?</strong><br> No. FIFO removes by relative insertion order under pressure. TTL removes by each entry’s expiration time even without pressure.</p><p><strong>Why choose FIFO over random?</strong><br> FIFO is deterministic and may match age-based workloads. Random requires less ordering but is less predictable.</p><h3>5. Random Replacement</h3><p><strong>Random replacement</strong> chooses a victim randomly when space is needed.</p><p>It does not track recency, frequency, or insertion order.</p><h3>5.1 How it works</h3><pre>Cache: [A, B, C, D]<br>New entry: E<br>Random victim: C<br>Result: [A, B, E, D]</pre><p>The same access stream may lead to different victims on different runs.</p><h3>5.2 Benefits</h3><ul><li>Very little policy metadata.</li><li>Fast and simple victim choice.</li><li>Avoids recency-list update overhead on each hit.</li><li>Can perform reasonably when access probabilities are similar or unpredictable.</li><li>Useful as an experimental baseline.</li></ul><h3>5.3 Costs and weaknesses</h3><ul><li>May evict the hottest key by chance.</li><li>Does not learn from access history.</li><li>Results vary, which can make individual tests less predictable.</li><li>Usually loses to a well-matched policy when the workload contains a clear hot set.</li></ul><h3>5.4 Why it is a useful baseline</h3><p>Test a sophisticated policy against random replacement. If the sophisticated policy provides almost the same hit rate and database load, its tracking overhead may not be worthwhile — or the workload may not contain predictable reuse.</p><h3>Best fit</h3><p>Random replacement is acceptable when bookkeeping must remain extremely small, keys have similar value, or measurements show that history-based prediction adds little.</p><h3>Cross-questions</h3><p><strong>Does random mean unfair?</strong><br> Every key has some chance of eviction, but fairness is not the main goal. The goal is application performance and correctness.</p><p><strong>Can random ever beat LRU?</strong><br> Yes, for some scan-heavy or unusual patterns. No policy dominates every possible access sequence.</p><p><strong>How should random policies be tested?</strong><br> Run several trials or use long representative traces, then compare distributions rather than relying on one short run.</p><h3>6. Most Recently Used (MRU)</h3><p><strong>Most Recently Used (MRU)</strong> removes the entry accessed most recently.</p><p>This sounds backward for normal web traffic because recent use often predicts near-future use. MRU is valuable only when the most recent item is unlikely to be needed again soon.</p><h3>6.1 Worked example: repeated cycle</h3><p>Imagine a scan through four items with cache capacity 3:</p><pre>Access pattern: A, B, C, D, A, B, C, D ...</pre><p>When D arrives after A, B, C, MRU removes C, the most recently touched item. It keeps older A and B, which appear sooner in the next cycle.</p><p>This can outperform LRU for this special pattern. LRU would remove A, the exact item needed next.</p><h3>6.2 Benefits</h3><ul><li>Can help with certain sequential scans and cyclic patterns.</li><li>Keeps older entries when recent entries are one-time scan results.</li><li>Provides a useful contrast when studying access behavior.</li></ul><h3>6.3 Costs and weaknesses</h3><ul><li>Removes exactly what most web workloads are likely to reuse.</li><li>Performs poorly for temporal locality, where recent items are requested again soon.</li><li>Requires recency tracking despite using it in the opposite direction from LRU.</li><li>Is rarely a safe default.</li></ul><h3>Best fit</h3><p>MRU fits measured workloads in which the most recently accessed entry is less likely to be reused than older cached entries.</p><h3>Cross-questions</h3><p><strong>Should MRU be selected merely because the workload has scans?</strong><br> No. Bypassing scans, using admission filtering, or using a scan-resistant LRU variant may protect normal traffic more effectively.</p><p><strong>Why can MRU help a repeated cycle larger than the cache?</strong><br> It may preserve the older items that will be revisited sooner in the next cycle.</p><p><strong>Is MRU common for general API caching?</strong><br> No. Recent reuse is common in APIs, making LRU or an adaptive policy a better starting point.</p><h3>7. Time to Live (TTL)</h3><p><strong>Time to live (TTL)</strong> defines how long an entry remains valid after it is stored.</p><p>TTL is usually discussed beside eviction, but it solves a different problem:</p><ul><li>LRU, LFU, FIFO, random, and MRU choose victims under capacity pressure.</li><li>TTL limits age and staleness even when memory is available.</li></ul><h3>7.1 How TTL works</h3><pre>Stored at:  10:00:00<br>TTL:        5 minutes<br>Expires at: 10:05:00</pre><p>After 10:05, the cache must not return the entry as a normal valid hit.</p><h3>7.2 Active and lazy expiration</h3><p>Caches commonly remove expired entries in two ways:</p><ul><li><strong>Lazy expiration:</strong> Discover and remove an expired entry when a request accesses it.</li><li><strong>Active expiration:</strong> A background task samples or scans entries and removes expired ones.</li></ul><p>Lazy expiration avoids constant scanning, but expired entries may occupy memory until touched. Active expiration reclaims memory earlier but consumes background CPU. Systems often combine both.</p><h3>7.3 Fixed versus sliding TTL</h3><ul><li><strong>Fixed TTL:</strong> Expiration time does not move when the entry is read.</li><li><strong>Sliding TTL:</strong> Each hit extends the lifetime.</li></ul><p>Fixed TTL provides a clearer maximum age. Sliding TTL keeps active entries alive but can preserve a stale value indefinitely if invalidation fails.</p><h3>7.4 TTL jitter</h3><p>If many keys are created together with the same TTL, they may expire together and overload the database.</p><pre>import random<br><br>base_ttl_seconds = 600<br>jitter_seconds = random.randint(-60, 60)<br>actual_ttl_seconds = base_ttl_seconds + jitter_seconds<br><br>cache.set(key, value, ttl=actual_ttl_seconds)</pre><p>This creates expiration times between 9 and 11 minutes instead of exactly 10 minutes for every key.</p><p>Keep the randomized maximum within the allowed freshness requirement.</p><h3>7.5 Benefits</h3><ul><li>Limits how long stale values normally survive.</li><li>Cleans up abandoned entries.</li><li>Is simple to understand and configure.</li><li>Allows different freshness rules for different data types.</li></ul><h3>7.6 Costs and weaknesses</h3><ul><li>Can expire a frequently used entry even when memory is available.</li><li>Does not by itself choose the most valuable victim under memory pressure.</li><li>Identical expiration times can create a thundering herd.</li><li>Very short TTLs may produce poor hit rates and repeated source work.</li><li>Very long TTLs may preserve stale or unused data too long.</li></ul><h3>Best fit</h3><p>Use TTL whenever cached data has a freshness or cleanup requirement. Combine it with a memory policy when the cache also has a fixed capacity.</p><h3>Cross-questions</h3><p><strong>Is an expired entry always removed at the exact expiration millisecond?</strong><br> Not necessarily. It must no longer be served as valid, but physical memory cleanup may happen lazily or in a background cycle.</p><p><strong>Does a hit normally reset TTL?</strong><br> Only for a sliding-expiration design. Fixed TTL does not change on reads.</p><p><strong>Can TTL replace explicit invalidation?</strong><br> It can limit stale duration, but it may not meet features requiring faster updates. Many systems use invalidation plus TTL as a safety net.</p><h3>8. Choosing a Policy</h3><p>Start with the workload, not with a policy name. Ask what deserves to stay and what is safe to remove.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a1MwpZcgauhwqf1iHZpt7w.png" /></figure><h3>8.1 Questions to ask</h3><ol><li>Is reuse predicted better by recency or frequency?</li><li>Does popularity change quickly?</li><li>Are there scans or one-time requests?</li><li>How large is the real working set?</li><li>Do values have very different sizes?</li><li>Is a miss equally expensive for every key?</li><li>How stale may values become?</li><li>Is eviction metadata overhead important?</li><li>Are keys local to one process or shared across nodes?</li><li>What happens to the database during a miss spike?</li></ol><h3>8.2 Cost-aware eviction</h3><p>Hit rate treats all hits as equal, but misses can have different costs:</p><pre>Miss A: 2 ms lookup<br>Miss B: 5-second report calculation</pre><p>Evicting B may be far more damaging even if A is requested more often. Advanced policies may consider frequency, recency, recomputation cost, and value size together.</p><p>A useful mental model is:</p><pre>Estimated value of keeping an entry<br>≈ probability of reuse × miss cost ÷ memory size</pre><p>This is not a universal formula, but it reveals why hit rate alone can be misleading.</p><h3>8.3 Admission and eviction work together</h3><p>Eviction chooses what leaves. Admission chooses whether the arriving item should enter.</p><p>If a new one-time report would evict a frequently reused product, the better decision may be to return the report without caching it.</p><p>Modern adaptive approaches often combine a frequency sketch or probation area with recency tracking. The goal is to protect established hot data from one-time scans while still allowing new popular items to prove their value.</p><h3>8.4 Practical Redis policy families</h3><p>Redis documents policies including:</p><ul><li>allkeys-lru, allkeys-lfu, and allkeys-random, which can choose among all keys.</li><li>volatile-lru, volatile-lfu, volatile-random, and volatile-ttl, which choose only among keys with an expiration.</li><li>noeviction, which rejects memory-growing writes instead of selecting a victim.</li></ul><p>Recent Redis documentation also includes least-recently-modified variants in applicable releases. Exact availability can depend on product and version, so configuration should be checked against the deployed edition.</p><p>Redis describes its LRU and LFU behavior as approximated, which reduces the cost of maintaining perfect global ordering or counts.</p><h3>8.5 Benchmark with representative traces</h3><p>Do not evaluate a policy only with a uniform random load test. Use traffic that represents:</p><ul><li>Real hot-key concentration.</li><li>Day and night changes.</li><li>Deployments and cold starts.</li><li>Background scans.</li><li>Value-size distribution.</li><li>TTL patterns.</li><li>Failure and retry traffic.</li></ul><p>Compare hit rate, byte hit rate, miss cost, database load, and user latency.</p><h3>Cross-questions</h3><p><strong>What is byte hit rate?</strong><br> It is the fraction of requested bytes served from cache. It complements request hit rate when values differ greatly in size.</p><p><strong>Should every key family use the same policy?</strong><br> Not necessarily. Separate caches or pools may be better when workloads and importance differ sharply.</p><p><strong>Why might the highest hit-rate policy still be worse?</strong><br> It may keep huge cheap-to-rebuild entries while evicting small expensive ones, consume too much metadata CPU, or produce worse tail latency.</p><h3>9. Common Pitfalls</h3><h3>9.1 Evicting by count instead of size</h3><p>Treating every entry as equal allows a few large values to dominate memory. Track value-size distribution and use byte or weighted limits where possible.</p><h3>9.2 Caching one-time reads</h3><p>One-off exports, administrative queries, migrations, backfills, and full-table scans may never be repeated. They consume capacity and pollute history-based policies.</p><p>Bypass the cache or isolate these workloads.</p><h3>9.3 Ignoring negative results</h3><p>Repeated lookups for nonexistent data can overload the database. Cache a distinct not-found marker briefly:</p><pre>value = database.get(key)<br>if value is None:<br>    cache.set(key, NOT_FOUND, ttl=30)<br>else:<br>    cache.set(key, value, ttl=600)</pre><p>Keep the negative TTL short and invalidate the marker when the item is created.</p><h3>9.4 Treating TTL as a complete memory policy</h3><p>TTL controls age. It does not guarantee that the most useful entries survive when memory fills. Combine expiration with a capacity policy when both concerns exist.</p><h3>9.5 No memory headroom</h3><p>Running at the absolute memory limit can trigger constant eviction and leave no space for:</p><ul><li>Temporary allocations.</li><li>Replication or persistence buffers.</li><li>Connection buffers.</li><li>Rebalancing.</li><li>Traffic variation.</li><li>Memory fragmentation.</li></ul><p>Reserve measured headroom appropriate to the cache technology and workload.</p><h3>9.6 Mixing permanent and disposable keys</h3><p>If a single store contains both cache entries and data that must never be evicted, an all-keys policy can remove important data. Even volatile-only policies become risky if TTL assignment is inconsistent.</p><p>Separate durable or non-evictable data from disposable cache workloads where possible.</p><h3>9.7 Ignoring admission</h3><p>A perfect victim-selection rule cannot help if every low-value item is admitted. Filter one-time, oversized, sensitive, or cheap-to-recompute entries before insertion.</p><h3>9.8 Changing policy without a controlled test</h3><p>A policy change can reshape database traffic immediately. Roll out gradually, watch source capacity, and keep a rollback plan.</p><h3>9.9 Using only global hit rate</h3><p>A strong global number can hide a critical route with poor caching. Measure by bounded key group, route, tenant class, or feature without using high-cardinality individual keys as metric labels.</p><h3>Cross-questions</h3><p><strong>Why can more cache memory sometimes provide little improvement?</strong><br> The workload may have low reuse, bad keys, overly short TTLs, or a working set already fully cached. Measure before scaling.</p><p><strong>Why separate background-job caching from user traffic?</strong><br> Large scans can evict latency-sensitive user data and distort recency or frequency history.</p><p><strong>Can compression improve eviction behavior?</strong><br> It can fit more values in memory, but compression and decompression add CPU and latency. Test the full trade-off.</p><h3>10. Monitoring Eviction</h3><p>Hit rate matters, but it is not enough to judge an eviction policy.</p><h3>10.1 Core metrics</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*LjDaLQiwV6i1XxwVS5DCTA.png" /></figure><h3>10.2 Separate eviction from expiration</h3><p>A drop in hit rate may come from memory pressure or simultaneous TTL expiry. Track them separately:</p><pre>High evictions + high memory → capacity or policy problem<br>High expirations + normal memory → TTL alignment or TTL-too-short problem<br>Low evictions + low hit rate → weak reuse, bad keys, or invalidation issue</pre><h3>10.3 Monitor by key group</h3><p>Use low-cardinality groups such as:</p><pre>product-detail<br>public-profile<br>search-page<br>configuration<br>negative-user-lookup</pre><p>Do not place raw user IDs or full cache keys in metric labels. That can leak information and make monitoring systems expensive.</p><h3>10.4 Useful alerts</h3><p>Alert when:</p><ul><li>Eviction rate suddenly rises above its normal baseline.</li><li>Hit rate drops for a critical key group.</li><li>Memory remains near the safe limit.</li><li>Database QPS and latency rise after evictions increase.</li><li>Many keys expire in the same short interval.</li><li>The same keys are repeatedly evicted and reinserted.</li><li>Oversized values exceed a safe threshold.</li><li>A no-eviction configuration starts rejecting writes.</li><li>One shard evicts heavily while others have free space.</li></ul><h3>10.5 Measure after policy changes</h3><p>Compare before and after using the same traffic periods:</p><ul><li>Overall and per-feature hit rate.</li><li>p50, p95, and p99 request latency.</li><li>Database QPS, CPU, and slow queries.</li><li>Cache CPU and network use.</li><li>Evictions, expirations, and churn.</li><li>Memory efficiency and operating cost.</li></ul><p>Allow enough time for the cache to warm and for daily traffic patterns to appear.</p><h3>Cross-questions</h3><p><strong>Can zero evictions be bad?</strong><br> It may mean there is plenty of capacity, but it can also mean new writes are being rejected or the cache is barely used. Interpret it with memory, errors, and hit rate.</p><p><strong>Why monitor reinsertions after eviction?</strong><br> They show that the policy removed entries the application needed again almost immediately — a strong sign of churn.</p><p><strong>Why can one shard evict while total cluster memory looks safe?</strong><br> Keys and values may be distributed unevenly. The overloaded shard reaches its local limit first.</p><h3>Policy Comparison at a Glance</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XKuWvuDlY8lHVwGLBi-JMg.png" /></figure><h3>Practical Selection Checklist</h3><ul><li>Identify the working set and how it changes over time.</li><li>Measure whether recency or frequency predicts reuse better.</li><li>Separate one-time scans from normal user traffic.</li><li>Measure value sizes, not only key count.</li><li>Define freshness separately from memory pressure.</li><li>Select TTLs based on data correctness requirements.</li><li>Add TTL jitter for keys created together.</li><li>Decide whether every new entry deserves admission.</li><li>Reserve memory headroom for overhead and bursts.</li><li>Test representative access traces and cold starts.</li><li>Compare request hit rate, byte hit rate, and miss cost.</li><li>Watch database load during rollout.</li><li>Measure per key group instead of relying only on global metrics.</li><li>Verify policy availability and behavior for the deployed cache version.</li><li>Roll out policy changes gradually with a rollback plan.</li></ul><h3>Cache Eviction Summary</h3><p>Cache eviction determines what leaves when space is needed. A good policy tries to keep the current working set — the data most likely to produce valuable future hits.</p><p>LRU keeps recently used data and is a strong default for many applications. LFU protects keys that remain popular over time, especially when frequency counts decay. FIFO is simple but ignores hits. Random replacement is cheap and provides a useful baseline. MRU helps only with special patterns where recent data is less likely to be reused. TTL controls freshness and cleanup, but it does not replace a memory-pressure policy.</p><p>Policy names are only a starting point. Admission rules, value size, TTL alignment, workload scans, approximation, sharding, and database miss cost can matter just as much.</p><p>The best policy is not necessarily the one with the highest overall hit rate. It is the one that keeps valuable data in memory, protects the database, meets user latency goals, and operates safely within its memory and metadata budget.</p><h3>Review Quiz</h3><h3>Questions</h3><ol><li>What is the difference between eviction, expiration, and invalidation?</li><li>What is a working set?</li><li>Which entry does LRU remove?</li><li>Why can a sequential scan hurt LRU?</li><li>Why does LFU need frequency decay?</li><li>Does a FIFO hit change insertion order?</li><li>Why is random replacement useful as a baseline?</li><li>When might MRU outperform LRU?</li><li>Why is TTL not a complete memory policy?</li><li>What is cache churn?</li><li>Why should capacity sometimes be measured in bytes instead of item count?</li><li>What is an admission policy?</li><li>Why add TTL jitter?</li><li>Which metrics should be watched together when eviction rises?</li></ol><h3>Answers</h3><ol><li>Eviction removes entries to manage capacity, expiration ends validity because TTL elapsed, and invalidation explicitly removes data because its source changed.</li><li>The working set is the data likely to be requested again within a useful time window.</li><li>LRU removes the entry that has gone the longest without access.</li><li>Every scanned item looks recent and can displace genuinely reusable hot data.</li><li>Without decay, an item popular long ago may remain protected even after it becomes cold.</li><li>No. Pure FIFO ignores reads and keeps insertion order unchanged.</li><li>It shows whether the overhead of a more complex predictive policy produces meaningful improvement.</li><li>MRU may help in certain repeated cycles or scans where the newest item will be reused later than older cached items.</li><li>TTL removes by age even without pressure; it does not choose the most useful victim when capacity fills.</li><li>Cache churn is rapid insertion and eviction that occurs before entries produce enough hits to be useful.</li><li>Values can differ greatly in size, so equal item counts may represent very different memory use.</li><li>It decides whether a new value deserves to enter the cache and possibly displace an existing value.</li><li>Jitter spreads expirations over time and reduces synchronized miss spikes.</li><li>Watch hit rate, memory, expirations, reinsertions, miss latency, database QPS, database CPU, and database latency.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83c135c61e9b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Caching! Everything you need to know Part:4]]></title>
            <link>https://medium.com/@sarfaraz_alam/caching-everything-you-need-to-know-part-4-877430e5c518?source=rss-e4ea22b08fc5------2</link>
            <guid isPermaLink="false">https://medium.com/p/877430e5c518</guid>
            <category><![CDATA[caching-strategies]]></category>
            <category><![CDATA[distributed-cache]]></category>
            <category><![CDATA[caching]]></category>
            <category><![CDATA[write-behind-cache]]></category>
            <category><![CDATA[cache-memory]]></category>
            <dc:creator><![CDATA[Sarfaraz]]></dc:creator>
            <pubDate>Tue, 29 Sep 2026 09:20:35 GMT</pubDate>
            <atom:updated>2026-09-29T09:20:35.764Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LcYGspiB7m1jOhlNQwJSig.png" /></figure><p><a href="https://medium.com/@sarfaraz_alam/caching-everything-you-need-to-know-part-3-5ff824899459">Caching! everything You need to know:part 3</a></p><h3>Write-Behind Cache</h3><p>Write-through caching waits for the database before telling the application that a write succeeded. This makes the durability story easier to understand, but every write pays the full cost of the database operation.</p><p>Write-behind caching, also called write-back caching, changes that agreement. The cache-aware layer accepts a change quickly, makes the new value available from the cache, and sends the database update later through a background process.</p><p>Write-behind can reduce user-facing write latency and smooth short traffic spikes. However, it creates a dangerous interval:</p><pre>The cache has accepted the change, but the database has not stored it yet.</pre><p>If the cache, queue, or worker fails during that interval, the change may be delayed, reordered, duplicated, or lost.</p><p>For this reason, “write succeeded” is often too vague. A write-behind API should distinguish:</p><ul><li>Accepted: The cache layer received the change.</li><li>Queued: The change was placed in a background-write queue.</li><li>Durably queued: The queued change survived the failure scenarios promised by the system.</li><li>Persisted: The database committed the change.</li></ul><p>Write-behind is not a free speed improvement. It is a delayed-write pipeline that needs the same careful design as a message-processing system.</p><h3>Important Terms</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/1*LqVaGn3DbP3WwAkXWItXQA.png" /></figure><h3>1. How Write-Behind Works</h3><p>In write-behind, the user-facing request does not normally wait for the database commit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J9o02cE7zv52-oZp0AKiwQ.png" /></figure><p>The exact ordering of “update cache” and “enqueue change” depends on the implementation. The two steps must be coordinated so a crash cannot leave a new cache value with no record of the database work still required.</p><h3>1.1 Typical write flow</h3><ol><li>The application submits a change to the cache-aware layer.</li><li>The layer validates the request.</li><li>It records the pending database operation in a queue or durable log.</li><li>It updates the cached value.</li><li>It acknowledges the level of acceptance promised by the API.</li><li>A background worker reads pending operations.</li><li>The worker writes them to the database, often in batches.</li><li>After the database commits, the worker marks the queued work complete.</li></ol><h3>1.2 Typical read flow</h3><p>Reads normally use the cache because it may contain a value newer than the database.</p><pre>Cache value:    Alice, version 9<br>Database value: Alice, version 8<br>State:          cache entry is dirty until version 9 is persisted</pre><p>If a reader bypasses the cache during the dirty period, it may see old data. A write-behind design must therefore define which read path provides the expected freshness.</p><h3>1.3 Simplified pseudocode</h3><pre>function setUser(userId, newValue, operationId):<br>    validate(newValue)<br><br>queuedChange = {<br>        operationId: operationId,<br>        key: &quot;user:&quot; + userId,<br>        value: newValue,<br>        version: nextVersion(userId)<br>    }<br>    durableQueue.append(queuedChange)<br>    cache.store(queuedChange.key, newValue, queuedChange.version)<br>    return DURABLY_QUEUED<br>background worker:<br>    changes = durableQueue.nextBatch()<br>    database.applyInOrder(changes)<br>    durableQueue.markComplete(changes)</pre><p>This is a conceptual example. Real implementations must handle atomicity, concurrent writers, retries, queue corruption, database constraints, and partial batch failures.</p><h3>1.4 Write-through versus write-behind</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*FBWfg64SGeQJWc8T011rCA.png" /></figure><h3>Cross-questions</h3><p><strong>Is write-behind the same as an asynchronous database API?</strong><br>They are related. Write-behind specifically keeps the newer value in a cache while database persistence happens asynchronously. A general asynchronous API may queue work without acting as a cache.</p><p><strong>Has a write “succeeded” when it enters memory?</strong><br>Only under a very weak contract. It has been accepted in memory, not durably persisted. The API should state exactly what the acknowledgment guarantees.</p><p><strong>Can the database be read directly after a write-behind acknowledgment?</strong><br>Yes, but it may return the old value until the background worker catches up. Callers requiring read-your-writes behavior should read through the cache-aware path or wait for persistence confirmation.</p><h3>2. The Write Queue</h3><p>The write queue is the heart of a write-behind system. It holds changes that have been accepted but not yet committed to the database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LfjOf47LDpeGWOQKq-Sd2w.png" /></figure><h3>2.1 What a queue entry contains</h3><p>A useful queued record may include:</p><ul><li>Operation ID or idempotency key.</li><li>Entity key.</li><li>Operation type: insert, update, delete, increment, or replace.</li><li>New value or change description.</li><li>Version or sequence number.</li><li>Creation time.</li><li>Retry count.</li><li>Tenant or partition identifier.</li><li>Trace ID for debugging.</li><li>Schema version for decoding the record.</li></ul><p>Do not place secrets in logs or unencrypted queues. Queue data should receive security controls appropriate to the underlying business data.</p><h3>2.2 In-memory versus durable queues</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1021/1*pIsMzV8HPfK0sVzQ6kSQsA.png" /></figure><p>The correct durability level comes from the business requirement, not from the word “cache.” Losing a view counter may be tolerable. Losing an accepted payment update is not.</p><h3>2.3 Queue acknowledgment</h3><p>The layer should acknowledge only after reaching the promised safety point.</p><pre>Weak acknowledgment:   placed in one process&#39;s memory<br>Stronger acknowledgment: fsynced to local durable log<br>Stronger still:        replicated to enough independent nodes<br>Final persistence:     committed by the database</pre><p>An <strong>fsync</strong> asks the operating system to flush buffered file data to stable storage. It can reduce performance, and even stable storage guarantees depend on the hardware and configuration.</p><h3>2.4 Partitioning the queue</h3><p>Large systems split queue work into partitions. A common rule sends all changes for the same entity key to the same partition:</p><pre>partition = hash(entityKey) mod numberOfPartitions</pre><p>This allows different keys to be processed in parallel while making per-key order easier to preserve.</p><h3>2.5 Queue cleanup</h3><p>Completed entries must eventually be removed or compacted. Cleanup must happen only after the database commit is known to have succeeded. Removing an entry too early can lose the only record of unfinished work.</p><h3>Cross-questions</h3><p><strong>Why not use a normal list in application memory?</strong><br>It may be adequate when losing pending writes is explicitly acceptable. Otherwise, a crash can erase acknowledged changes.</p><p><strong>Does a replicated queue guarantee zero data loss?</strong><br>No system offers an unlimited guarantee. It reduces risk for defined failures. Misconfiguration, software bugs, operator mistakes, or correlated failures can still cause loss.</p><p><strong>Why keep a schema version in queue records?</strong><br>Workers may process older records after a deployment. A version tells new code how to decode or migrate the old format safely.</p><h3>3. Why Write-Behind Improves Performance</h3><p>Write-behind improves perceived performance by moving slow database work outside the user’s request.</p><h3>3.1 Lower user-facing latency</h3><p>Suppose the timing is:</p><pre>Cache and durable queue acknowledgment: 4 ms<br>Database update:                        40 ms</pre><p>A write-through request may take at least about 44 ms, while write-behind may respond after about 4 ms and perform the 40 ms database work later.</p><p>This is a simplified illustration. Network calls, serialization, replication, and validation add other costs.</p><h3>3.2 Batching</h3><p>Batching combines several database operations into one request or transaction.</p><pre>Without batching: 1,000 writes → 1,000 database round trips<br>With batches of 100: 1,000 writes → about 10 batch round trips</pre><p>The database can often process a group more efficiently because fixed costs such as network round trips and transaction setup are shared.</p><p>Larger batches are not always better. They use more memory, wait longer to fill, create larger transactions, and make partial failures harder to handle.</p><h3>3.3 Coalescing or merging writes</h3><p>Several queued replacements for the same key may be reduced to the newest value:</p><pre>product:123 stock = 10<br>product:123 stock = 9<br>product:123 stock = 8<br><br>Possible coalesced database write: product:123 stock = 8</pre><p>This is safe only when intermediate states do not matter.</p><p>For an audit trail, payment ledger, notification sequence, or inventory decrement, every operation may be meaningful. Replacing operations with the final value could lose important facts.</p><h3>3.4 Smoothing traffic spikes</h3><p>The queue absorbs a short burst while workers write at a rate the database can sustain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gezvf_YS1xORtxMTPXIUXg.png" /></figure><p>This works only for a temporary spike. If incoming writes remain faster than database capacity, the queue grows without limit unless backpressure is applied.</p><h3>Cross-questions</h3><p><strong>Does write-behind make the database itself faster?</strong><br>Not necessarily. It hides database latency from the request and may improve efficiency through batching or coalescing. The database still performs the durable work.</p><p><strong>Can batching reduce correctness?</strong><br>Poorly designed batching can. The system must define transaction boundaries, ordering, partial-failure behavior, and whether operations may be merged.</p><p><strong>Can the queue absorb any size traffic spike?</strong><br>No. It is limited by memory, disk, network, retention, and recovery-time requirements. Backpressure is required before those limits are reached.</p><h3>4. Data Loss Risk</h3><p>The main risk in write-behind is acknowledging data before it reaches the database.</p><h3>4.1 The dirty window</h3><p>The dirty window begins when a write is accepted and ends when the database commits it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OdGSH1cl46L5Kl42Hx3Ofg.png" /></figure><p>The longer this window, the more pending data may be affected by a severe failure.</p><h3>4.2 Common loss scenarios</h3><ul><li>The process crashes while changes exist only in memory.</li><li>A cache node fails before its queue is replicated.</li><li>A disk fails before pending entries reach another durable copy.</li><li>A worker marks an item complete before the database commits.</li><li>A queue retention policy deletes old but unfinished work.</li><li>An operator flushes the cache or queue accidentally.</li><li>A software bug incorrectly coalesces meaningful operations.</li><li>A deployment cannot decode older queued messages.</li><li>A “permanent failure” item is discarded instead of preserved for investigation.</li></ul><h3>4.3 Acknowledged does not always mean durable</h3><p>If an API returns 200 OK after storing a write only in volatile memory, users may reasonably believe the data is safe when it is not.</p><p>Safer contracts use explicit states or documentation:</p><pre>202 Accepted           → queued for later processing<br>durabilityStatus       → memory | local_log | replicated | database_committed<br>operationId            → identifier for checking final status</pre><p>HTTP status codes alone do not create durability, but they can communicate asynchronous behavior more honestly.</p><h3>4.4 Recovery point objective</h3><p>The RPO expresses how much recent data the system can afford to lose.</p><pre>RPO = 0 seconds       → no acknowledged data loss is acceptable<br>RPO = 30 seconds      → losing up to roughly 30 seconds may be accepted<br>RPO = 5 minutes       → losing a few minutes may be accepted</pre><p>An RPO of zero is difficult and costly. It normally requires durable, replicated acknowledgment before success and careful operational controls.</p><h3>Cross-questions</h3><p><strong>If the cache has persistence enabled, is data loss impossible?</strong><br>No. Persistence frequency, replication, disk behavior, failover, and acknowledgment rules determine the real protection.</p><p><strong>Does a short flush interval guarantee a short loss window?</strong><br>It reduces normal delay, but a stalled worker or database outage can make the real window much longer. Monitor actual queue age, not only configured intervals.</p><p><strong>Should write-behind be used for money movement?</strong><br>Usually not as the sole durability mechanism. Financial operations generally require an authoritative durable ledger and strong idempotency before acknowledging success.</p><h3>5. Reducing Data Loss Risk</h3><p>Risk cannot be removed merely by naming a cache “durable.” It is reduced through several layers of protection.</p><h3>5.1 Durable write-ahead log</h3><p>Before acknowledging the write, append it to a durable log. If the process crashes, workers replay unfinished records after restart.</p><p>The log should be written before the queued operation is considered safely accepted hence the name write-ahead.</p><h3>5.2 Replication</h3><p>Keep pending writes on more than one independent node. A common policy waits for a chosen number of replicas before acknowledgment.</p><p>Replication protects against some node failures, but it does not automatically protect against application bugs or deletion replicated to every copy.</p><h3>5.3 Frequent flushing</h3><p>Shorter flush intervals reduce normal queue age and the amount of dirty data. The trade-off is smaller batches and more database overhead.</p><h3>5.4 Graceful shutdown</h3><p>During a planned shutdown:</p><ol><li>Stop accepting new writes.</li><li>Allow in-flight requests to finish.</li><li>Flush or durably hand off queued changes.</li><li>Confirm worker checkpoints.</li><li>Shut down only after the chosen safety condition is met.</li></ol><p>Graceful shutdown does not help during power loss or sudden crashes, so it is not a replacement for durability.</p><h3>5.5 Operation status and reconciliation</h3><p>Give important asynchronous writes an operation ID. Callers or internal processes can check whether each operation is queued, persisted, failed, or needs attention.</p><p>A reconciliation job compares expected results with the database and repairs discrepancies. Reconciliation is a safety net, not an excuse to ignore pipeline correctness.</p><h3>5.6 Backups and disaster recovery tests</h3><p>Back up the authoritative database and any queue state required for pending writes. Regularly test restoration. A backup that has never been restored is only an assumption.</p><h3>5.7 Match safeguards to business value</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JAwwiCwqN6Y7Ay5JG02yQw.png" /></figure><h3>Cross-questions</h3><p><strong>Can frequent flushing replace a durable queue?</strong><br>No. A crash can still happen between acceptance and the next flush.</p><p><strong>Why use both replication and a write-ahead log?</strong><br>They address different failures. A log survives process restart; replication can survive loss of a machine or disk.</p><p><strong>What is reconciliation useful for?</strong><br>It detects missing, duplicated, or inconsistent results after bugs and unusual failures, then alerts or repairs according to business rules.</p><h3>6. Ordering and Safe Retries</h3><p>Asynchronous work may be delayed, processed concurrently, or attempted more than once. Correct ordering and idempotency are essential.</p><h3>6.1 Why ordering matters</h3><p>Suppose two updates occur:</p><pre>Version 8: delivery address = Pune<br>Version 9: delivery address = Mumbai</pre><p>If version 9 reaches the database first and version 8 arrives later, an unprotected database update could incorrectly restore Pune.</p><h3>6.2 Per-key ordering</h3><p>Route all operations for the same entity to the same ordered queue partition. Different entities can still be processed in parallel.</p><pre>user:123 → partition 4 → versions 8, 9, 10 in order<br>user:456 → partition 1 → processed independently</pre><p>Per-key ordering is more scalable than forcing every system write through one global sequence.</p><h3>6.3 Version checks</h3><p>Store a version with each record and update only if the incoming version is newer.</p><pre>UPDATE users<br>SET name = :name, version = :incoming_version<br>WHERE id = :id<br>  AND version &lt; :incoming_version;</pre><p>If an older retry arrives after a newer version, it changes zero rows and cannot reverse the database state.</p><h3>6.4 Idempotent operations</h3><p>An operation is idempotent when repeating it produces the same final state.</p><p>Usually idempotent:</p><pre>Set user:123 language = &quot;en&quot;</pre><p>Not naturally idempotent:</p><pre>Add ₹100 to balance<br>Send welcome email<br>Increment stock by 1</pre><p>For non-idempotent operations, include a unique operation ID and record processed IDs durably so a retry cannot repeat the side effect.</p><h3>6.5 At-least-once versus at-most-once delivery</h3><ul><li>At-least-once: Retry until acknowledged. Work may happen more than once, so consumers need idempotency.</li><li>At-most-once: Do not retry after uncertain outcomes. Work may be lost, but duplicate execution is reduced.</li><li>Exactly-once effect: The system may deliver more than once internally, but deduplication and transactions make the business result appear once.</li></ul><p>“Exactly once” is not achieved merely by setting a queue option. It requires the database change and deduplication record to be coordinated.</p><h3>6.6 Retry policy</h3><p>Use bounded exponential backoff with jitter:</p><pre>attempt 1 → wait about 1 second<br>attempt 2 → wait about 2 seconds<br>attempt 3 → wait about 4 seconds<br>attempt 4 → wait about 8 seconds</pre><p><strong>Jitter </strong>adds randomness so many failed workers do not retry at exactly the same moment.</p><p>Do not retry permanent errors such as invalid data forever. Classify errors as transient, permanent, or uncertain.</p><h3>Cross-questions</h3><p><strong>Does an ordered queue guarantee database order?</strong><br>Only if workers preserve that order and database writes use appropriate version or transaction checks. Parallel processing can still reorder completion.</p><p><strong>Why retry a set operation but not blindly retry an increment?</strong><br>Repeating set value = 10 usually leaves 10. Repeating increment by 1 may incorrectly add twice unless the operation ID is deduplicated.</p><p><strong>Can timestamps replace sequence numbers?</strong><br>Sometimes, but clock differences and equal timestamps make them risky. Database-issued or per-key sequence numbers are often clearer.</p><h3>7. Handling Background Write Failures</h3><p>Background failures are harder to see because the original request may have already returned success or acceptance.</p><h3>7.1 Classify the failure</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/1*OIKx6fjplYfnqbOaiAq3FQ.png" /></figure><h3>7.2 Dead-letter queue</h3><p>After a configured number of failures, move an item to a dead-letter queue (DLQ) rather than discarding it or blocking the entire partition forever.</p><p>A DLQ needs:</p><ul><li>Alerts.</li><li>Enough context to diagnose the problem safely.</li><li>A documented replay or repair process.</li><li>Access control because it may contain business data.</li><li>Retention and deletion rules.</li></ul><p>A dead-letter queue is not a solution by itself. If nobody monitors and repairs it, it becomes a hidden data-loss folder.</p><h3>7.3 Poison messages</h3><p>A <strong>poison message</strong> always fails — for example, because its schema is invalid. Retrying it forever wastes resources and may block later work for the same partition.</p><p>Move it aside after safe limits, alert, and decide whether later same-key updates may proceed without violating order.</p><h3>7.4 Database outage</h3><p>During a long database outage:</p><ol><li>Workers should stop aggressive retries.</li><li>Pending queue size and oldest age will grow.</li><li>The system should reduce or reject new writes before capacity is exhausted.</li><li>Operators should see clear lag and capacity alerts.</li><li>Recovery should drain work at a rate that does not overload the returning database.</li></ol><h3>7.5 User-visible failure status</h3><p>For important operations, provide status such as:</p><pre>ACCEPTED → PERSISTING → PERSISTED<br>                     ↘ FAILED_REQUIRES_ACTION</pre><p>This is more honest than returning a permanent-looking success for work that may later fail validation at the database.</p><h3>Cross-questions</h3><p><strong>What if a queued write violates a database constraint?</strong><br>It is usually a permanent failure. The layer should have validated earlier, but it must still preserve the failed item, alert, and follow a business repair process.</p><p><strong>Should one failed key block every other key?</strong><br>Usually no. Partitioning and per-key ordering allow unrelated work to continue. Later operations for the same key may need to wait.</p><p><strong>Who should own DLQ repair?</strong><br>A clearly named team with alerts, a runbook, permissions, and tools to inspect, correct, replay, or safely discard items.</p><h3>8. Backpressure</h3><p><strong>Backpressure</strong> is the system’s way of saying, “Work is arriving faster than it can be safely processed.”</p><p>Without backpressure, the queue can consume all memory or disk, recovery time can become unacceptable, and the system may crash.</p><h3>8.1 Key measurements</h3><ul><li>Queue depth: number of pending operations.</li><li>Queue bytes: storage used by pending operations.</li><li>Oldest pending age: how long the oldest operation has waited.</li><li>Incoming rate: writes added per second.</li><li>Drain rate: writes persisted per second.</li><li>Estimated drain time: how long the current backlog will take to clear.</li></ul><pre>Estimated drain time ≈ queued operations / effective drain rate</pre><p>If new writes continue arriving, use the net drain rate:</p><pre>Net drain rate = processing rate − incoming rate</pre><p>If the net drain rate is zero or negative, the backlog will not clear.</p><h3>8.2 Backpressure responses</h3><p>As pressure increases, the system may:</p><ol><li>Increase workers within safe database limits.</li><li>Flush smaller or more frequent batches.</li><li>Coalesce safe repeated updates.</li><li>Slow low-priority producers.</li><li>Apply per-tenant or per-user rate limits.</li><li>Return 429 Too Many Requests or 503 Service Unavailable with retry guidance.</li><li>Reject nonessential writes before critical ones.</li><li>Temporarily switch selected operations to synchronous persistence.</li></ol><p>Adding unlimited workers is dangerous because it can move the overload directly to the database.</p><h3>8.3 Bounded queues</h3><p>A bounded queue has a known maximum size. When full, the producer must wait, reject work, or use an approved fallback. This is safer than silently consuming all available resources.</p><h3>8.4 Load shedding</h3><p>Load shedding deliberately rejects lower-priority work so the system can continue processing important operations. It should be based on explicit product priorities, not random data loss.</p><h3>Cross-questions</h3><p><strong>Is a growing queue always a problem?</strong><br>A short increase during a burst can be normal. Continuous growth or rising oldest-item age means the system is falling behind.</p><p><strong>Why not keep accepting writes until disk is full?</strong><br>Recovery time becomes enormous, other services may lose disk space, and sudden exhaustion can corrupt or stop the system. Apply limits earlier.</p><p><strong>Can autoscaling workers fix backpressure?</strong><br>Only if the database has spare capacity. Otherwise, more workers increase contention and make the outage worse.</p><h3>9. When to Use Write-Behind</h3><p>Write-behind is best suited to workloads where write latency matters, writes can be delayed briefly, and the data-loss contract is understood.</p><h3>9.1 Good candidates</h3><ul><li>Page-view and impression counters.</li><li>Analytics events where small bounded loss is acceptable.</li><li>Telemetry and device measurements.</li><li>Game statistics that can be reconstructed or reconciled.</li><li>User preferences backed by a durable queue.</li><li>High-frequency updates that can safely be coalesced.</li><li>Workloads with short bursts and predictable average database capacity.</li></ul><h3>9.2 Poor or dangerous candidates</h3><ul><li>Payment ledgers.</li><li>Bank balances.</li><li>Irreplaceable orders acknowledged as final.</li><li>Security permission changes that must apply immediately everywhere.</li><li>Inventory operations where intermediate changes must not be lost.</li><li>Legal or audit records requiring immediate durable storage.</li><li>Data with complex constraints that may reject the delayed write.</li></ul><p>These systems may still use caches, but the authoritative operation should normally commit durably before final success is reported.</p><h3>9.3 Decision questions</h3><p>Before choosing write-behind, ask:</p><ol><li>What does acknowledgment promise?</li><li>What is the allowed RPO?</li><li>How long may the database lag behind the cache?</li><li>Can writes be safely batched or coalesced?</li><li>Are operations idempotent?</li><li>What ordering is required: global, per customer, or per key?</li><li>Can the database reject data after the user was told it was accepted?</li><li>How will users learn about a permanent background failure?</li><li>Can the queue survive a process, machine, or regional failure?</li><li>What happens when incoming traffic exceeds drain capacity?</li><li>How will the system reconcile missing or duplicate outcomes?</li></ol><p>If these answers are unclear, cache-aside or write-through is normally safer.</p><h3>Cross-questions</h3><p><strong>Is high write volume by itself a reason to use write-behind?</strong><br>No. Correctness, durability, ordering, and recovery requirements matter more. Database tuning, partitioning, or direct event ingestion may be better.</p><p><strong>Can write-behind be safe for user preferences?</strong><br>Often, if a durable queue, clear status, retry, and reasonable recovery path exist. The exact business promise still matters.</p><p><strong>Should write-behind be added only because write-through feels slow?</strong><br>First measure the cause. Slow database queries, locks, indexes, network distance, or oversized transactions may be fixable without accepting asynchronous-write risk.</p><h3>10. Real-World Analogies</h3><p>Analogies are useful for intuition, though real systems need more precise guarantees.</p><h3>10.1 Restaurant order ticket</h3><p>A waiter accepts an order and gives the customer confirmation before the kitchen prepares the food.</p><ul><li>Cache acknowledgment: waiter accepts the order.</li><li>Write queue: order ticket rail.</li><li>Background worker: kitchen staff.</li><li>Database commit: completed dish.</li><li>Backpressure: stop seating customers when the kitchen is overwhelmed.</li><li>Dead-letter queue: unclear order set aside for manager review.</li></ul><p>If the ticket is lost, the customer believes an order exists while the kitchen knows nothing about it. A durable ordering system reduces that risk.</p><h3>10.2 Postal collection box</h3><p>Placing a letter in a collection box is not the same as successful delivery.</p><ul><li>Accepted: letter entered the box.</li><li>Queued: waiting for collection.</li><li>In progress: moving through sorting centers.</li><li>Persisted business result: delivered to the recipient.</li></ul><p>A tracking number is like an operation ID: it helps check final status and investigate failures.</p><h3>10.3 Notebook and accounting ledger</h3><p>A shopkeeper quickly records sales in a notebook and enters them into the official accounting system at the end of the day.</p><p>The notebook improves speed and allows batching. But if it is lost or entries are copied in the wrong order, the official ledger is wrong. Numbered pages, duplicate copies, reconciliation, and controlled handoff are real-world versions of durability, ordering, and retry controls.</p><h3>10.4 Email outbox</h3><p>An email client may show a message in “Outbox” before the server accepts it. The client retries in the background and later moves it to “Sent.” A permanent failure should remain visible instead of silently disappearing.</p><h3>Cross-questions</h3><p><strong>What is the limitation of these analogies?</strong><br>They explain delayed processing, but software adds concurrency, replication, machine failure, and exact correctness rules. Architecture decisions need measured guarantees, not analogy alone.</p><p><strong>Which analogy best explains acknowledgment levels?</strong><br>The postal example: placing a letter in a box, entering the transport network, and confirmed delivery are different states.</p><h3>11. Production Checklist</h3><h3>Contract and business safety</h3><ul><li>The API clearly distinguishes accepted, durably queued, and persisted states.</li><li>The business owner has approved the RPO and maximum persistence delay.</li><li>Critical data has an authoritative durability path appropriate to its value.</li><li>Read behavior during the dirty period is documented.</li><li>Permanent background failures have a user or operator resolution path.</li></ul><h3>Queue durability</h3><ul><li>The queue’s process, machine, disk, and region failure guarantees are known.</li><li>Acknowledgment happens only after the promised durability point.</li><li>Queue records include operation ID, key, version, timestamp, and schema version.</li><li>Encryption, access control, retention, and privacy rules are configured.</li><li>Recovery and replay have been tested, not merely documented.</li></ul><h3>Correctness</h3><ul><li>Per-key ordering requirements are defined.</li><li>Database writes use versions or other concurrency protection where needed.</li><li>Retried operations are idempotent or deduplicated by operation ID.</li><li>Batching and coalescing rules preserve required intermediate events.</li><li>Deletes and recreations cannot be reordered incorrectly.</li><li>Workers mark queue items complete only after confirmed database commit.</li></ul><h3>Failure handling</h3><ul><li>Errors are classified as transient, permanent, conflict, or unknown outcome.</li><li>Retries use bounded exponential backoff with jitter.</li><li>Poison messages move to a monitored dead-letter process.</li><li>Database outages do not cause unlimited retry storms.</li><li>Cache and queue restarts preserve or intentionally discard data according to contract.</li><li>Graceful shutdown drains or safely hands off work.</li></ul><h3>Backpressure and capacity</h3><ul><li>Queue capacity is bounded.</li><li>Safe warning and rejection thresholds are defined.</li><li>Producer rate limits and load-shedding priorities exist.</li><li>Worker scaling respects database capacity.</li><li>Maximum acceptable backlog age and estimated drain time are defined.</li><li>Recovery after a long outage has been load tested.</li></ul><h3>Monitoring and operations</h3><ul><li>Queue depth, bytes, and oldest-item age are monitored.</li><li>Incoming, processing, success, retry, and failure rates are monitored.</li><li>Dirty-entry count and cache-to-database lag are monitored.</li><li>Batch size and flush duration are monitored.</li><li>Dead-letter count and age trigger alerts.</li><li>Database latency, conflicts, throttling, and capacity are monitored.</li><li>End-to-end time from acceptance to persistence is measured at p50, p95, and p99.</li><li>Reconciliation detects missing, duplicated, or out-of-order results.</li><li>A named team owns alerts and a tested incident runbook.</li></ul><h3>Cross-questions</h3><p><strong>Which metric is more useful than queue depth alone?</strong><br>Oldest-item age. A large fast-moving queue may be healthy, while a small queue containing a stuck day-old item is not.</p><p><strong>What should be tested before production?</strong><br>Process crashes, node loss, queue replay, duplicate delivery, out-of-order completion, database outage, poison messages, full queues, deployments with old records, and recovery under backlog.</p><h3>Write-Behind Summary</h3><p>Write-behind acknowledges a change before the database commit and persists it later through a background pipeline. This lowers user-facing write latency and can improve database efficiency through batching and safe coalescing.</p><p>The speed comes from delaying durable work, not eliminating it. During the dirty period, the cache is newer than the database. A failure can lose or corrupt acknowledged changes unless the queue, ordering, retries, and recovery process are designed carefully.</p><p>The essential rules are:</p><ul><li>Define what acknowledgment actually guarantees.</li><li>Use a durable, appropriately replicated queue when loss is unacceptable.</li><li>Preserve per-key ordering with partitions and versions.</li><li>Make retries idempotent or deduplicate them.</li><li>Coalesce only when intermediate operations do not matter.</li><li>Treat permanent failures through a monitored repair process.</li><li>Apply backpressure before the queue exhausts resources.</li><li>Monitor end-to-end persistence lag, not only cache latency.</li><li>Prefer source-first durability for money, audit, permissions, and other critical records.</li></ul><p>Write-behind is appropriate when delayed persistence is a deliberate business decision supported by operational safeguards. It is dangerous when asynchronous acceptance is presented as durable success without those safeguards.</p><h3>Quiz</h3><p>Try answering these before opening the answers.</p><h3>Questions</h3><ol><li>What is the main difference between write-through and write-behind?</li><li>What is a dirty entry?</li><li>Why can an in-memory queue lose acknowledged data?</li><li>What does batching improve?</li><li>When is write coalescing unsafe?</li><li>Why are operation IDs important for retries?</li><li>What is per-key ordering?</li><li>What should happen to a permanently failing queue item?</li><li>What does backpressure protect?</li><li>Why is queue age important in addition to queue depth?</li><li>What does an RPO describe?</li><li>Why is write-behind usually risky for financial ledgers?</li></ol><p>Show answers</p><h3>Answers</h3><ol><li>Write-through waits for the database commit before ordinary success. Write-behind acknowledges earlier and persists through a background worker.</li><li>A dirty entry is a cached value newer than the value currently stored in the database.</li><li>Process or machine failure clears volatile memory before pending operations reach durable storage.</li><li>Batching reduces repeated network, transaction, and statement overhead by writing a group together.</li><li>Coalescing is unsafe when every intermediate operation matters, such as ledger entries, increments, audit events, or notifications.</li><li>An operation ID allows the database or worker to recognize a retry and avoid applying the same non-idempotent effect twice.</li><li>Per-key ordering ensures changes for one entity are persisted in the same logical order in which they were accepted.</li><li>Preserve it in a monitored dead-letter or repair workflow, alert the owner, and investigate instead of silently discarding it.</li><li>Backpressure prevents unlimited queue growth and protects memory, disk, workers, and the database when input exceeds processing capacity.</li><li>Depth shows how much is queued; age shows how long work has waited and reveals stuck or severely delayed items.</li><li>The recovery point objective describes how much recent data loss the business is prepared to accept after a severe failure.</li><li>Acknowledged financial records normally require strong immediate durability, strict ordering, deduplication, and auditability. Losing or silently delaying them can change balances and legal records.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=877430e5c518" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Caching! everything You need to know:part 3]]></title>
            <link>https://medium.com/@sarfaraz_alam/caching-everything-you-need-to-know-part-3-5ff824899459?source=rss-e4ea22b08fc5------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ff824899459</guid>
            <category><![CDATA[caching]]></category>
            <category><![CDATA[read-through-caching]]></category>
            <category><![CDATA[write-through-caching]]></category>
            <category><![CDATA[cache]]></category>
            <category><![CDATA[caching-strategies]]></category>
            <dc:creator><![CDATA[Sarfaraz]]></dc:creator>
            <pubDate>Sat, 26 Sep 2026 10:54:39 GMT</pubDate>
            <atom:updated>2026-09-26T10:54:39.519Z</atom:updated>
            <content:encoded><![CDATA[<ul><li><a href="https://medium.com/@sarfaraz_alam/caching-everything-you-need-to-know-part-1-5b0273f64a87">Caching! everything You need to know : part 1</a></li><li><a href="https://medium.com/@sarfaraz_alam/caching-everything-you-need-to-know-part-2-e22f14405508">Caching! everything You need to know : Part 2</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*lhsMzWj-6rRdJt9Vp_zHWQ.png" /></figure><h3>Read-Through vs. Write-Through Caching</h3><p>Caching repeatedly raises the same design question:</p><blockquote><strong><em>Who is responsible for keeping the cache and database aligned?</em></strong></blockquote><p>With cache-aside, the application performs the work directly. It checks the cache, loads missing values from the database, stores them, and invalidates cached copies after the database changes.</p><p>That gives the application full control, but it can also produce repeated code. Every service that reads or changes the same data must follow the same rules correctly.</p><p>Read-through and write-through move some of this responsibility into a cache-aware layer:</p><ul><li>A read-through cache knows how to load a missing value from the source.</li><li>A write-through cache knows how to save a value to the source before updating the cached copy.</li></ul><p>The “cache layer” may be a cache product with built-in loader and writer hooks, a cache library inside the application, or a shared wrapper service. A plain Redis or Memcached server does not automatically know how to query an application’s database. Additional code must teach the layer how to load and write each type of data.</p><p>These patterns can make business code smaller and more consistent. In exchange, the cache-aware layer becomes more complex and more important to system reliability.</p><h3>Important Terms</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yXxb_v83jGTo6KgbztZY-g.png" /></figure><h3>The Central Difference</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*63MFdlvxsizKCiTPTFj52A.png" /></figure><p>Cache-aside exposes the cache workflow to application code. Read-through and write-through place that workflow behind a common interface.</p><h3>1. Read-Through Cache</h3><p>In a read-through cache, the application asks the cache layer for data. If the value is missing, the cache layer calls a loader, stores the loaded value, and returns it.</p><p>From the application’s point of view, both hits and misses use the same call:</p><pre>user = cache.get(&quot;user:123&quot;)</pre><p>The application does not contain the miss-handling steps for that data type.</p><h3>1.1 Read-through flow</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/1*Wr7tLgxuNHRxaDsyY2redg.png" /></figure><p>Step by step:</p><ol><li>The application calls get with a key.</li><li>The cache checks whether a valid entry exists.</li><li>On a hit, it returns the cached value.</li><li>On a miss, it calls the registered loader.</li><li>The loader reads from the database or another service.</li><li>The cache stores the loaded value with a TTL.</li><li>The cache returns it to the application.</li></ol><h3>1.2 Java example</h3><pre>class UserService {<br>    private final ReadThroughCache&lt;User&gt; cache =<br>        new ReadThroughCache&lt;&gt;(this::loadUser, 300);<br>User loadUser(String key) {<br>        String userId = key.split(&quot;:&quot;)[1];<br>        return database.getUser(userId);<br>    }<br>User getUser(String userId) {<br>        return cache.get(&quot;user:&quot; + userId);<br>    }<br>}</pre><p>In this example:</p><ul><li>this::loadUser is a method reference to the loader.</li><li>300 is the TTL in seconds, or five minutes.</li><li>getUser does not contain explicit hit-or-miss logic.</li><li>On a miss, ReadThroughCache calls loadUser automatically.</li></ul><p>Real code should use a safer key parser than split, distinguish a cached not-found marker from a true miss, and define what happens when loading fails.</p><h3>1.3 Why application code becomes cleaner</h3><p>Without read-through, every caller might repeat this sequence:</p><pre>check cache → test for miss → query database → cache result → return result</pre><p>With read-through, callers use one operation:</p><pre>get value</pre><p>The repeated workflow is centralized in the loader and cache layer. This reduces the chance that one service forgets to populate the cache, uses the wrong TTL, or handles a not-found result differently.</p><h3>1.4 Benefits</h3><ul><li>One loader defines how a data type is retrieved.</li><li>Application read code becomes shorter.</li><li>Cache fills happen consistently on misses.</li><li>Several callers can share the same loading rules.</li><li>Request coalescing can be implemented once in the cache layer.</li><li>Metrics for hits, misses, load time, and load failures can be centralized.</li></ul><h3>1.5 Costs and limitations</h3><ul><li>The cache layer must understand how keys map to data access rules.</li><li>It may need database credentials or access to another service.</li><li>Loader errors and timeouts must be handled inside the layer.</li><li>The first request for a cold key still waits for the source.</li><li>A loader can overload the database during a cold start.</li><li>Read-through does not explain how changed data is invalidated.</li><li>Debugging can be less obvious because a simple get may secretly perform a database query.</li></ul><h3>Cross-questions</h3><p><strong>Does read-through remove database reads?</strong><br>No. It avoids database reads on hits. A miss still uses the database through the loader.</p><p><strong>Is read-through the same as cache-aside?</strong><br>The runtime steps are similar. The important difference is ownership: cache-aside puts miss logic in application code, while read-through hides it inside a cache-aware layer.</p><p><strong>Does read-through keep entries fresh after a database update?</strong><br>Not by itself. It defines how missing values are loaded. A separate write, invalidation, or expiration strategy is still required.</p><p><strong>What happens if two requests miss the same key together?</strong><br>Without protection, both may call the loader. A good implementation can use single-flight loading so one request loads the value while the others wait for the same result.</p><h3>2. Write-Through Cache</h3><p>In a write-through cache, the application sends a write to the cache layer. The layer writes the value to the database and then maintains the cached copy.</p><p>The layer reports normal success only after the required write path finishes.</p><h3>2.1 Write-through flow</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*p2aalnMYrjKuVBf-XKBBng.png" /></figure><p>Step by step:</p><ol><li>The application calls set on the cache-aware layer.</li><li>The layer validates or transforms the input if needed.</li><li>Its writer saves the value to the database.</li><li>If the database write succeeds, the layer stores the final value in the cache.</li><li>The layer reports success to the application.</li></ol><p>The database should remain the durable source of truth. The phrase “write-through” means the write passes through the cache layer to durable storage; it does not mean the cache replaces the database.</p><h3>2.2 Java example</h3><pre>class UserService {<br>    private final WriteThroughCache&lt;User&gt; cache =<br>        new WriteThroughCache&lt;&gt;(this::writeUser, 300);<br>void writeUser(String key, User value) {<br>        String userId = key.split(&quot;:&quot;)[1];<br>        database.updateUser(userId, value);<br>    }<br>void replaceUser(String userId, User userData) {<br>        cache.set(&quot;user:&quot; + userId, userData);<br>    }<br>}</pre><p>replaceUser does not explicitly update the database and delete the cache entry. The shared cache layer owns that process.</p><p>In production, the writer should also handle validation, concurrency versions, database-generated values, timeouts, and partial failures.</p><h3>2.3 Why reads after writes can be faster</h3><p>With cache-aside and delete-on-write, the first read after a write misses because the key was deleted. With write-through, the new value is already cached, so a following read can be a hit.</p><p>This is especially useful when users usually read an object immediately after changing it — for example, opening a profile after saving it.</p><h3>2.4 Benefits</h3><ul><li>One writer defines how a data type is saved.</li><li>Application write code becomes smaller and more consistent.</li><li>The new value is normally cached immediately after the write.</li><li>The first read after a write does not need to rebuild the entry.</li><li>Validation, serialization, version checks, and metrics can be centralized.</li><li>Manual “write database, then invalidate cache” code is reduced.</li></ul><h3>2.5 Costs and limitations</h3><ul><li>Every write waits for the durable database operation.</li><li>Cache-layer validation, retries, or replication add more latency.</li><li>The cache-aware layer is now part of the critical write path.</li><li>A problem in that layer can block or delay application writes.</li><li>A database success followed by cache failure creates a partial failure.</li><li>Every writer must use the same path or separately invalidate the cache.</li><li>Writing values that are never read wastes cache space.</li></ul><h3>Cross-questions</h3><p><strong>Does write-through mean “write only to the cache now and save to the database later”?</strong><br>No. That is normally called write-behind or write-back caching. Write-through waits for the durable write before reporting ordinary success.</p><p><strong>Are write-through writes faster than direct database writes?</strong><br>Usually not. They still include the database write and add cache-layer work. Their benefit is simpler coordination and a ready cached value, not faster durable writes.</p><p><strong>Can write-through guarantee that users always read the latest data?</strong><br>Only if all relevant writers use the coordinated path, writes are ordered correctly, and failure cases are handled. Direct database changes can still make the cache stale.</p><p><strong>Should the cache be updated before the database?</strong><br>Normally no. If the database then rejects the write, the cache would contain a value that was never durably saved.</p><h3>3. Combining Read-Through and Write-Through</h3><p>The two patterns solve different halves of data access, so they are often combined:</p><ul><li>Read-through handles hits and automatically loads misses.</li><li>Write-through saves changes and refreshes the cached value.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*T5e7BLRG9RknlI3Thkq1PQ.png" /></figure><p>To callers, the combination can look like one data store:</p><pre>get(key)        → cached hit or automatic load<br>set(key, value) → durable write and cache update</pre><h3>3.1 What the shared layer must own</h3><p>A combined layer normally needs rules for:</p><ul><li>Key construction and versioning.</li><li>Serialization and deserialization.</li><li>TTL selection.</li><li>Loading missing data.</li><li>Negative caching.</li><li>Writing durable data.</li><li>Database-generated values.</li><li>Concurrency control.</li><li>Error handling and retries.</li><li>Metrics, tracing, and logging.</li></ul><p>This is more than a simple key-value cache. It is a real data access component and should be treated like production application code.</p><h3>3.2 The bypass problem</h3><p>The model works only when writers do not silently bypass it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*jMUt7-jMtBds36rMBEbo_Q.png" /></figure><p>If direct writes are unavoidable, they must publish reliable change events or explicitly invalidate the correct keys.</p><h3>Cross-questions</h3><p><strong>Does combining the patterns make the cache the source of truth?</strong><br>No. The database should still be the durable authority. The cache-aware layer is the access path, while cached values remain replaceable copies.</p><p><strong>Can different services use different programming languages?</strong><br>Yes, but a shared network service or a precisely defined protocol may be needed. Separate libraries must agree on keys, formats, versions, TTLs, and error behavior.</p><p><strong>What if a maintenance script writes directly to the database?</strong><br>It can leave cached values stale. The script should use the shared write path or trigger invalidation/change events.</p><h3>4. Comparison with Cache-Aside</h3><p>Read-through and write-through move behavior into a cache-aware layer. Cache-aside keeps it visible in the application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1019/1*4VCFZ4seKYsi_O0AgQVy0A.png" /></figure><h3>4.1 When to use cache-aside</h3><p>Cache-aside is often suitable when:</p><ul><li>The cache should remain an optional optimization.</li><li>Different data types need different caching behavior.</li><li>Application code needs detailed control.</li><li>Existing services already write directly to the database.</li><li>The caching product has no loader or writer hooks.</li><li>You want to add caching gradually around an existing system.</li></ul><p>It is the most common starting point because it can be introduced without replacing the normal data access path.</p><h3>4.2 When to use read-through</h3><p>Read-through is often suitable when:</p><ul><li>Many callers load the same data in the same way.</li><li>Miss-handling code is being repeated.</li><li>A reliable, well-monitored loader is available.</li><li>Cold-key latency is acceptable.</li><li>Cache population should follow one shared policy.</li><li>The cache library or wrapper supports single-flight loading.</li></ul><p>Read-through does not remove the need for a freshness strategy.</p><h3>4.3 When to use write-through</h3><p>Write-through is often suitable when:</p><ul><li>Reads commonly follow writes.</li><li>Slower, coordinated writes are acceptable.</li><li>All writers can use the cache-aware path.</li><li>The writer can perform validation and concurrency checks.</li><li>Database errors and partial failures are well defined.</li><li>Avoiding the post-write cache miss is valuable.</li></ul><p>Write-through provides fresher read-after-write behavior only when bypass writes are prevented or reliably communicated.</p><h3>Cross-questions</h3><p><strong>Which pattern is always best?</strong><br>None. The choice depends on ownership, failure requirements, freshness, write frequency, adoption cost, and available cache technology.</p><p><strong>Can a system use read-through for one data type and cache-aside for another?</strong><br>Yes. Patterns can be selected per feature, but consistency within each data type is important.</p><p><strong>Why is write-through listed as “not a read pattern”?</strong><br>It defines how writes are processed. It says nothing by itself about how cache misses are loaded. A system can combine it with read-through or another read strategy.</p><h3>5. Failure Handling</h3><p>Read-through and write-through centralize failures as well as normal behavior. The cache layer needs explicit rules for each possible failure.</p><h3>5.1 Read-through miss failure</h3><p>If a cache miss occurs and the loader cannot reach the database, the cache layer cannot produce a fresh value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0dwD_Aefu98JFZA0QSdVBw.png" /></figure><p>Possible responses include:</p><ul><li>Return an error.</li><li>Serve a separately retained stale value.</li><li>Return a safe default or reduced response.</li><li>Start a background refresh and use a temporary fallback.</li></ul><p>The correct response depends on the meaning of the data. A stale product description may be acceptable. A stale permission decision may grant access incorrectly and should normally fail safely.</p><p>The layer must distinguish not found from failed to load. A database timeout must not be cached as if the record does not exist.</p><h3>5.2 Preventing repeated failed loads</h3><p>If the database is unavailable, thousands of misses may repeatedly call the loader. Protections include:</p><ul><li>Short loader timeouts.</li><li>Circuit breakers.</li><li>Exponential backoff with jitter.</li><li>Single-flight loading per key.</li><li>Global concurrency limits.</li><li>Rate limiting and load shedding.</li><li>Briefly caching a distinct error state only when its semantics are safe.</li></ul><p>Error caching must be used carefully. A temporary failure should not look like a valid not-found result.</p><h3>5.3 Write-through: database write fails</h3><p>If the durable write fails:</p><ol><li>Do not install the new value in the cache.</li><li>Leave the previously valid cached value unchanged or invalidate it if its correctness is uncertain.</li><li>Report the write failure.</li></ol><p>This prevents the cache from claiming that an unsaved update succeeded.</p><h3>5.4 Write-through: database succeeds, cache update fails</h3><p>This is a partial failure:</p><pre>Database contains new value → cache may contain old value</pre><p>The layer should make a best-effort attempt to delete or mark the entry stale. A later read can then reload the committed database value.</p><pre>class UserService {<br>    WriteResult writeThroughSet(String key, Object value) {<br>        database.write(key, value);<br><br>        try {<br>            // Read back the final stored value. Database defaults, triggers,<br>            // normalization, or computed columns may have changed it.<br>            Object finalValue = database.read(key);<br>            cache.store(key, finalValue, 300);<br>        } catch (CacheError e) {<br>            bestEffortDelete(key);<br>            recordMetric(&quot;write_through.cache_store_failed&quot;);<br><br>            // The durable write already committed. Retrying the complete<br>            // business operation may repeat side effects.<br>            return WriteResult.COMMITTED_WITH_CACHE_MISS;<br>        }<br><br>        return WriteResult.COMMITTED;<br>    }<br>}</pre><h3>5.5 Why a full retry can be unsafe</h3><p>Suppose a command charges a payment and then the cache update fails. Repeating the complete command could charge the customer twice unless the operation uses an idempotency key.</p><p>After a known database commit, retry only the failed cache maintenance step or use a reliable change event. Do not blindly repeat the entire business write.</p><h3>5.6 Can database and cache updates be one transaction?</h3><p>Usually they are separate systems and cannot share a simple atomic transaction. An atomic transaction means every operation commits together or none does.</p><p>Practical designs accept the partial-failure possibility and use:</p><ul><li>Best-effort invalidation.</li><li>Finite TTLs.</li><li>Retry queues.</li><li>Change-data-capture events.</li><li>Transactional outbox records.</li><li>Version checks during reads and writes.</li></ul><h3>Cross-questions</h3><p><strong>If the cache store fails after a database commit, did the user’s write fail?</strong><br>The durable data change succeeded. The API should communicate according to its contract, but it should not incorrectly imply that nothing happened. Internally, the cache repair should be retried.</p><p><strong>Can a stale value be served during a read-through loader outage?</strong><br>Only when the feature explicitly allows it and the system has retained that stale value. Safety and freshness requirements decide this.</p><p><strong>Why read the saved value back before caching it?</strong><br>The database may add defaults, run triggers, normalize fields, calculate columns, or reject part of the input. The returned stored value is more authoritative than the submitted object.</p><h3>6. Consistency Considerations</h3><p>Write-through is often described as keeping cache and database “in sync.” That statement is true only under specific assumptions.</p><h3>6.1 All writers must use or notify the same path</h3><p>If one service uses write-through and another writes directly to the database, the direct write bypasses cache maintenance.</p><pre>Service A → write-through layer → database Alice + cache Alice<br>Service B → direct database write → database Bob + cache still Alice</pre><p>Ways to control this include:</p><ul><li>Restrict database write permissions to the shared writer.</li><li>Require all services to use a single data access API.</li><li>Publish database change events that invalidate or refresh entries.</li><li>Periodically reconcile selected critical cached values.</li><li>Use short TTLs as a final safety limit.</li></ul><h3>6.2 Simultaneous writes need ordering</h3><p>Two writers can start from the same old version. Without protection, the later completion may accidentally overwrite a newer intent.</p><p>Optimistic locking adds a version number:</p><pre>class UserService {<br>    void writeUser(String key, Object value, long expectedVersion) {<br>        boolean updated = database.updateIfVersionMatches(<br>            key,<br>            value,<br>            expectedVersion<br>        );<br><br>        if (!updated) {<br>            throw new ConcurrentWriteError();<br>        }<br><br>        Object finalValue = database.get(key);<br>        cache.store(key, finalValue, 300);<br>    }<br>}</pre><p>If the current version differs from expectedVersion, another writer has already changed the data. The write is rejected instead of silently overwriting that change.</p><h3>6.3 The cache must not reverse database order</h3><p>Even when database writes are correct, cache stores can finish out of order:</p><pre>Write A commits database version 6<br>Write B commits database version 7<br>Cache B stores version 7<br>Cache A arrives late and stores version 6  ← stale</pre><p>Mitigations include version-aware cache writes, compare-and-set, or storing a version with the value and refusing older versions.</p><h3>6.4 Database transformations matter</h3><p>The input object may differ from the saved row because the database can apply:</p><ul><li>Default values.</li><li>updated_at timestamps.</li><li>Triggers.</li><li>Generated identifiers.</li><li>Computed columns.</li><li>Normalization.</li><li>Constraints and stored procedures.</li></ul><p>The writer should cache the database’s returned final row, not merely the original request object.</p><h3>6.5 Read-your-writes is not global consistency</h3><p><strong>Read-your-writes consistency </strong>means a caller can read its own successful update. Write-through can help because it immediately prepares a cached value.</p><p>It does not automatically guarantee that every user in every region sees the new value at exactly the same moment. Replication delay, local caches, CDNs, and network partitions may still create temporary differences.</p><h3>Cross-questions</h3><p><strong>Does a five-minute TTL solve direct-write inconsistency?</strong><br>It limits how long stale data normally remains, but users can still see incorrect data during those five minutes. Critical data needs active invalidation or stronger controls.</p><p><strong>Is a timestamp always safe for ordering writes?</strong><br>Not necessarily. Clocks can differ across machines and timestamp precision can collide. Database-generated monotonic versions are often easier to reason about.</p><p><strong>Can optimistic locking prevent all cache races?</strong><br>It protects database writes from lost updates. Cache stores still need ordering or version checks so an older completion cannot replace a newer cached value.</p><h3>7. Latency and Cold Starts</h3><p>These patterns change where the user waits, but they do not remove the cost of database work.</p><h3>7.1 Write latency</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cL8sPNxA9w81RuXJ2u8a9w.png" /></figure><p>Write-through may add:</p><ul><li>Validation and formatting.</li><li>A database read-back.</li><li>Cache replication.</li><li>Serialization.</li><li>Network calls.</li><li>Retries and version checks.</li></ul><p>This does not make write-through bad. It means the extra consistency and convenience must be worth the latency.</p><h3>7.2 Cold-cache behavior</h3><p>Read-through hides miss handling from application code, but a cold miss still requires the complete source read.</p><pre>Warm hit: application → cache → application<br>Cold miss: application → cache → loader → database → cache → application</pre><p>After a restart or cache flush, many keys can be cold at once. The database may see a sudden traffic increase.</p><h3>7.3 Cold-start protections</h3><ul><li>Pre-warm only the most popular keys.</li><li>Use per-key single-flight loading.</li><li>Add TTL jitter so keys do not expire together later.</li><li>Shift production traffic gradually.</li><li>Rate-limit loader concurrency.</li><li>Retain safe stale values during refresh.</li><li>Confirm database headroom before flushing a large cache.</li></ul><h3>7.4 Hit latency can still become slow</h3><p>A cache hit is not automatically fast. Large values, network distance, overloaded cache nodes, connection-pool waits, serialization, and replication can increase hit latency. Track p50, p95, and p99 rather than assuming hits meet the latency target.</p><h3>Cross-questions</h3><p><strong>Does read-through improve the first request for a new key?</strong><br>Usually no. The first request still waits for the loader. It mainly simplifies code and speeds later requests.</p><p><strong>Why not pre-warm the entire database?</strong><br>Most data may never be read, memory is limited, and bulk loading can overload both the database and cache. Pre-warm the measured hot set.</p><p><strong>Can write-through reduce total request latency?</strong><br>It makes writes slower but may make immediate later reads faster. Evaluate the complete user workflow, not one operation in isolation.</p><h3>8. Implementation Notes</h3><p>The implementation depends on whether the cache is local, shared, or a dedicated data grid.</p><h3>8.1 Local cache libraries</h3><p>Read-through is common in local in-process libraries. A loader function runs when a key is absent.</p><pre>LoadingCache&lt;String, User&gt; cache = Caffeine.newBuilder()<br>    .maximumSize(10_000)<br>    .expireAfterWrite(Duration.ofMinutes(30))<br>    .build(key -&gt; database.getUser(key));<br><br>User user = cache.get(&quot;user:123&quot;);</pre><p>This is fast because it avoids a network call to a shared cache. However, every application instance has its own entries, loaders may run separately on different servers, and invalidation must reach every local cache.</p><h3>8.2 Shared caches such as Redis and Memcached</h3><p>Redis and Memcached are normally general-purpose key-value systems. By default, they do not know:</p><ul><li>Which table stores a user.</li><li>How authorization should work.</li><li>Which fields belong in a response.</li><li>How database errors should be interpreted.</li><li>Which keys a product update should affect.</li></ul><p>A wrapper library or service supplies that behavior.</p><pre>class ReadThroughCache&lt;T&gt; {<br>    private final Cache&lt;T&gt; cache;<br>    private final Function&lt;String, T&gt; loader;<br>    private final int ttlSeconds;<br><br>    ReadThroughCache(<br>        Cache&lt;T&gt; cache,<br>        Function&lt;String, T&gt; loader,<br>        int ttlSeconds<br>    ) {<br>        this.cache = cache;<br>        this.loader = loader;<br>        this.ttlSeconds = ttlSeconds;<br>    }<br><br>    T get(String key) {<br>        T cached = cache.get(key);<br>        if (cached != null) {<br>            return cached;<br>        }<br><br>        T value = loader.apply(key);<br>        if (value != null) {<br>            cache.set(key, value, ttlSeconds);<br>        }<br>        return value;<br>    }<br>}</pre><p>This simplified example explains the shape of a loader but omits production features such as negative caching, single-flight loading, loader timeouts, metrics, serialization errors, and the distinction between a miss and a cached null.</p><h3>8.3 Dedicated data grid systems</h3><p>Some distributed caches and data grids provide loader and writer hooks directly. They may also offer:</p><ul><li>Partitioning.</li><li>Replication.</li><li>Transactions within the grid.</li><li>Querying and indexes.</li><li>Eviction policies.</li><li>Persistence connectors.</li></ul><p>These features can be useful, but they make the caching platform an active participant in business reads and writes. It needs timeouts, security, capacity planning, backups where appropriate, deployment testing, metrics, and clear operational ownership.</p><h3>8.4 Interface design</h3><p>A useful wrapper should make important outcomes visible. Instead of returning only null or throwing a generic exception, it may distinguish:</p><pre>HIT<br>LOADED<br>NOT_FOUND<br>LOAD_FAILED<br>WRITE_COMMITTED<br>WRITE_REJECTED<br>COMMITTED_WITH_CACHE_MISS</pre><p>The application can then respond correctly, while metrics show what actually happened.</p><h3>8.5 Testing checklist</h3><p>Test at least the following cases:</p><ol><li>Read hit.</li><li>Read miss and successful load.</li><li>Record not found.</li><li>Loader timeout or error.</li><li>Several concurrent misses for one key.</li><li>Successful write and cache store.</li><li>Database write rejection.</li><li>Database commit followed by cache failure.</li><li>Two concurrent writes with different versions.</li><li>A direct database update and its invalidation event.</li><li>Cache restart or complete cold start.</li><li>Old serialized entries during a deployment.</li></ol><h3>8.6 Monitoring checklist</h3><p>Track:</p><ul><li>Cache hits, misses, and evictions.</li><li>Loader calls, latency, errors, and timeouts.</li><li>Writer calls, latency, conflicts, and errors.</li><li>Database query and write load.</li><li>Cache store and invalidation failures.</li><li>Single-flight waiters and lock timeouts.</li><li>Value versions and stale-data incidents.</li><li>Cold-start duration and database impact.</li><li>End-to-end p50, p95, and p99 latency.</li></ul><h3>Cross-questions</h3><p><strong>If a wrapper around Redis loads data on a miss, is that read-through?</strong><br>Yes, from the application’s point of view, if callers use the wrapper and the wrapper owns the automatic loader behavior. Redis itself is still only the storage component.</p><p><strong>Should the loader contain business authorization?</strong><br>Authorization must be enforced somewhere before private data is returned. Be careful not to cache a privileged response under a key shared with unauthorized users.</p><p><strong>Is a local loading cache safe in a multi-server system?</strong><br>It can be, but each server has an independent copy. The design must tolerate temporary differences or provide invalidation to every instance.</p><h3>End-to-End Combined Example</h3><p>Consider a user-profile service using both patterns.</p><h3>First read</h3><pre>1. Service calls get(&quot;user:v2:123&quot;).<br>2. Cache layer reports a miss.<br>3. Loader reads user 123 from the database.<br>4. Database returns Alice, version 7.<br>5. Layer caches Alice with version 7 and a five-minute TTL.<br>6. Service receives Alice.</pre><h3>Successful write</h3><pre>1. Service calls set(&quot;user:v2:123&quot;, updatedAlice, expectedVersion=7).<br>2. Writer asks the database to update only version 7.<br>3. Database commits version 8 and returns its final stored row.<br>4. Layer caches the returned version 8 value.<br>5. Layer reports success.<br>6. The next read is a cache hit for version 8.</pre><h3>Concurrent-write conflict</h3><pre>1. Service A and Service B both read version 8.<br>2. Service A successfully writes version 9.<br>3. Service B tries to write using expectedVersion=8.<br>4. Database rejects Service B because currentVersion=9.<br>5. Service B reloads the latest value or asks the user to resolve the conflict.</pre><h3>Cache failure after commit</h3><pre>1. Database successfully commits version 10.<br>2. Cache store fails.<br>3. Layer makes a best-effort deletion of the old cached value.<br>4. It records a partial-failure metric and schedules repair if needed.<br>5. The next read-through miss reloads version 10.</pre><h3>Review Questions and Answers</h3><h3>1. What problem does read-through solve?</h3><p>It centralizes cache-miss handling. Callers ask for a key, and the cache-aware layer loads and stores missing data automatically.</p><h3>2. What problem does write-through solve?</h3><p>It centralizes the durable write and cache-update process so application code does not repeatedly coordinate both systems.</p><h3>3. Does read-through solve invalidation?</h3><p>No. It explains how absent entries are loaded, not how old entries are removed after the source changes.</p><h3>4. What is the difference between write-through and write-behind?</h3><p>Write-through waits for durable storage before ordinary success. Write-behind accepts the cached write first and persists it asynchronously later, which is faster but risks losing uncommitted data.</p><h3>5. Why must all writers follow or notify the write-through path?</h3><p>A direct database write can change the source without changing the cache, leaving a stale cached copy.</p><h3>6. What is the safest response when the database write fails?</h3><p>Do not cache the proposed new value. Report failure and leave or invalidate the previous entry according to whether it remains trustworthy.</p><h3>7. What if the database succeeds but the cache store fails?</h3><p>The data is durably committed. Delete or mark the cached entry stale, record the partial failure, and allow a later read to reload the authoritative value.</p><h3>8. Why can the submitted value differ from the saved value?</h3><p>Database defaults, triggers, generated fields, timestamps, normalization, constraints, and computed columns can change it.</p><h3>9. Does read-through remove cold-start load?</h3><p>No. It moves cold-miss logic behind the cache interface. The loaders still contact the database.</p><h3>10. What protects simultaneous writes?</h3><p>Database transactions, version numbers, optimistic locking, and compare-and-set operations help preserve correct ordering and prevent lost updates.</p><h3>11. Is the cache layer now critical infrastructure?</h3><p>For read-through it is important, though some designs can bypass it. For write-through it is directly on the write path, so its latency and availability are especially critical.</p><h3>12. When is centralization worth the added complexity?</h3><p>It is valuable when many callers need identical read or write behavior, duplication is causing mistakes, and the organization can reliably operate one shared access layer.</p><h3>Read-Through and Write-Through Summary</h3><p>Read-through and write-through move repeated caching responsibilities from business code into a cache-aware layer.</p><p>In read-through, a loader retrieves missing values and fills the cache. This simplifies reads but does not remove cold-cache latency, loader failures, or the need for invalidation.</p><p>In write-through, a writer saves data durably before maintaining the cached copy and reporting ordinary success. This usually makes immediate reads hit the new value, but it increases write-path latency and creates important partial-failure cases.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ff824899459" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Caching! everything You need to know : Part 2]]></title>
            <link>https://medium.com/@sarfaraz_alam/caching-everything-you-need-to-know-part-2-e22f14405508?source=rss-e4ea22b08fc5------2</link>
            <guid isPermaLink="false">https://medium.com/p/e22f14405508</guid>
            <category><![CDATA[caching-algorithms]]></category>
            <category><![CDATA[cache]]></category>
            <category><![CDATA[caching]]></category>
            <category><![CDATA[caching-strategies]]></category>
            <category><![CDATA[dns]]></category>
            <dc:creator><![CDATA[Sarfaraz]]></dc:creator>
            <pubDate>Wed, 23 Sep 2026 19:28:37 GMT</pubDate>
            <atom:updated>2026-09-23T19:31:56.971Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*npg7G3dLLg2JvO_egRR-mA.png" /></figure><p><a href="https://medium.com/@sarfaraz_alam/caching-everything-you-need-to-know-part-1-5b0273f64a87">Caching! everything You need to know : part 1</a></p><h3>Cache-Aside Pattern: Application-Managed Caching</h3><p>Every caching design starts with a simple question:</p><blockquote><strong><em>Who decides what enters the cache, when it is refreshed, and when it is removed?</em></strong></blockquote><p>In the cache-aside pattern, the application makes those decisions.</p><p>When reading data, the application checks the cache first. If the value is not there, the application reads it from the database, places a copy in the cache, and returns it. When changing data, the application normally updates the database first and then deletes the old cached copy.</p><p>Cache-aside is also called lazy loading because the application does not fill the cache in advance. It loads an item only after a request needs it.</p><p>The pattern works with ordinary key-value systems such as Redis and Memcached. The cache does not need to understand database tables, relationships, or business rules. That logic remains in the application.</p><p>This separation is both the strength and the cost of cache-aside:</p><ul><li>Strength: The application has complete control over what is cached and how.</li><li>Cost: Every code path and service that reads or writes the data must follow the same rules.</li></ul><h3>Important Terms</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/1*oiutJzrJjc32XIiSbRKX8w.png" /></figure><h3>1. How Cache-Aside Works</h3><p>Cache-aside has separate flows for reads and writes. The application coordinates both flows, while the database remains the source of truth.</p><h3>1.1 The read flow</h3><p>When the application needs an item, it follows these steps:</p><ol><li>Build the cache key.</li><li>Ask the cache for that key.</li><li>If the key exists, return the cached value. This is a cache hit.</li><li>If the key does not exist, read the value from the database. This is a cache miss.</li><li>Store the database result in the cache with a TTL.</li><li>Return the result to the caller.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*qfaETa8vTfiF5a3ZDTJGgg.png" /></figure><h3>Read pseudocode</h3><pre>function getUser(userId):<br>    key = &quot;user:v1:&quot; + userId</pre><pre>cachedValue = cache.get(key)<br>    if cachedValue exists:<br>        return cachedValue</pre><pre>user = database.findUser(userId)</pre><pre>if user does not exist:<br>        cache.set(key, NOT_FOUND, ttl = 30 seconds)<br>        return not found</pre><pre>cache.set(key, user, ttl = 10 minutes)<br>    return user</pre><p>Notice that the cache is not contacted by the database. The application explicitly calls both systems.</p><h3>1.2 Cold and warm caches</h3><p>A cold cache is empty or contains very little useful data. This often happens after a restart, deployment, cache flush, or major key-format change. Most early requests miss and reach the database.</p><p>A warm cache already contains frequently requested entries. More requests become hits, so response time and database load improve.</p><p>Because cache-aside loads data lazily, a cold cache warms up naturally as requests arrive. The disadvantage is that users making the first requests pay the slower database cost.</p><p>For especially popular data, a system may pre-warm selected keys before opening traffic. Pre-warming is an optional addition; it is not the normal lazy behavior of cache-aside.</p><h3>1.3 The write flow</h3><p>A common cache-aside write flow is:</p><ol><li>Update the database.</li><li>Confirm that the database update succeeded.</li><li>Delete the related cache key or keys.</li><li>Return success.</li></ol><p>The next read misses the cache, loads the new database value, and repopulates the cache.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*Tl0Gs_GrvqXmChAKuTW9nA.png" /></figure><h3>Write pseudocode</h3><pre>function updateUser(userId, changes):<br>    updatedUser = database.updateUser(userId, changes)</pre><pre>if database update failed:<br>        return error</pre><pre>cache.delete(&quot;user:v1:&quot; + userId)<br>    return updatedUser</pre><p>The order matters. If the application deletes the key before updating the database, another request could repopulate the cache with the old database value during the gap.</p><h3>Cross-questions</h3><p>Why not read the database first on every request and then check the cache?<br>That would defeat the main purpose of caching. The database work would already have happened before the cache could help.</p><p>Does every cache miss mean something is wrong?<br>No. A miss is expected for a new key, an expired entry, a recently invalidated entry, or the first request after a cold start. The concern is an unexpectedly high or rapidly changing miss rate.</p><p>Is the cache the source of truth?<br>No. In normal cache-aside, the database is the durable source of truth. The cache contains disposable copies.</p><h3>2. Why Delete Instead of Update?</h3><p>After changing the database, the application has two apparent choices:</p><ol><li>Update the cached value directly.</li><li>Delete the cached value and let the next read rebuild it.</li></ol><p>Deleting is usually safer.</p><h3>2.1 Updating the cache duplicates logic</h3><p>The value stored in the cache may not be identical to one database row. It may include:</p><ul><li>Data joined from several tables.</li><li>Calculated fields.</li><li>Permission-dependent fields.</li><li>Formatting or localization.</li><li>Related counts or summaries.</li></ul><p>If write code tries to reconstruct that cached value, it duplicates the logic used by read code. The two versions can drift apart and produce incorrect results.</p><p>Deleting avoids that duplication. The established read path rebuilds the value correctly when it is next needed.</p><h3>2.2 One write may affect several cached views</h3><p>Changing a product could affect keys such as:</p><pre>product:v2:123<br>category-products:v4:shoes:page:1<br>search:v3:running-shoes:page:1<br>seller-summary:v1:88<br>homepage:v7:featured-products</pre><p>Updating every cached representation is difficult. Deleting affected keys is simpler, although the application still needs a clear record of which keys depend on the changed data.</p><h3>2.3 Delete is normally idempotent</h3><p>Deleting the same key more than once has the same final result: the key is absent. This makes retries simpler.</p><p>Updating a cached value repeatedly can be more dangerous if the update is not a complete replacement — for example, incrementing a count twice by mistake.</p><h3>2.4 Delete reduces the inconsistent window</h3><p>If the application writes the database and then updates the cache, concurrent writers can finish out of order. An older writer may overwrite a newer cached value.</p><p>Deleting does not guarantee perfect consistency, but it avoids directly installing a potentially old value. The next read asks the source of truth for the current state.</p><h3>Trade-off of deletion</h3><p>The first read after deletion becomes a miss and is slower. If an item is extremely hot, that miss can also cause a stampede. Per-key locking, background refresh, or write-through caching may be considered for such cases.</p><h3>Cross-questions</h3><p>Is updating the cache after a write always wrong?<br>No. It can be reasonable when the cached value is simple, the write result contains the complete new value, the key relationships are well understood, and immediate cache availability matters. It simply requires more careful concurrency handling.</p><p>Why update the database before deleting the cache?<br>The database must change first because it is the source of truth. If deletion happens first, a concurrent reader may miss the cache, read the still-old database value, and put that old value back into the cache.</p><p>What if the database write succeeds but cache deletion fails?<br>The stale value may remain until its TTL expires. This is why finite TTLs, retries, an invalidation queue, and monitoring are valuable safety measures.</p><h3>3. Cache Key Design</h3><p>A cache key is part of the data model. Poor key design can return the wrong user’s data, mix different response versions, or create so many unique entries that the cache becomes ineffective.</p><h3>3.1 A useful key structure</h3><p>A common structure is:</p><pre>namespace:version:entity:identifier:variant</pre><p>Examples:</p><pre>shop:v2:product:123<br>shop:v2:product:123:language:en<br>shop:v2:search:query:boots:page:2:sort:price<br>tenant:42:v1:user:123:permissions</pre><h3>3.2 Properties of a good key</h3><p>A good key is:</p><ul><li>Deterministic: The same logical request always produces the same key.</li><li>Complete: Every input that can change the response is included.</li><li>Namespaced: Unrelated features cannot accidentally share a key.</li><li>Versioned: A format change can move traffic to a new key space safely.</li><li>Bounded in length: It does not contain uncontrolled or enormous input.</li><li>Safe: It does not reveal secrets or sensitive personal data.</li></ul><h3>3.3 Include every response-changing input</h3><p>Suppose an API response depends on the user ID, language, currency, page, and sort order. Omitting one creates a correctness bug.</p><p>Incorrect:</p><pre>products:shoes</pre><p>Better:</p><pre>catalog:v3:category:shoes:lang:en:currency:INR:page:2:sort:price-asc</pre><p>Parameters should use a canonical order. These two requests are logically equal:</p><pre>?page=2&amp;sort=price<br>?sort=price&amp;page=2</pre><p>They should produce the same cache key. Sorting and normalizing parameters prevents duplicate entries.</p><h3>3.4 Version keys when the value format changes</h3><p>Suppose the cached user object changes from version 1 to version 2. Changing the namespace from user:v1:123 to user:v2:123 prevents new code from trying to decode old entries.</p><p>This is called key versioning. Old versioned entries can expire naturally, avoiding a risky full-cache deletion during deployment.</p><h3>3.5 Multi-tenant and private data</h3><p>In a multi-tenant application, the tenant or organization ID must usually be part of the key:</p><pre>tenant:42:user:123</pre><p>Without tenant isolation, identical user IDs in two organizations could collide. For user-specific responses, the user or permission context may also be required.</p><p>Do not place raw passwords, access tokens, medical information, or other secrets in cache keys. Keys may appear in logs and monitoring tools. If sensitive input must affect the key, use a safe one-way hash where appropriate.</p><h3>3.6 High-cardinality keys</h3><p>Cardinality means the number of distinct possible values. A key pattern with high cardinality creates many unique entries.</p><p>For example, caching free-form search queries that are rarely repeated can create millions of keys with few hits. Before caching such data, measure how often identical requests actually repeat.</p><h3>Cross-questions</h3><p>Should a key contain the entire SQL query?<br>Usually not in raw form. Queries may be long, expose details, and differ in harmless formatting. A normalized representation or stable hash is usually safer.</p><p>Why include a version if there is already a TTL?<br>A TTL may leave incompatible values alive during a deployment. A new version switches new code to a clean key space immediately.</p><p>Can two services share the same keys?<br>Yes, but only if they agree on ownership, schema, serialization, TTL, and invalidation rules. Otherwise, separate namespaces are safer.</p><h3>4. TTLs and Staleness</h3><p>A TTL defines how long the cache may retain an entry. It is both a freshness control and a cleanup mechanism.</p><h3>4.1 Choosing a TTL</h3><p>There is no universal best TTL. Choose it by considering:</p><ul><li>How often the source data changes.</li><li>How harmful stale data would be.</li><li>How expensive a miss is.</li><li>How frequently the item is requested.</li><li>Whether reliable invalidation exists.</li><li>How much memory is available.</li></ul><p>Example starting points might look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*YUvfgoegp0T7pyJVojfedQ.png" /></figure><p>These are examples only. Business requirements should determine real values.</p><h3>4.2 Maximum staleness is not always equal to TTL</h3><p>If an entry is cached immediately before the source changes, it can remain stale for nearly the full TTL. With a 10-minute TTL, the worst normal staleness may therefore approach 10 minutes.</p><p>If explicit invalidation works, normal staleness may be much shorter. The TTL then acts as a backup limit when invalidation fails.</p><h3>4.3 TTL jitter</h3><p>If thousands of entries receive exactly the same TTL at the same time, they may expire together and create a load spike.</p><p>TTL jitter adds a random variation:</p><pre>Actual TTL = Base TTL + random variation</pre><pre>Example: 10 minutes ± 1 minute</pre><p>This spreads misses across time. Jitter should remain within the feature’s allowed freshness limit.</p><h3>4.4 Sliding and fixed expiration</h3><ul><li>Fixed expiration: The countdown begins when the entry is written. Reads do not extend it.</li><li>Sliding expiration: Each access extends the entry’s lifetime.</li></ul><p>Fixed expiration gives a clearer upper limit on staleness. Sliding expiration keeps popular entries alive but can allow an old value to remain indefinitely if invalidation is missed. For source-backed data, fixed expiration is often easier to reason about.</p><h3>4.5 Soft and hard TTLs</h3><p>Some systems use two expiration points:</p><ul><li>Soft TTL: The value may be served, but the system should begin refreshing it.</li><li>Hard TTL: The value must no longer be served.</li></ul><p>This supports stale-while-revalidate behavior: users receive a slightly old value quickly while one worker refreshes it in the background.</p><h3>Cross-questions</h3><p>Does a longer TTL always improve performance?<br>It often improves hit rate, but it can increase staleness and retain unused values longer. Performance is only one part of the decision.</p><p>Can an entry have no TTL if invalidation is perfect?<br>In theory, yes. In practice, invalidation is rarely perfect across every failure and code path. A finite backup TTL limits damage from missed invalidations.</p><p>Should every key use the same TTL?<br>No. Different data has different change rates, miss costs, and freshness requirements. Choose TTLs by data category or feature.</p><h3>5. Null and Negative Caching</h3><p>Sometimes the database correctly returns no record. If the application does not cache that result, repeated requests for the same missing item will repeatedly hit the database.</p><p>Negative caching stores a short-lived marker meaning “this item was not found.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*jIuahqiHx2oH4WfuJaW2EA.png" /></figure><h3>5.1 Why negative caching helps</h3><p>It protects the database from:</p><ul><li>Repeated requests for deleted resources.</li><li>Broken links or old client data.</li><li>Bots scanning random identifiers.</li><li>Application bugs that repeatedly request nonexistent records.</li><li>Cache penetration, where requests deliberately use keys unlikely to exist.</li></ul><h3>5.2 Use a distinct marker</h3><p>The application must distinguish among:</p><ol><li>The cache key is absent.</li><li>The key contains a NOT_FOUND marker.</li><li>The real stored value is null, if null is a valid value.</li></ol><pre>CACHE_MISS  ≠  CACHED_NOT_FOUND  ≠  VALID_NULL_VALUE</pre><p>Using a distinct serialized marker avoids ambiguity.</p><h3>5.3 Keep negative TTLs short</h3><p>Negative entries normally use a shorter TTL than positive entries. If a missing item is created shortly after the negative result is cached, users should not wait long before it becomes visible.</p><p>Example:</p><pre>Existing user TTL: 10 minutes<br>Missing user TTL:  15–60 seconds</pre><p>If the application creates the item, it should also delete any negative cache entry immediately.</p><h3>5.4 Security and random-key attacks</h3><p>An attacker can request millions of different nonexistent keys. Caching every negative response could fill the cache with useless markers.</p><p>Defenses may include:</p><ul><li>Rate limiting.</li><li>Authentication and input validation.</li><li>A maximum negative-entry TTL.</li><li>Separate memory limits or namespaces.</li><li>Probabilistic structures such as a Bloom filter for very large known-ID sets.</li></ul><h3>Cross-questions</h3><p>Is negative caching the same as caching an empty list?<br>Not exactly. An empty list may be a valid successful result. A negative entry says the requested entity or lookup does not exist. Both may be cached, but their meanings should remain clear.</p><p>Could negative caching hide a newly created record?<br>Yes, until the negative TTL ends, unless the create path invalidates that key. That is why negative TTLs are usually short.</p><p>Should errors such as database timeouts be negatively cached?<br>Usually no. “The database failed” is not the same as “the record does not exist.” Caching temporary errors as not-found results can turn a short failure into prolonged incorrect behavior.</p><h3>6. Failure Handling</h3><p>Cache-aside depends on two systems: the cache and the database. The application must handle failure in either one without creating excessive latency or incorrect data.</p><h3>6.1 Cache read failure</h3><p>If the cache times out or is unavailable, a common approach is to fail open:</p><ol><li>Stop waiting after a short cache timeout.</li><li>Read from the database.</li><li>Return the database result.</li><li>Record the cache error for monitoring.</li></ol><p>This preserves availability, but the database must be able to handle at least some fallback traffic. Otherwise, a cache outage can cause a database outage.</p><p>Useful protections include:</p><ul><li>Short cache timeouts.</li><li>Circuit breakers.</li><li>Database rate limits.</li><li>Request queues or load shedding.</li><li>Serving safe stale data where allowed.</li></ul><h3>6.2 Cache write failure during a read</h3><p>If a database read succeeds but cache.set fails, the application can usually still return the database value. The request is correct, but future requests may continue to miss.</p><p>Cache population is generally a best-effort optimization. It should not normally make an otherwise successful read fail.</p><h3>6.3 Database read failure</h3><p>If both the cache misses and the database read fails, the application cannot obtain the authoritative value. Options include:</p><ul><li>Return an error.</li><li>Serve an expired value from a separate stale store, if the feature allows it.</li><li>Return a reduced or default response.</li></ul><p>The application must not pretend that a timeout means “not found.”</p><h3>6.4 Database write failure</h3><p>If the database write fails, do not invalidate a correct cached value as though the change succeeded. Return an error and let the caller decide whether to retry.</p><h3>6.5 Cache invalidation failure after a successful write</h3><p>This is one of the most important failure cases:</p><pre>Database update succeeds → cache delete fails → stale cache remains</pre><p>Possible safeguards include:</p><ul><li>Retry the delete with a bounded retry policy.</li><li>Use a finite TTL so the stale value eventually disappears.</li><li>Publish invalidation events through a reliable queue.</li><li>Use a transactional outbox so the database change and invalidation event are recorded together.</li><li>Alert when invalidation failures rise.</li></ul><p>A transactional outbox writes an event record in the same database transaction as the business update. A background worker later publishes that event and retries if necessary. This avoids losing the intention to invalidate when the application crashes after committing the database change.</p><h3>Cross-questions</h3><p><strong>Should a user-facing read fail because the cache is down?</strong><br>Usually not when the cache is only an optimization. However, safely failing open requires database capacity controls.</p><p><strong>Should a successful database write be reported as failed because cache deletion failed?</strong><br>This depends on the product’s consistency promise. Often the durable write is reported as successful and invalidation is retried asynchronously. Retrying the whole write carelessly could duplicate non-idempotent changes.</p><p><strong>Why use short cache timeouts?</strong><br>A cache is supposed to make requests faster. Waiting several seconds for a failing cache before trying the database makes it a latency problem instead of an optimization.</p><h3>7. Common Race Conditions</h3><p>A race condition occurs when the result depends on the timing of concurrent operations. Each operation may look correct by itself, but an unexpected order creates stale data.</p><h3>7.1 Delete-before-write race</h3><p>This race occurs when a writer deletes the cache before updating the database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*03PZzkXtxblTH9I4p1mLGQ.png" /></figure><p>Main prevention: Write the database first, then delete the cache.</p><h3>7.2 Stale read repopulates after invalidation</h3><p>Even with write-then-delete, a reader that began earlier may cause a race:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*mzerQhnwstMmdYkU9uK8kA.png" /></figure><p>This timing window is often small but real.</p><p>Possible mitigations include:</p><ul><li>Short TTLs.</li><li>Version numbers in values or keys.</li><li>Compare-and-set operations.</li><li>Delayed double deletion in carefully designed systems.</li><li>Change events that trigger another invalidation.</li><li>Preventing cache population when the source version is older than a known version.</li></ul><p><strong>Delayed double deletion</strong> means deleting once after the write and again after a short delay. It can reduce some stale repopulation windows but is timing-dependent and not a complete correctness guarantee.</p><h3>7.3 Concurrent cache misses and stampede</h3><p>When a hot key expires, many readers can miss at once and all query the database.</p><p>The common solution is request coalescing or a single-flight mechanism:</p><ol><li>The first request obtains a short per-key lock.</li><li>It reads the database and fills the cache.</li><li>Other requests wait briefly or use stale data.</li><li>After the fill completes, waiting requests read the same cached value.</li></ol><p>Locks need timeouts so a crashed worker does not block the key indefinitely.</p><h3>7.4 Concurrent writers</h3><p>Two writers may update the same record:</p><pre>Writer A begins with version 5<br>Writer B begins with version 5<br>Writer B commits version 6<br>Writer A commits later and overwrites B</pre><p>This is primarily a database concurrency problem, not just a cache problem. Optimistic locking can require the expected version during an update. If the version has changed, the write is rejected and retried with fresh data.</p><p>After a successful update, the relevant cache entry is invalidated.</p><h3>7.5 Out-of-order invalidation messages</h3><p>In event-driven systems, invalidation or update events can arrive late or out of order. If events write cache values, include a monotonic version or timestamp and reject older versions. If events only delete keys, repeated deletion is generally safer because it is idempotent.</p><h3>Cross-questions</h3><p><strong>Does write-then-delete eliminate every race condition?</strong><br>No. It removes the common delete-before-write race but cannot prevent every stale reader from repopulating after deletion.</p><p><strong>Can a distributed lock guarantee perfect correctness?</strong><br>Not by itself. Lock expiry, network partitions, process pauses, and incorrect lock ownership can still cause problems. Locks should reduce duplicate work, while the database enforces critical correctness.</p><p><strong>Are race conditions likely in development?</strong><br>They may be rare on a developer’s machine and frequent under production concurrency. Load tests and deliberately controlled timing tests help expose them.</p><h3>8. When to Use Cache-Aside</h3><p>Cache-aside is a strong fit when:</p><ul><li>The workload is read-heavy.</li><li>The same data is requested repeatedly.</li><li>A cache miss can safely fall back to the database or service.</li><li>Slightly stale data is acceptable or can be bounded.</li><li>The application needs control over cache keys and TTLs.</li><li>The cache technology is a simple key-value store.</li><li>It is wasteful to cache data that may never be requested.</li></ul><p>Typical examples include:</p><ul><li>Product details.</li><li>Public user profiles.</li><li>Article or post content.</li><li>Configuration and reference data.</li><li>Search results with short TTLs.</li><li>Computed summaries and dashboard widgets.</li><li>External API responses that are safe to reuse.</li></ul><h3>When it may be a poor fit</h3><p>Consider another strategy, or avoid caching, when:</p><ul><li>Every read must reflect the most recent write.</li><li>The data changes more often than it is reused.</li><li>Requests are mostly unique.</li><li>Correct invalidation is too complex.</li><li>A miss is so expensive that lazy loading is unsafe.</li><li>Many services write the same data but cannot share invalidation rules.</li><li>The cache is required as part of a coordinated write transaction.</li></ul><p>Alternatives may include write-through caching, refresh-ahead, materialized views, database indexing, read replicas, or removing the expensive computation itself.</p><h3>Advantages and disadvantages</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*FmePv5PZ8oqUfCiXkVUZpg.png" /></figure><h3>Cross-questions</h3><p>Is cache-aside useful for write-heavy data?<br>Usually less so. Frequent writes repeatedly invalidate entries, giving them little time to produce hits. Measure whether reuse between writes is high enough to justify the complexity.</p><p>Can cache-aside be used with an external API instead of a database?<br>Yes. The source may be any slower authoritative service, provided its terms, privacy rules, and freshness requirements allow caching.</p><p>Does using Redis automatically mean the application uses cache-aside?<br>No. Redis is a tool. Cache-aside is an interaction pattern. Redis can also support sessions, queues, locks, write-through designs, and many other uses.</p><h3>9. Monitoring Cache-Aside</h3><p>Monitoring must cover the cache, the source of truth, and the application behavior connecting them.</p><h3>9.1 Core metrics</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*Qz8LBt_RLlQF6GBeiqN7Iw.png" /></figure><h3>9.2 Measure by feature or key group</h3><p>A single global hit ratio can be misleading. One highly effective feature can hide another feature with almost no hits.</p><p>Group metrics by safe, low-cardinality labels such as:</p><pre>cache=&quot;redis-primary&quot;<br>operation=&quot;get&quot;<br>result=&quot;hit&quot;<br>key_group=&quot;product-detail&quot;</pre><p>Do not use the full cache key or user ID as a metric label. That creates high-cardinality metrics and may leak sensitive information.</p><h3>9.3 Useful latency percentiles</h3><p>Track p50, p95, and p99 for:</p><ul><li>Cache hits.</li><li>Cache misses.</li><li>Database fallback calls.</li><li>Cache writes and deletes.</li><li>Complete user requests.</li></ul><p>A fast p50 with a very slow p99 may indicate network pauses, overloaded cache nodes, connection-pool exhaustion, or large values.</p><h3>9.4 Alerts worth considering</h3><p>Alert when:</p><ul><li>Hit ratio drops sharply from its normal baseline.</li><li>Cache timeouts or errors rise.</li><li>Database traffic rises as cache hits fall.</li><li>Evictions remain high.</li><li>Memory approaches its safe limit.</li><li>Invalidation failures occur repeatedly.</li><li>Miss latency exceeds the user-facing latency budget.</li><li>A cold-cache event causes an unusual source-load spike.</li></ul><p>Thresholds should be based on normal behavior and user impact rather than copied from another system.</p><h3>9.5 Logs and traces</h3><p>For debugging, distributed traces can show:</p><pre>Request → cache lookup → miss → database query → cache fill → response</pre><p>Logs should record the key group, outcome, duration, and error category without exposing full private values or credentials.</p><h3>9.6 Measure correctness, not only speed</h3><p>A cache can be fast and wrong. Where practical, sample a small portion of requests and compare cached results with the source of truth. Track stale-value incidents, invalidation lag, and data-version mismatches.</p><p>Sampling must be rate-limited so the monitoring itself does not overload the database.</p><h3>Cross-questions</h3><p><strong>Is a high hit ratio enough to prove success?</strong><br>No. Also examine correctness, user latency, database load, cache cost, and failure behavior.</p><p><strong>Why did the hit ratio fall after a deployment?</strong><br>Possible causes include a new key version, changed serialization, shorter TTLs, accidental parameter differences, cache flushes, or a new traffic pattern.</p><p><strong>Can a 60% hit ratio still be valuable?</strong><br>Yes. If misses involve a very expensive query or paid external API, even a moderate hit ratio may save substantial time and cost.</p><h3>End-to-End Example</h3><p>Suppose an online shop serves product 123.</p><h3>First read</h3><pre>1. Application builds key shop:v2:product:123.<br>2. Cache returns a miss.<br>3. Application reads product 123 from the database.<br>4. Database returns price ₹2,000.<br>5. Application caches the product for 10 minutes with TTL jitter.<br>6. User receives the product.</pre><h3>Later read</h3><pre>1. Application builds the same key.<br>2. Cache returns a hit.<br>3. User receives the cached product without a database query.</pre><h3>Product update</h3><pre>1. Administrator changes the price to ₹1,800.<br>2. Application commits ₹1,800 to the database.<br>3. Application deletes shop:v2:product:123.<br>4. The next reader misses, reads ₹1,800, and caches the fresh product.</pre><h3>If invalidation fails</h3><p>The cache may temporarily continue serving ₹2,000. The application retries invalidation, records a metric, and relies on the finite TTL as a final safety limit. Whether this temporary staleness is acceptable must be decided by the product requirement.</p><h3>Review Questions and Answers</h3><h3>1. Why is cache-aside called lazy loading?</h3><p>Because an entry is loaded only after a request needs it. The application does not automatically copy the entire database into the cache.</p><h3>2. Who is responsible for cache-aside logic?</h3><p>The application is responsible for constructing keys, checking the cache, reading the source on a miss, populating entries, choosing TTLs, and invalidating entries after writes.</p><h3>3. What is the safest common order for a write?</h3><p>Update the database first, confirm success, and then delete the cached entry. This keeps the database authoritative and reduces the risk of repopulating from an old database value.</p><h3>4. Why use both invalidation and a TTL?</h3><p>Invalidation normally removes stale values quickly. The TTL is a safety net when an invalidation is missed or fails.</p><h3>5. What is negative caching?</h3><p>It is temporarily caching a distinct marker that says a requested item does not exist. It prevents repeated database queries for the same missing item.</p><h3>6. Why is cache invalidation considered difficult?</h3><p>One data change may affect many cached representations, multiple services may write the data, failures can interrupt deletion, and concurrent reads can restore an old value after deletion.</p><h3>7. What happens during a cache stampede?</h3><p>Many requests miss the same popular key at once and all contact the source. Per-key locking, request coalescing, early refresh, and stale-while-revalidate can reduce the load.</p><h3>8. When should cache-aside not be the first choice?</h3><p>It is less suitable when strictly current reads are required, data changes constantly, requests rarely repeat, or the source cannot tolerate cold-cache misses.</p><h3>9. What should be monitored besides hit ratio?</h3><p>Monitor latency, errors, timeouts, source traffic, memory, evictions, invalidation failures, cache-fill activity, stampede protection, and stale-data incidents.</p><h3>10. What is the most important design principle?</h3><p>Treat the cache as a disposable optimization and keep the database or another durable service as the source of truth.</p><h3>Cache-Aside Summary</h3><p>In cache-aside, the application owns the caching behavior. It checks the cache before reading the database, fills the cache after a miss, and normally invalidates cached values after successful database writes.</p><p>The pattern is popular because it is flexible, works with simple key-value stores, and caches only data that is actually requested. Its main costs are application complexity, cold misses, stale data, and concurrency races.</p><p>Safe cache-aside design depends on several connected decisions:</p><ul><li>Build deterministic, complete, versioned, and safely namespaced keys.</li><li>Choose TTLs based on freshness risk and miss cost.</li><li>Update the source of truth before deleting cached copies.</li><li>Use negative caching carefully for repeated not-found requests.</li><li>Plan for cache, database, and invalidation failures.</li><li>Protect hot keys from stampedes.</li><li>Monitor correctness and source load, not only hit ratio.</li></ul><p>Cache-aside is not a promise of perfect consistency. It is a practical way to exchange a controlled amount of freshness and complexity for lower latency and lower source load.</p><p><a href="https://medium.com/@sarfaraz_alam/caching-everything-you-need-to-know-part-1-5b0273f64a87">Caching! everything You need to know : part 1</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e22f14405508" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Caching! everything You need to know : part 1]]></title>
            <link>https://medium.com/@sarfaraz_alam/caching-everything-you-need-to-know-part-1-5b0273f64a87?source=rss-e4ea22b08fc5------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b0273f64a87</guid>
            <category><![CDATA[caching]]></category>
            <category><![CDATA[cache]]></category>
            <category><![CDATA[caching-algorithms]]></category>
            <category><![CDATA[caching-strategies]]></category>
            <category><![CDATA[dns]]></category>
            <dc:creator><![CDATA[Sarfaraz]]></dc:creator>
            <pubDate>Tue, 22 Sep 2026 11:16:13 GMT</pubDate>
            <atom:updated>2026-09-23T19:31:15.716Z</atom:updated>
            <content:encoded><![CDATA[<h3>Caching Fundamentals: What Is a Cache?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*npg7G3dLLg2JvO_egRR-mA.png" /></figure><p>Reading data from a database or calling another service takes time. Under heavy traffic, even a small delay on each request can add up quickly and place a large amount of pressure on the system.</p><p>A cache is a fast storage layer that keeps temporary copies of frequently used data. When an application needs the same data again, it can read the cached copy instead of repeatedly going back to a slower database, API, file system, or remote service.</p><p>Caching can help a system:</p><ul><li>Respond to requests faster.</li><li>Reduce the number of database queries and external API calls.</li><li>Lower CPU, network, and infrastructure costs.</li><li>Handle more users with the same underlying resources.</li><li>Continue operating more smoothly during traffic spikes.</li></ul><p>The main challenge is that a cache stores a copy of the original data. If the original data changes, the cached copy may become outdated, or stale. Effective caching is therefore a balance between speed, memory use, and data freshness.</p><p>This chapter explains what a cache is, where caches can exist in a system, which data is suitable for caching, how cache performance is measured, and the trade-offs introduced by every cached copy.</p><h3>Key Terms: Cache Hit, Cache Miss, TTL, and Hit Rate</h3><p>Before exploring caching in detail, it helps to understand four important terms.</p><h3>Cache hit</h3><p>A cache hit happens when the requested data is already in the cache and is still valid. The application can return it immediately without contacting the original data source.</p><h3>Cache miss</h3><p>A cache miss happens when the requested data is not in the cache, has expired, or has been removed. The application must retrieve it from the original source. It may then store the result in the cache so that later requests can use it.</p><h3>Time to live (TTL)</h3><p>Time to live, usually shortened to TTL, is the amount of time a cached entry remains valid. For example, an entry with a TTL of 10 seconds expires 10 seconds after it is stored.</p><p>A short TTL provides fresher data but usually causes more cache misses. A long TTL improves the chance of a cache hit but increases the risk of serving stale data.</p><h3>Cache hit rate</h3><p>The cache hit rate, also called the cache hit ratio, is the percentage of cache lookups that result in hits.</p><pre>Hit rate = Cache hits / (Cache hits + Cache misses) × 100</pre><p>For example, if a cache records 7 hits and 7 misses:</p><pre>Hit rate = 7 / (7 + 7) × 100 = 50%</pre><p>If an entry expires because its TTL has ended, the next request for that entry is a miss. After the application retrieves and caches the data again, later requests can become hits.</p><h3>1. The Cost of Repeatedly Hitting the Database</h3><p>Consider a social media application. When a user opens their feed, the application may need to:</p><ol><li>Authenticate the user.</li><li>Fetch the user’s profile.</li><li>Retrieve the list of accounts the user follows.</li><li>Fetch recent posts from those accounts.</li><li>Get like and comment counts for each post.</li><li>Retrieve profile pictures for the post authors.</li></ol><p>Without caching, a single feed load could produce 50 or more database queries. If millions of users load their feeds, the database can quickly become the system’s bottleneck.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*fTG4OBkBWuqWRBVRiqdykA.png" /></figure><p>With caching, the application may answer most of those lookups from a faster cache and contact the database only for missing or expired data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*il-rU8zXARKlVqCwlU8rsg.png" /></figure><h3>Illustrative performance impact</h3><p>The exact improvement depends on the workload, hardware, data, and cache design. The following figures are an example, not a guarantee:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*nev6x7u9cZ_TXMV84alSkg.png" /></figure><p>The improvement comes from avoiding repeated work. Instead of asking the database to rebuild or retrieve the same result over and over, the application reuses a recently stored result.</p><h3>2. The Shape of a Cache</h3><p>At its core, a cache is usually a key-value store designed for fast lookups. The application supplies a key, and the cache returns the value stored under that key.</p><pre>user:123     → { &quot;name&quot;: &quot;Alice&quot;, &quot;plan&quot;: &quot;premium&quot; }<br>product:456  → { &quot;title&quot;: &quot;Widget&quot;, &quot;price&quot;: 20 }<br>session:abc  → { &quot;userId&quot;: 123, &quot;expiresAt&quot;: &quot;...&quot; }</pre><h3>Keys</h3><p>A key is the unique name used to find an item in the cache. A good cache key should be:</p><ul><li>Predictable: The same request should produce the same key.</li><li>Descriptive: A developer should be able to understand what the key represents.</li><li>Unique: Unrelated data must not accidentally use the same key.</li><li>Complete: Every input that changes the result should be represented in the key.</li></ul><p>For example, a key for a user’s profile could be:</p><pre>user:123:profile</pre><p>If the response changes by language, the language should also be part of the key:</p><pre>user:123:profile:en<br>user:123:profile:fr</pre><p>Leaving an important input out of a key can return the wrong cached value. This problem is called a cache key collision or an incorrectly scoped key.</p><h3>Values</h3><p>A value is the actual cached data. It may be:</p><ul><li>A JSON object.</li><li>A string or number.</li><li>Binary data such as an image.</li><li>An HTML fragment or complete page.</li><li>An API response.</li><li>A precomputed result such as a count, report, or summary.</li></ul><p>Values should generally be small enough to store and transfer efficiently. Very large cached objects consume memory quickly and can make cache reads slower.</p><h3>Metadata</h3><p>Metadata is additional information about an entry. Depending on the cache, it may include:</p><ul><li>When the entry was created.</li><li>When it expires.</li><li>How frequently it has been accessed.</li><li>When it was last accessed.</li><li>Its size in memory.</li><li>A version number or validation tag.</li></ul><p>The cache uses this information to expire, validate, or remove entries.</p><h3>3. Cache Layers</h3><p>Caching can happen at several levels of a system. Each layer solves a different problem and has different trade-offs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pav5OfMfwXZtL1tMgGm02w.png" /></figure><p>The closer a valid cached copy is to the user, the less work the rest of the system must perform.</p><h3>3.1 Browser cache</h3><p>The browser cache is the cache closest to the user. It stores resources on the user’s device, including:</p><ul><li>Images.</li><li>JavaScript files.</li><li>Stylesheets.</li><li>Fonts.</li><li>Sometimes HTML pages and API responses.</li></ul><p>If the browser already has a valid copy, it may avoid downloading the resource again. This reduces network traffic and can make a page feel much faster.</p><p>Browser caching is commonly controlled through HTTP headers:</p><ul><li>Cache-Control describes whether a response may be cached and for how long.</li><li>ETag identifies a particular version of a resource. The browser can ask the server whether its copy is still current.</li></ul><p>Browser caching works especially well for versioned static files, such as app.a1b2c3.js, because a content change creates a new filename while old versions can safely have a long TTL.</p><h3>3.2 CDN cache</h3><p>A Content Delivery Network (CDN) caches content at edge locations around the world. A user downloads content from a nearby edge server instead of repeatedly contacting the application’s main, or origin, server.</p><p>CDNs are a strong fit for:</p><ul><li>Static files.</li><li>Images, audio, and video.</li><li>Software downloads.</li><li>Public web pages.</li><li>Public API responses shared by many users.</li></ul><p>A CDN reduces latency caused by geographic distance and lowers traffic reaching the origin. Private or user-specific data requires careful cache rules so that one user’s response is never served to another user.</p><h3>3.3 Application or in-process cache</h3><p>An application cache lives in the memory of the running application process. Because the data is already inside the process, a lookup can be extremely fast and requires no network call.</p><p>This type of cache is useful for small, frequently reused data such as configuration, lookup tables, or computed results.</p><p>However, every application instance has its own local cache. In a system with several servers, this creates two important issues:</p><ul><li>The same data may be duplicated in memory on every server.</li><li>Different servers may temporarily hold different versions of a value.</li></ul><p>An application cache also disappears when the application restarts.</p><h3>3.4 Distributed cache</h3><p>A distributed cache is a separate caching service shared by multiple application instances. Redis and Memcached are common examples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*tSMAoQ7NsfMVGw2z_2X2mQ.png" /></figure><p>A distributed cache is slower than local memory because each lookup crosses a network. It is still normally much faster than a complex database query or remote service call. Its main advantages are shared data, larger capacity, and centralized cache management.</p><p>Common uses include:</p><ul><li>Database query results.</li><li>User sessions.</li><li>Rate-limit counters.</li><li>Shared configuration.</li><li>Precomputed pages or API responses.</li></ul><p>Because many application servers may depend on it, a distributed cache should be designed with appropriate replication, monitoring, timeouts, and fallback behavior.</p><h3>3.5 Database buffer pool</h3><p>Databases have their own internal caching. A database buffer pool keeps frequently accessed data pages and indexes in the database server’s memory. Repeated reads can then use memory instead of slower disk storage.</p><p>This cache is normally invisible to application code and is managed automatically by the database.</p><p>A database buffer pool does not make application-level caching unnecessary. The database still needs to parse queries, check permissions, find rows, perform joins, and send results. An application cache can avoid that work entirely for repeated results.</p><h3>4. Cache Hits and Misses</h3><p>When an application requests a key from a cache, the request follows one of two main paths.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/326/1*FjdAxb2Wos9Bt61yh_w0uQ.png" /></figure><p>On a hit, the slow source is avoided. On a miss, the request is slower because the application must still contact the original source. It may also spend time serializing and storing the new cache entry.</p><h3>Interpreting the hit ratio</h3><p>The following ranges provide a rough guide only. The right target depends on the application and the cost of a miss.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*28mvZjAWanlYKnimE9KY3g.png" /></figure><p>A high hit ratio is helpful only if the cached responses are correct and cache lookup latency is low. A 99% hit ratio is not useful if the cache regularly returns stale or incorrect information.</p><h3>Why a 90% hit ratio can have a large effect</h3><p>Suppose 100,000 read requests arrive each second and the cache hit ratio is 90%:</p><pre>Cache hits   = 100,000 × 0.90 = 90,000 requests/second<br>Cache misses = 100,000 × 0.10 = 10,000 requests/second</pre><p>Only 10,000 requests per second reach the database for those reads. In this simplified example, a database capable of handling 10,000 such queries per second can support roughly 100,000 application reads per second when 90% are served by the cache.</p><p>This is an approximation. Real systems also have writes, different query costs, network overhead, and other limits.</p><h3>5. What Should Be Cached?</h3><p>Not all data benefits equally from caching.</p><h3>Good candidates</h3><p>Caching usually provides the most value when data:</p><ul><li>Is read much more often than it is changed.</li><li>Is requested repeatedly by the same or many users.</li><li>Is expensive to calculate.</li><li>Comes from a slow database, API, or service.</li><li>Can safely be slightly stale.</li><li>Has a predictable cache key.</li></ul><p>Examples include product details, public profiles, site configuration, popular posts, search suggestions, aggregate counts, and generated reports.</p><h3>Poor candidates</h3><p>Caching may provide little value, or create unacceptable risk, when data:</p><ul><li>Changes constantly.</li><li>Is read only once.</li><li>Is unique for almost every request.</li><li>Is too large relative to its reuse.</li><li>Must always be perfectly current.</li><li>Contains sensitive information that cannot be safely isolated.</li></ul><p>Examples can include rapidly changing inventory during a limited sale, one-time tokens, highly unique queries, and authoritative financial balances.</p><p>This does not mean such data can never be cached. It means the cache design, TTL, security boundaries, and consistency guarantees require extra care.</p><h3>The 80/20 rule and hot data</h3><p>Many applications follow a rough pattern in which a small portion of the data receives most of the requests. This is often described using the 80/20 rule: approximately 20% of the data may serve 80% of the reads.</p><p>The frequently requested portion is called the hot set or hot data.</p><pre>Frequently requested 20% → approximately 80% of requests<br>Less requested 80%       → approximately 20% of requests</pre><p>This is a useful guideline rather than a universal law. Caching the hot set captures much of the performance benefit without requiring enough memory to hold the entire dataset. Rarely requested entries may be evicted before they are reused and therefore add little value.</p><h3>6. Cache Consistency and Stale Data</h3><p>Cache consistency means keeping the cached copy reasonably aligned with the source of truth. The database is usually the source of truth because it stores the durable, authoritative version of the data.</p><p>Suppose a product price changes in the database from $15 to $20, but its cached entry is not changed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cy8yDETkNgfJrJJc0yUBkA.png" /></figure><p>The old cached copy is stale. How serious this is depends on the data. An old profile description may be harmless for a few minutes, while an old price, permission, or account balance can cause serious problems.</p><h3>Common consistency approaches</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*b9mYNYyw8cAAFFP6Gx5TWQ.png" /></figure><p>The right choice should be made feature by feature. A product description may be allowed to remain stale for five minutes. A bank balance should not use the same freshness policy.</p><p>It is also common to combine approaches. For example, an application may invalidate a product entry whenever the product changes and still assign a TTL as a safety net in case an invalidation event is missed.</p><h3>7. Common Caching Anti-Patterns</h3><p>Caching has costs as well as benefits. The following patterns often create more problems than they solve.</p><h3>7.1 Caching everything</h3><p>Blindly caching every result fills memory with entries that may never be requested again. Useful hot entries may then be evicted to make room for cold, one-time data.</p><p>Cache data because measurements show that it is reused or expensive — not simply because it exists.</p><h3>7.2 Using an infinite TTL</h3><p>An entry that never expires can remain wrong forever. If the application misses one invalidation, users may continue seeing old data until the entry is manually removed or the cache restarts.</p><p>Even when explicit invalidation is the main strategy, a finite TTL often provides a useful safety net. The appropriate duration depends on how quickly the data must reflect changes.</p><h3>7.3 Treating the cache as primary storage</h3><p>A cache should not normally be the only copy of important data. Cache entries may be:</p><ul><li>Evicted when memory is full.</li><li>Deleted when their TTL expires.</li><li>Lost during a restart or failure.</li><li>Removed during maintenance.</li></ul><p>Durable data should be written to a database or another reliable source of truth. If the only copy exists in a cache, losing the cache may permanently lose the data.</p><h3>7.4 The thundering herd problem</h3><p>The thundering herd, also called a cache stampede, happens when a popular entry expires and many requests attempt to rebuild it at the same time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/232/1*Q65l-Gob5nd_FNPMU2Lf0A.png" /></figure><p>Common protections include:</p><ul><li>Per-key locking or request coalescing: Allow one request to rebuild a key while the others wait for its result.</li><li>Early refresh: Refresh a popular entry shortly before it expires.</li><li>Background refresh: Rebuild entries asynchronously rather than making users wait.</li><li>TTL jitter: Add a small random variation to expiration times so that many keys do not expire simultaneously.</li><li>Serve stale while refreshing: Temporarily return the last known value while one worker retrieves a fresh copy, when the feature permits stale data.</li></ul><h3>8. Caching in Distributed Systems</h3><p>Distributed systems introduce extra challenges because several application servers and cache nodes may hold or use copies of the same data.</p><h3>8.1 Consistency across nodes</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*O657ZHKkDP7QqB9iufrs3g.png" /></figure><p>When data changes, entries may need to be deleted or refreshed in several places. Updates do not always reach every node at exactly the same moment, so some requests may briefly see the new value while others see the old one. This is one form of eventual consistency.</p><p>Versioned keys, invalidation messages, centralized caches, and carefully selected TTLs can reduce the problem, but each technique has a cost.</p><h3>8.2 Data partitioning</h3><p>A large distributed cache splits, or partitions, data across multiple nodes because a single node cannot provide unlimited memory or traffic capacity.</p><pre>Hash(key) → cache node responsible for that key</pre><p>Consistent hashing is a technique that limits how many keys must move when cache nodes are added or removed. With a simple remainder-based mapping, changing the number of nodes can remap most keys. Consistent hashing normally remaps only a portion, which reduces sudden cache misses and data movement.</p><p>Replication may also be used so that a node failure does not make all of its cached keys temporarily unavailable.</p><h3>8.3 Failure handling</h3><p>A system should decide in advance what happens if the cache becomes unavailable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JvZcx0hCLnVeuJdhxKDJLg.png" /></figure><p>Failing open sounds convenient, but it can turn a cache outage into a database outage if all traffic suddenly falls through. Timeouts, circuit breakers, rate limits, and capacity planning help keep the fallback path safe.</p><h3>9. Measuring Cache Performance</h3><p>A cache should be measured rather than assumed to be effective. Important metrics include:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*GN9yXdIDBpWC4q8eRE8Vkw.png" /></figure><h3>Latency percentiles</h3><p>Average latency can hide slow requests, so systems often monitor percentiles:</p><ul><li>p50 is the median, or typical, latency. Half of measured requests are faster and half are slower.</li><li>p95 is slower than 95% of measured requests.</li><li>p99 represents one of the slowest requests that users still experience regularly. Only 1% are slower.</li></ul><p>For example, a cache with p50 latency of 1 ms and p99 latency of 100 ms usually responds quickly, but has a significant slow tail that should be investigated.</p><h3>Warning signs</h3><p>A sudden fall in hit ratio or rise in evictions may mean:</p><ul><li>Traffic patterns have changed.</li><li>The cache is too small for the current hot set.</li><li>TTLs are too short.</li><li>Entries are being invalidated too aggressively.</li><li>Cache keys have changed, causing old entries to become unreachable.</li><li>A deployment started generating too many unique keys.</li></ul><p>Metrics should be examined together. A low hit ratio with almost no memory usage may point to poor key reuse or very short TTLs, while a low hit ratio with high memory usage and frequent evictions may point to insufficient cache capacity.</p><h3>10. Practical Checklist</h3><p>Before caching a piece of data, ask:</p><ol><li>Is the data requested often enough to be reused?</li><li>Is retrieving or computing it expensive?</li><li>How stale may it safely become?</li><li>What should the cache key contain?</li><li>How large is each value?</li><li>What TTL is appropriate?</li><li>How will the entry be invalidated when the source changes?</li><li>What happens if the cache is unavailable?</li><li>Can the original source handle a sudden wave of misses?</li><li>Which metrics will prove that the cache is helping?</li></ol><p>If these questions do not have clear answers, adding a cache may move complexity rather than solve the original problem.</p><h3>Summary</h3><p>Caching stores copies of frequently accessed data in a faster layer. It can reduce request latency, database load, network traffic, and infrastructure cost while helping a system handle more users.</p><p>Caches exist throughout the stack, including the browser, CDN, application process, distributed cache, and database buffer pool. Each layer has a different speed, capacity, sharing model, and consistency trade-off.</p><p>The hit ratio is one of the most useful cache metrics. In a simplified read-heavy example, a 90% hit ratio sends only 10% of those requests to the original source and can provide roughly a 10× increase in read capacity.</p><p>What gets cached matters more than how much gets cached. Frequently read, expensive, stable, and safely reusable data usually benefits the most. Frequently changing, one-time, very large, or strictly fresh data often benefits less or requires a more careful design.</p><p>Every cached copy creates a freshness problem. TTLs, invalidation, write-through behavior, and explicitly accepted staleness are different ways to manage it. Common mistakes include caching everything, using infinite TTLs, treating the cache as durable storage, and ignoring the thundering herd problem.</p><p>Understanding these fundamentals prepares us for the next topic: caching patterns. The most common starting point is the cache-aside pattern, in which the application explicitly reads from the cache, retrieves missing data from the source, and places that data into the cache for future requests.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b0273f64a87" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>