<?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[Everything Databases - Medium]]></title>
        <description><![CDATA[Anything and everything related to database management systems and it’s internals. - Medium]]></description>
        <link>https://medium.com/everything-databases?source=rss----a14174d7d276---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Everything Databases - Medium</title>
            <link>https://medium.com/everything-databases?source=rss----a14174d7d276---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 10:11:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/everything-databases" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Bulletproof Transactions: Implementing Rigorous 2PL from Scratch]]></title>
            <link>https://medium.com/everything-databases/bulletproof-transactions-implementing-rigorous-2pl-from-scratch-025c31003bf7?source=rss----a14174d7d276---4</link>
            <guid isPermaLink="false">https://medium.com/p/025c31003bf7</guid>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[database-engine]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[transactions]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Ashwin Prasad]]></dc:creator>
            <pubDate>Tue, 11 Feb 2025 19:26:51 GMT</pubDate>
            <atom:updated>2025-02-11T19:26:51.324Z</atom:updated>
            <content:encoded><![CDATA[<h4>Engineering transaction isolation from first principles. Implementing Repeatable Read Through Rigorous 2 Phase Locking</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L1mB1Z_G6snKY3xF_pzsAw.png" /><figcaption>Thumbnail Made from Canva</figcaption></figure><h3>1) Introduction</h3><p>Handling multiple queries simultaneously, or a single query with parallel workers for better performance, is a standard expectation for any database. Most databases achieve this on their own terms with their own trade-offs. But accommodating multiple transactions to execute concurrently comes with it’s own set of issues.</p><p>A transaction is a unit of work that can happen in a database. It is a unit because it is atomic. Either all the operations in the transaction execute successfully or none of them gets executed. There’s no intermediate state that the transaction leaves behind when it fails mid execution. A transaction is a collection of one or more queries.</p><p>At a lower level, we can’t allow 2 different queries to modify a common piece of data or data structure simultaneously as this might corrupt the data or render the other query useless. Imagine if 2 write operations occur on the same index and the same node of the index. Both the queries or operations might find enough space to insert at the same file offset or memory buffer <em>(Since they do not have any information about what the other write operation is trying to do) </em>and end up overwriting each other’s information on the same buffer or file offset. This results in corrupted data altogether. This necessitates some kind of <strong>synchronization</strong> between transactions <em>(usually done though latches).</em></p><p>While latches ensure short-term in-memory synchronization for protecting critical data structures, locks provide long-term concurrency control to maintain transactional consistency and isolation. Latches are a low-level programmers problem that prevent memory corruption while locks are a higher level user problem that prevents data inconsistencies.</p><h3>2) The Problems with Concurrent Access</h3><p>There are some identified problems that database systems needs to address when they allow multiple transactions to execute simultaneously, in order to ensure the consistency of the database systems:<br><strong>1. Dirty Reads<br>2. Dirty Writes<br>3. Lost Updates<br>4. Non Repeatable Reads<br>5. Phantom Reads<br>6. Write Skews</strong></p><h4>2.1) Dirty Reads</h4><p>Dirty read problem arises when a transaction reads data that was updated by another transaction but not committed yet.</p><pre>//Table 2.1: Dirty Read Illustration<br><br>+-----------+-------------------+---------+<br>| TimeStamp |        T1         |   T2    |<br>+-----------+-------------------+---------+<br>| t1        | READ(x)           |         |<br>| t2        | WRITE(x) = x + 10 |         |<br>| t3        |                   | READ(x) |<br>| t4        |                   | COMMIT  |<br>| t5        | ROLLBACK          |         |<br>+-----------+-------------------+---------+</pre><p>In the above table, <strong>T2 </strong>reads the value of <strong>x</strong> and proceeds to do some operations and make some decision with it. But it does not know that the actual value of <strong>x </strong>is <strong>x-10</strong> since transaction <strong>T1</strong> has been rolled back <em>(maybe due to a network failure or some other criteria failure)</em>.</p><h4>2.2) Dirty Writes</h4><p>Dirty writes occur when a transaction modifies a data that has already been modified by another transaction which has not been committed or rolled back yet.</p><p>Transaction <strong>T1</strong> modifies a data item. Another transaction <strong>T2</strong> then further modifies that data item before <strong>T1</strong> performs a <strong>COMMIT</strong> or <strong>ROLLBACK</strong>. If <strong>T1</strong> or <strong>T2</strong> then performs a ROLLBACK, it is unclear what the correct data value should be.</p><pre>// Table 2.2: Dirty Writes Illustration<br><br>+-----------+----------------------------+--------------------------+<br>| Timestamp |             T1             |            T2            |<br>+-----------+----------------------------+--------------------------+<br>| t1        | WRITE(buyer) = &#39;Alice&#39;     |                          |<br>| t2        |                            | WRITE(buyer) = &#39;Bob&#39;     |<br>| t3        |                            | WRITE(recipient) = &#39;Bob&#39; |<br>| t4        |                            | COMMIT                   |<br>| t5        | WRITE(recipient) = &#39;Alice&#39; |                          |<br>| t6        | COMMIT                     |                          |<br>+-----------+----------------------------+--------------------------+</pre><p>Now at the end of the transactions from the above table 2.2, <em>‘Bob’</em> is set as buyer whereas <em>‘Alice’</em> is set as recipient.</p><h4>2.3) Lost Updates</h4><p>When updates of a transaction are lost because some other transaction overwrites the previous update, this is called a lost update problem.</p><pre>//Table 2.3: Lost Update Illustration<br><br>+-----------+-------------------+-------------------+<br>| Timestamp |        T1         |        T2         |<br>+-----------+-------------------+-------------------+<br>| t1        | READ(x)           |                   |<br>| t2        | WRITE(x) = x + 15 |                   |<br>| t3        |                   | READ(x)           |<br>| t4        |                   | WRITE(x) = x - 25 |<br>| t5        |                   | COMMIT            |<br>| t6        | COMMIT            |                   |<br>+-----------+-------------------+-------------------+</pre><p>In the above scenario, after having incremented <strong>x’s</strong> value by 15, <strong>T1</strong> might have to do some intermediate processing, during when, <strong>T2</strong> reads, updates and commits <strong>x</strong> value. Once <strong>T1</strong> is done with it’s processing, it comes back to commit the transaction, which makes <strong>T2s</strong> updates useless.</p><h4>2.4) Non Repeatable Reads</h4><p>A Non-Repeatable read occurs when a transaction <strong>(T1)</strong> reads the same data twice but observes different values each time. This happens because another transaction <strong>(T2)</strong> modifies the data between the two read operations performed by <strong>T1</strong>.</p><pre>//Table 2.4: Non Repeatable Read Illustration<br><br>+-----------+---------+------------------+<br>| Timestamp |   T1    |        T2        |<br>+-----------+---------+------------------+<br>| t1        | READ(x) |                  |<br>| t2        |         |                  |<br>| t3        |         | READ(x)          |<br>| t4        |         | WRITE(x) = x + 2 |<br>| t5        |         | COMMIT           |<br>| t6        | READ(x) |                  |<br>+-----------+---------+------------------+</pre><p>We consider this to be an issue because we expect a transaction to retrieve the same value when reading data multiple times, ensuring consistency and reliability. Inconsistent values can lead to incorrect decisions in the business layer, as the data may have been modified by another transaction in the meantime.</p><h4><strong>2.5) Phantom Reads</strong></h4><p><strong>Phantom</strong> reads are very similar to Non-Repeatable reads but with a minor difference:<br><em>1) The base transaction does not read a single value but usually a range of values.<br>2) The other transaction that does not modify an existing value. But Adds a new row or deletes a row to/from the range of values queried by the base transaction.</em></p><pre>+-----------+-----------------------------------+----------------------------------------------+<br>| Timestamp |                T1                 |                      T2                      |<br>+-----------+-----------------------------------+----------------------------------------------+<br>| t1        | READ(&#39;students&#39; WHERE &#39;age&#39; &lt; 18) |                                              |<br>| t2        |                                   | INSERT(&#39;student&#39;(name=&quot;Bruce Wayne&quot;,age=12)) |<br>| t3        | READ(&#39;students&#39; WHERE &#39;age&#39; &lt; 18) |                                              |<br>+-----------+-----------------------------------+----------------------------------------------+</pre><p>These above mentioned problems could lead the state of the database straight into inconsistency if not handled properly. It is not hard to imagine how. Just think about a banking system with the above issues. The business layer of the application needs to be free from the fear of reading inconsistent or stale data from the database. This requires the database system to abstract away concurrency related issues from the business layer and provide strong mechanisms to support it.</p><h4>2.6) Write Skews</h4><p>Write Skew occurs when 2 transactions read the same objects and then update some of those objects concurrently.</p><p>Imagine that you have a hospital and you want at least one doctor to remain on call at any given time. Now what happens when the only 2 available doctors request leave at approximately the same time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/0*9Cn1-NwGfN_JS5Qf.png" /><figcaption>Fig 2.6.1: Write Skew Example from Designing Data Intensive Applications</figcaption></figure><p>Both transactions check the number of doctors available on call and if the count is greater than 1, the system grants the leave and the transaction updates the on_call column to false. Both transactions commit without any issues, making our requirement of having at least one doctor on call at all times false.</p><blockquote>It is less obvious that a conflict occurred here, but it’s definitely a race condition: if the two transactions had run one after another, the second doctor would have been prevented from going off call. The anomalous behaviour was only possible because the transactions ran concurrently.</blockquote><h3>3) Introducing Isolation Levels</h3><p>Some clever people came up with mechanisms to handle these race conditions and anomalies to keep the state of the database consistent at all times. While accomplishing that, the realization that not all systems require strong consistency struck them. Depending upon the system using the database engine, sometimes lesser consistency guarantees can be tolerated. As a direct result of this, the concept of <strong>Isolation Levels</strong> were introduced, where each level guarantees a different magnitude of isolation and consistency of data.</p><p>The 4 main Isolation Levels are:</p><ul><li><strong>Read Uncommitted</strong></li><li><strong>Read Committed</strong></li><li><strong>Repeatable Read</strong></li><li><strong>Serializable</strong></li></ul><p>Let’s dive a little deeper into these isolation levels and understand the different guarantees and trade-offs between them.</p><p><em>Note: Please keep in mind that, these isolation levels can be implemented differently in different database engines. Most modern engines use an approach called MVCC (Multi Version Concurrency Control). Depending upon the implementation, whether a reader blocks the writer or if a writer can block a reader is determined. <br>For example, in MVCC, even in repeatable read, a read operation on a row does not block a write operation on the same row in another transaction. Whereas it will block in r</em>igorous<em> 2 phase locking.</em></p><h4>3.1) Read Uncommitted</h4><p>Read Uncommitted is the weakest isolation level and does not offer any consistency guarantees. In this isolation level, any changes made by any transaction, even if the transaction is not committed, can be read by any other transaction. All the anomalies we discussed earlier can occur in this isolation level except for those where write-write conflicts occur, like <strong>dirty writes</strong> and <strong>lost updates</strong> <em>(This will be completely dependent on the implementation specifics of the database engine. Most of them will not block the write operation of the second transaction)</em>.</p><h4><strong>3.2) Read Committed</strong></h4><p>In this isolation level, a transaction cannot read the modifications from other transactions that are not committed yet. This takes care of the dirty read problem but still does not account for the <strong>Non-Repeatable Read</strong> as well as the <strong>Phantom Read</strong> issue we saw above.</p><h4>3.3) Repeatable Read</h4><p>This isolation level guarantees that any row or object will always return the same consistent value throughout the lifetime of the transaction. This takes care of the non-repeatable reads.</p><p>In <strong>Rigorous 2 Phase Locking</strong>, A shared lock is acquired on any row or object being read by a transaction. This makes it impossible for other transactions to acquire an exclusive lock and hence the row will remain unmodified until the original transaction with the shared lock is committed or rolled back.</p><p>In <strong>Multi Version Concurrency Control</strong>, even if the same row is modified in some other transaction, the current transaction will read the same value it read previously. <strong>MVCC</strong> achieves this by maintaining multiple versions of the same row.</p><h4>3.4) Serializable</h4><p>While repeatable read takes care of the non-repeatable read problem by acquiring shared locks on the rows, It cannot acquire shared locks on values that do not exist in the table yet <em>(Values that will be newly inserted). </em>This makes phantom reads possible.</p><p>Serializable isolation levels typically have to use some sort of <strong>Predicate</strong> or <strong>Gap locks </strong>on the range of values being read in the first transaction and thus, prevent any new inserts into that range.</p><h3>4) Differences between Optimistic and Pessimistic Concurrency Control</h3><p>Two primary mechanisms for handling concurrency are <strong>Optimistic Concurrency Control (OCC)</strong> and <strong>Pessimistic Concurrency Control (PCC)</strong>. Both strategies aim to maintain data integrity, but they operate under different assumptions about the likelihood of conflicts.</p><p><strong>Pessimistic Concurrency Control</strong> assumes that conflicts between transactions are common. It prevents conflicts by locking data resources as soon as they are accessed, ensuring that no other transaction can modify the data until the lock is released.</p><ul><li><strong>Shared Lock (Read Lock)</strong>: Allows multiple transactions to read data but prevents writes.</li><li><strong>Exclusive Lock (Write Lock)</strong>: Ensures that only one transaction can read and write the data.</li></ul><p>Usually, <strong>Rigorous</strong> <strong>2PL</strong> is implemented as the pessimistic concurrency protocol</p><p><strong>Optimistic Concurrency Control</strong> allows transactions to execute without locking resources and only checks for conflicts before committing. If a conflict is detected, the transaction is rolled back and must be retried. It assumes that conflicts between transactions are rare.</p><p>OCC typically follows three main phases:</p><ol><li><strong>Read Phase</strong>: The transaction reads data without any locks. It operates on a local copy of the data.</li><li><strong>Validation Phase</strong>: Before committing, the transaction checks whether other transactions have modified the same data.</li><li><strong>Write Phase</strong>: If no conflicts are found, changes are committed. otherwise, the transaction is rolled back and restarted.</li></ol><p>Most modern systems prefer <strong>OCC</strong> over <strong>PCC</strong> and usually implement the <strong>MVCC</strong> version of it.</p><h3>5) Basic Rules of Rigorous 2 Phase Locking</h3><p>Rigorous Two-Phase Locking <em>(Rigorous 2PL)</em> is a concurrency control protocol that ensures serializability by enforcing two rules:</p><ul><li>A transaction must acquire a lock before accessing a resource <em>(read or write).</em></li><li>If a transaction needs an exclusive lock, it must wait if another transaction holds any lock on the resource.</li><li>All locks must be held until the transaction commits or aborts.</li><li>Locks are released only at the end of the transaction.</li><li>Deadlocks are possible, so a deadlock detection or prevention mechanism is required.</li></ul><p>This prevents cascading aborts <em>(phenomenon where failure of one transaction leads causes a dependent transaction to abort)</em> by ensuring no transaction reads uncommitted data</p><h3>6) Building a Pessimistic Transaction Manager</h3><p>Let’s outline the core data structures, function and all fundamental components of a pessimistic transaction manager.</p><h4>6.1) Global State</h4><pre>//Table 5.1.1: Example State of a lock table.<br>+--------+----------------+-----------+-------------+<br>| Row ID | Transaction ID | Lock Type | LOCK STATUS |<br>+--------+----------------+-----------+-------------+<br>|      1 |              1 | SHARED    | ACQUIRED    |<br>|      1 |              2 | SHARED    | ACQUIRED    |<br>|      2 |              1 | EXCLUSIVE | ACQUIRED    |<br>|      2 |              2 | SHARED    | WAITING     |<br>+--------+----------------+-----------+-------------+<br><br><br>//Table 5.1.2: Transaction Status<br>+----------------+-------------+<br>| Transaction ID |   STATUS    |<br>+----------------+-------------+<br>|              1 | IN PROGRESS |<br>|              2 | ABORTED     |<br>|              3 | COMITTED    |<br>|              4 | IN PROGRESS |<br>+----------------+-------------+</pre><p>All the information a Transaction Manager would require, is in the table above. Whether this state is persisted to disk or kept completely In-memory, is based upon the implementational details. For simplicity, I will be storing the entire information In-memory.</p><pre>enum LockType {<br>    SHARED,<br>    EXCLUSIVE<br>};<br><br><br>enum LockStatus {<br>    ACQUIRED,<br>    WAITING<br>};<br><br><br>struct LockTableEntry {<br>    int rowId;<br>    int transactionId;<br>    LockType lockType;<br>    LockStatus lockStatus;<br>};<br><br><br>enum TransactionStatus {<br>  IN_PROGRESS,<br>  COMMITTED,<br>  ABORTED<br>}<br><br><br>int globalTxnCounter;<br>std::unordered_map&lt;int, TransactionStatus&gt; txnIdVsStatus;<br>std::list&lt;LockTableEntry&gt; LockTable;<br><br>//DataStructures for faster lookups<br>std::unordered_map&lt;int, std::list&lt;LockTableEntry*&gt;&gt; txnIdVsLockTableEntries;<br>std::unordered_map&lt;int, std::list&lt;LockTableEntry*&gt;&gt; rowIdVsLockTableEntries;</pre><p>The above is the C++ representation of the global transaction state. It is the code equivalent of the tabular format at <em>5.1.1 </em>and<em> 5.1.2</em></p><p>I do not want to ponder over the actual code as that would defeat the main purpose of this writing piece, but let’s dive into the pseudo code and understand the workings of the transaction manager.</p><p>It is to be noted that unordered_map and <strong>std::list</strong> aren’t thread safe implementations. I am using the plain versions to keep things simple and understandable. When implementing an actual manager, one should consider using a <strong>std::shared_mutex</strong> and <strong>sharded locks.</strong></p><h4>6.2) Functions of a Transaction Manager</h4><pre>//Exposed APIs from the transaction manager<br><br>int beginTransaction();<br><br>int acquireLock(int transactionId, int rowId, LockType lockType);<br><br>void commit(int transactionId);<br><br>int rollback(int transactionId);<br><br>//This one below is not exposed but rather a private function<br>void releaseLocks(int transactionId);</pre><p><strong>6.2.1) beginTransaction(): </strong>Initializes a new transaction with a unique identifier and returns the identifier</p><p><strong>6.2.2) acquireLock(): </strong>Requests a lock (<strong>SHARED</strong> or <strong>EXCLUSIVE</strong>) on a specific row.</p><ul><li>If the row is not<strong> </strong>locked, grant the lock and associate it with transaction Id.</li><li>If the row is <strong>locked by the same transaction</strong>, upgrade the lock if needed.</li><li>If a <strong>conflict</strong> exists <em>(e.g., requesting an exclusive lock while another transaction holds a shared lock)</em>, the current transaction blocks and waits for the lock <em>(polls every n milliseconds)</em> for a given period <em>wait_time</em>. If the threshold <em>wait_time</em> is exceeded or if a <strong>deadlock</strong> is identified, the transaction is aborted.</li><li>If allowed, multiple transactions can hold shared locks.</li></ul><p><strong>6.2.3) commit(): </strong>Releases all locks held by the transaction and updates the transaction status.</p><p><strong>6.2.4) rollback(): </strong>This one is a little bit tricky. It will take a separate discussion about recovery managers and undo logs to understand rollbacks work. But since we are limiting the scope of this to <em>“Concurrency and Integrity”</em>, let’s not deep dive into rollbacks for now.</p><p>Basic idea is to log every object update in a special log called <strong>Undo Logs</strong> and, when the transaction aborts or rollbacks, we revert the state of the modified object to their state before the transaction changed them.</p><p>Finally, release all the locks held by the transaction.</p><h3>7) Conclusion</h3><p>While <strong>Rigorous</strong> <strong>2PL</strong> guarantees serializability and recoverability, it can introduce contention and potential deadlocks, requiring careful handling through deadlock detection or timeout-based approaches. I have chosen <strong>Rigorous 2PL</strong> over <strong>MVCC</strong> for it’s implementation simplicity.</p><p>Whether you’re building a database engine or tuning an existing one, mastering these concepts ensures you can make informed trade-offs between correctness and efficiency.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=025c31003bf7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/everything-databases/bulletproof-transactions-implementing-rigorous-2pl-from-scratch-025c31003bf7">Bulletproof Transactions: Implementing Rigorous 2PL from Scratch</a> was originally published in <a href="https://medium.com/everything-databases">Everything Databases</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From LRU to LRU-K: Elevate Your Caching Game]]></title>
            <link>https://medium.com/everything-databases/from-lru-to-lru-k-elevate-your-caching-game-96c292317474?source=rss----a14174d7d276---4</link>
            <guid isPermaLink="false">https://medium.com/p/96c292317474</guid>
            <category><![CDATA[caching-strategies]]></category>
            <category><![CDATA[cache]]></category>
            <category><![CDATA[lru-k]]></category>
            <category><![CDATA[caching]]></category>
            <category><![CDATA[lru-cache]]></category>
            <dc:creator><![CDATA[Ashwin Prasad]]></dc:creator>
            <pubDate>Sun, 09 Feb 2025 19:32:53 GMT</pubDate>
            <atom:updated>2024-12-21T19:59:32.394Z</atom:updated>
            <content:encoded><![CDATA[<h4>Why Least Recently Used — K Matters: A Smarter Way to Handle Cache in Modern Systems</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U3Mo0QKtEXFrjCwIchoMBQ.png" /></figure><h3>1) Caching and It’s Importance</h3><p>Caching is a process of storing frequently accessed data in a faster, temporary storage layer <em>(usually memory)</em> so that it can be retrieved quickly without repeatedly querying slower back-end systems like databases or hard drives. Modern systems often deal with immense volumes of data and must serve millions of user requests in real-time. Without caching, every request would require accessing the primary storage, which is significantly slower.</p><p>User Abandonment Studies have shown that users have very low tolerance for slow web experiences. Typically, if a page doesn’t load within 3 seconds, users are likely to abandon the site or application. This directly translates to lost engagement and potential revenue. <em>(Please refer to </em><a href="http://www.nngroup.com/articles/response-times-3-important-limits/"><em>Jakob Nielsen&#39;s research</em></a><em>)</em></p><p>Caching goes on a long way in improving the overall performance. This not only is a direct result of retrieving the results from a faster secondary store, but also from making sure less computation takes place when the necessary entities are retrieved from cache. The entities stored in the cache are already stored in a response-ready format that can be directly served to the client <em>(This reduces additional processing during the lifetime of the request).</em></p><h3>2) The Need for Efficient Eviction Policies</h3><p>Despite all the advantages of caching, cache memory is typically much smaller and more expensive than main storage. This limitation necessitates intelligent eviction policies - strategies for determining which data to remove when the cache reaches its capacity.</p><p>Since storage is limited and we need to remove certain caches to facilitate storing of other caches, we need to ensure certain conditions to the best of our ability, to reap the benefits of a caching system. One of the most vital responsibility while building a caching mechanism is ensuring th<strong>e </strong>below<strong>:</strong></p><blockquote>the<strong> Victim cache </strong>(The cache entity that will be replaced) is chosen in such a way that it will not be used anytime in the near future.</blockquote><p>A robust caching system strategically identifies and evicts cache entities that have a statistically low probability of near-future reuse, thereby optimising memory access efficiency and computational performance.</p><p>If we were to disregard all reasoning and implement a naive cache eviction policy that removes a randomly chosen cache entry whenever space is required, we might encounter a phenomenon known as <strong>Thrashing</strong>.</p><h4>2.1) Thrashing</h4><p>Imagine a kitchen where you’re constantly searching for ingredients, moving things around, but never finding what you need efficiently. This is precisely what thrashing looks like in a computer’s memory system.</p><p>Thrashing is a state of excessive page faulting <em>(cache miss and page faults are interchangeable terms)</em> that occurs when a computer spends more time managing memory transfers between RAM <em>(or any secondary fast storage)</em> and disk <em>(or any primary slower storage)</em> than actually performing useful computational work. It’s like a system getting stuck in a perpetual, unproductive shuffling of data.</p><ul><li>Process A requests <strong>Object 1</strong> → <strong>Object 1</strong> is in loaded into cache.</li><li>Process C requests <strong>Object 2</strong> → <strong>Object 2</strong> is loaded by swapping out <strong>Object</strong> 1.</li><li>Process A needs <strong>Object 1</strong> again → <strong>Object</strong> 1 is reloaded by swapping out <strong>Object</strong> 2.</li><li>Process B requests <strong>Object 3</strong> → <strong>Object</strong> 3 is loaded, and another <strong>Object</strong> (e.g., from Process A) is swapped out.</li><li>The cycle continues, with the disk I/O dominating, and minimal computation occurs.</li></ul><p>This typically occurs because of having a dumb cache manager that keeps evicting important objects from the cache rather than objects that are no longer being used <em>(Objects of some other processes)</em></p><blockquote>“The cycle ends here. We must be better”</blockquote><blockquote>- The Cache Manager</blockquote><h3>3) Keeping Your Cache In Check With LRU and LFU</h3><p>To ensure the cache removes the least useful object <em>(the one unlikely to be accessed again soon)</em> is the goal. We can achieve this effectively using two widely adopted algorithms: <strong>LFU</strong> <em>(Least Frequently Used)</em> and <strong>LRU</strong> <em>(Least Recently Used)</em>.</p><h4>3.1) Least Frequently Used for Cache Eviction</h4><p>This is the lesser popular of the 2 above mentioned cache eviction policies. But this is a decent algorithm in the aspect that it needs very limited book-keeping, and is straightforward to implement.</p><p>The <strong>Least Frequently Used (LFU)</strong> algorithm evicts the cache object that has been accessed the fewest times. It tracks the usage count of each object and removes the one with the lowest count when space is needed.</p><ul><li><strong>Frequency Count</strong>: Each object has a counter that increments every time it is accessed.</li><li><strong>Eviction</strong>: When the cache is full, the object with the smallest counter is removed.</li></ul><p><strong>LFU</strong> mainly suffers from two drawbacks:</p><ol><li>New objects in the cache start with a frequency of zero. If eviction happens before these objects are accessed multiple times, they may be prematurely removed even if they are likely to become <strong>“hot”</strong> soon.</li><li><strong>LFU</strong> focuses solely on frequency and ignores recency. Objects that were frequently accessed in the past but are no longer relevant will continue to stay in the cache longer than necessary, wasting space. Sudden spikes in access frequency of objects can render the algorithm helpless. An object might temporarily become frequently accessed and then stop being accessed altogether.</li></ol><h4>3.2) Least Recently Used for Cache Eviction</h4><p>Many real-world applications exhibit temporal locality, where recent access patterns are more important than long-term access history. This is what <strong>LFU</strong> fails to capture and where <strong>LRU</strong> outshines <strong>LFU</strong>.</p><blockquote>Temporal locality is a principle in computer programming that describes the tendency of programs to repeatedly use the same data or resources within a short period of time.</blockquote><p><strong>Least Recently Used (LRU)</strong> is a cache eviction policy that removes the least recently accessed item when the cache reaches its maximum capacity. The assumption is, if something is used recently, it is more probable to be used in the near future than something that was touched long ago.</p><p>This algorithm can be simply implemented through a HashMap and a <strong>Doubly Linked List</strong>. For more details on this, please refer <a href="https://medium.com/@ashwinhprasad/obvious-internals-of-ordered-maps-87315686e84a">Internals of Linked HashMap</a> .</p><p>Now let us come to the drawbacks of LRU:</p><p>If the workload has a burst of accesses to a large number of unique items, LRU may evict valuable items prematurely. Even If the workload only accesses these unique items only once, it will take a long time for them to get out of cache because their recent access time has been updated very recently.</p><p>Take a relational database management system as an example. If a query has to do a full table scan on a table due to lack of indexes on the necessary columns, all the pages pertaining to the particular table will be loaded into memory. Even if the query is executed only once and even though most of these are not “Important” or <strong>“Hot”</strong> as other significant pages which will be accessed for multiple different types of queries, these lesser important pages will stay in memory for a long time since they have been recently accessed.</p><p><strong>3.2.1) Hot Objects<br></strong>While <strong>temporal locality</strong> is crucial, it doesn’t account for another significant aspect: some objects are inherently <strong>“hot”</strong> or <strong>“valuable”</strong>. By <strong>“hot”</strong>, we mean objects that are accessed repeatedly across multiple queries or operations. These objects often represent shared resources or key data points that lie at the intersection of multiple workflows, making them critical for system efficiency.</p><p>For example, in hierarchical structures like indexes, objects closer to the root or top are frequently accessed because they serve as entry points to a broader range of data. In contrast, objects associated with more specific or isolated pieces of data tend to see infrequent use. This distinction highlights that <strong>frequency of access</strong> can be just as important as recency in determining an object’s value within the cache.</p><p><strong>LRU </strong>falls short in such scenarios because it prioritises recent activity without accounting for how often an object is accessed over time. As a result, <strong>“hot” </strong>objects that are essential to multiple queries might be evicted in favour of less valuable objects that were accessed more recently but are unlikely to be used again soon.</p><h3>4) Frequency Meets Recency: The LRU-K Breakthrough</h3><p>While LRU evicts the least recently accessed item, LRU-K tracks the <strong>K most recent accesses</strong> for each object. This allows the algorithm to estimate the <strong>temporal locality</strong> and <strong>frequency</strong> of an object over a longer time window.</p><p><strong>Frequency</strong>:<br>By tracking the <strong>K</strong> most recent accesses,<strong> LRU-K</strong> explicitly considers how often an object is used. Objects with shorter intervals between successive accesses <em>(indicating higher frequency)</em> are retained longer.</p><p><strong>Recency</strong>:<br>The algorithm does not ignore recency; it still gives priority to recently accessed objects when <strong>K</strong> is small or access intervals are analysed. Objects without recent activity naturally fall behind in priority.</p><p>This dual consideration ensures that <strong>LRU-K</strong> is well-suited for workloads where some objects are frequently shared <strong>(“hot”)</strong> across queries while still respecting the importance of temporal locality.</p><h4>4.1) LRU-K Algorithm</h4><p>For every object in the cache, the algorithm maintains a record of the last <strong>K</strong> times the object was accessed. These timestamps are updated every time the object is accessed.</p><p>When the cache storage is full and new space is required, The object with the largest <strong>Backward-K-Distance</strong> is chosen as the victim and is evicted to make more space.</p><p><strong>4.1.1) Backward-K-Distance<br></strong>Backward k-distance is computed as the difference in time between the current timestamp and the timestamp of <strong>Kth</strong> previous access time</p><p>So essentially, the object which has the earliest <strong>Kth</strong> access time is selected as the victim object.</p><p><strong>4.1.2) Special Case</strong></p><p>When there are objects in the cache that have not been accessed for at least K times, a secondary eviction algorithm can be used <em>(Such as LRU).</em></p><p>But the object with less than <strong>K</strong> access times should not be evicted if it’s last access time is within a certain threshold <em>(This threshold is a hyper parameter and depends on the system)</em>. This is to make sure that objects that are very recently added are not immediately removed. This is to avoid premature eviction.</p><h4>4.2) Why This Works?</h4><p>Now that the workings of LRU-K is clear, it’s time to dive into why it actually works. Why does considering the <strong>Kth</strong> last access time supposedly better than just using the last access time.</p><p>The <strong>Kth</strong> last access time captures more than just recency; it incorporates <strong>frequency</strong> within the context of recency. With this information, we can say that an object has been accessed <strong>K</strong> times within a given time frame which captures the inter arrival time of the object. By analysing <strong>K</strong> accesses over a given time frame, it reflects how frequently an object has been accessed in addition to when.</p><p>Let’s see an example to understand this:</p><pre>K = 5,<br>Object A: [T-50, T-40, T-30, T-20, T-10] # Have been accessed 5 times within 50 seconds<br>Object B: [T-90, T-70, T-50, T-30, T-10] # Have been accessed 5 times within 90 seconds<br>Object C: [T-35, T-25, T-15, T-10, T-5] # Have been accessed 5 times within 35 seconds</pre><p>Based on this information, the <strong>LRU-K algorithm</strong> suggests evicting <strong>Object B</strong> because its 5 accesses are spread over the widest time range compared to the other objects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*DU2juQBmRhjPBND13vuEXA.png" /><figcaption>Fig 4.2.1: Generated Normal Distribution Based on the above objects access time mean and standard deviation</figcaption></figure><p>In contrast, <strong>Object C’s Kth last access time</strong> is the closest to the current time, indicating it has been accessed 5 times within a shorter duration. This suggests higher recent activity and makes it a better candidate for retention. Object B, with more widely spread access times, demonstrates less recent utility and is chosen for eviction.</p><p>If, at a later point, Object C is not accessed frequently while other objects are, its <strong>Kth</strong> last access time will shift further into the past. This increases the <strong>standard deviation</strong> of its access time distribution, making it a stronger candidate for eviction when the time comes.</p><p>This is know LRU-K gives the best of both worlds: <strong>Frequency and Recency</strong></p><h3>5) Choosing the K Value In LRU-K</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*baEEBbRbNrwxA549H23Skw.png" /><figcaption>Fig 5.1: Cache Hit rates for different K values from LRU-K original paper</figcaption></figure><p>In the original paper introducing <strong>LRU-K</strong>, the authors highlight the significant advantages of increasing <strong>K</strong> in the algorithm. They note:</p><blockquote>“LRU-2 outperforms LRU-1 by more than a factor of 2 with respect to this cost/performance metric. We also note from this experiment that the results of LRU-3 are even closer to those of the optimum policy AO, compared to the results of LRU-2. In fact, it is possible to prove, with stable page access patterns, that LRU-K approaches AO with increasing value of K.”</blockquote><p>While increasing <strong>K</strong> improves cache hit ratios and moves closer to the optimal policy <em>(AO)</em>, it’s important not to select a <strong>K</strong> value that is too large. If <strong>K</strong> is excessively high, many objects may be evicted before being accessed <strong>K</strong> times, forcing the use of alternative eviction policies like standard LRU <em>(Complementary policy used when objects that have not been accessed at least </em><strong><em>K</em></strong><em> times are present)</em>. This can lead to inefficiencies in scenarios with high turnover of objects or infrequent access patterns.</p><p>Higher <strong>K </strong>values also introduce significant bookkeeping complexity. The system must maintain access histories for a larger number of objects, consuming more memory and processing power. This added overhead can negate the performance benefits of using higher <strong>K.</strong></p><p>A practical sane engineering approach to selecting <strong>K</strong> is to start with a small value, such as <em>K = 2</em>. Gradually increase <strong>K</strong> and monitor application telemetry, such as <strong>cache hit rates, latency, and memory usage</strong>, to identify the optimal balance between performance gains and resource consumption. This iterative method ensures <strong>K</strong> is tuned to the specific workload without unnecessary complexity.</p><h3>6) LRU-K in Action: Practical Implementation</h3><p>I will not be diving too much into code to show the implementation since that would make this programming oriented and that is not the goal of this writing piece. But I’ll write about the implementational details at a slightly higher level.</p><h4>6.1) CacheMap</h4><p>This is a HashMap that stores the mapping between the <strong>Cache Object Id</strong> <em>(Key)</em> and the <strong>content of the cache</strong> itself <em>(Value). </em>This is where the actual cache resides. Whenever a new object needs to be added to the cache, it is added here</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*hMPKH_Bi1TYjqj-gv1j_XA.png" /></figure><h4>6.2) AccessTimeMap</h4><p>For Each Cache Object in the <strong>CacheMap</strong>, we need to maintain the last <strong>K</strong> access times. Let’s use another HashMap for this and call this one the <strong>AccessTimeMap</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*XGzne0UKnAChwMvS2gv8Fw.png" /></figure><p>Whenever a cache object is accessed, the last access time window is updated in the <strong>AccessTimeMap </strong>for that particular cache object.</p><h4>6.3) Eviction</h4><p>When the <strong>CacheMap</strong> runs out of space and we need to insert a new cache in it, we need to evict an old cache. Now that we have the <strong>AccessTimeMap</strong> which contains the last K access times of each objects, simply iterate through the elements of the <strong>AccessTimeMap</strong> and evict the cache object with the least <strong>Kth</strong> recent access time.</p><p><strong>6.3.1) Performance Consideration<br></strong>This is a pretty slow process if the size of the cache is high. Iteration takes <em>O(n). </em>To quickly identify the least <strong>Kth</strong> recently accessed cache object, introduce a <strong>Min Heap</strong> into the equation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*OHaiqOgNNP9qWVWPRWkb3g.png" /></figure><p>This Min Heap will store the <strong>Kth</strong> recently access times of all objects <em>(There is an exception, will address that later on)</em> in the <strong>CacheMap</strong> as well as the <strong>Cache Object Id.</strong></p><p>With this, accessing the object with the <strong>Kth</strong> recently accessed time becomes quick, with a time complexity of <em>O(1). </em>Every time an object’s <strong>Kth</strong> access time entry is updated in <strong>AccessTimeMap</strong>, the min heap needs to be updated.</p><h4>6.4) Complementary LRU Policy</h4><p>Before we celebrate the successful planning of the LRU-K policy, there is a small missing piece of the equation we haven’t addressed yet. <strong>What if there are objects in the AccessTimeMap that are not accessed for at least K times since initialisation?</strong></p><p>In this scenario, we can’t use the min heap directly to evict the cache object since the min heap is built upon <strong>Kth</strong> last access time of the objects in cache.</p><p>To address this, along with the <strong>CacheMap</strong>, maintain a <strong>Doubly Linked List</strong> that tracks the access history of objects that have not been accessed for at least <strong>K</strong> times yet. When the <strong>AccessTimeMap’s Kth</strong> recent access time<strong> </strong>entry for the cache object is filled for the first time, delete the corresponding node from the doubly linked list. Elements that are recently accessed are added to the tail of the doubly linked list.</p><p>When a cache object needs to be evicted and if the doubly linked list is not empty, remove the<strong> Cache Object Id </strong>from the head of the doubly linked list. This is basically the standard <strong>LRU</strong> algorithm.</p><p>We’re just using regular LRU as a complementary policy for eviction when we know that there are objects in the cache that haven’t been accessed for at least <strong>K</strong> times.</p><h3>7) Conclusion</h3><p><strong>LRU-K</strong> emerged as a powerful response to the inadequacies of traditional cache eviction policies like <strong>LFU</strong> and <strong>LRU</strong>. While alternatives like <strong>ARC</strong> and other specialised solutions exist, <strong>LRU-K</strong> strikes a balance between simplicity and performance. It requires minimal bookkeeping, delivers near-optimal efficiency, and operates as a generic, self-sufficient policy — free from the need for higher-level system hints about the processes utilising the cache.</p><h3>8) References</h3><ul><li><a href="https://www.cs.cmu.edu/~natassa/courses/15-721/papers/p297-o_neil.pdf"><em>https://www.cs.cmu.edu/~natassa/courses/15-721/papers/p297-o_neil.pdf</em></a></li><li><a href="https://www.youtube.com/watch?v=aoewwZwVmv4&amp;list=PLSE8ODhjZXjYDBpQnSymaectKjxCy6BYq&amp;index=7"><em>https://www.youtube.com/watch?v=aoewwZwVmv4&amp;list=PLSE8ODhjZXjYDBpQnSymaectKjxCy6BYq&amp;index=7</em></a></li><li><a href="https://github.com/hygoni/research-paper-summary/blob/main/Memory%20Management/Page%20Replacement%20Algorithm/LRU-K/summary.md">https://github.com/hygoni/research-paper-summary/blob/main/Memory%20Management/Page%20Replacement%20Algorithm/LRU-K/summary.md</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96c292317474" width="1" height="1" alt=""><hr><p><a href="https://medium.com/everything-databases/from-lru-to-lru-k-elevate-your-caching-game-96c292317474">From LRU to LRU-K: Elevate Your Caching Game</a> was originally published in <a href="https://medium.com/everything-databases">Everything Databases</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>