<?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 Adam Jones on Medium]]></title>
        <description><![CDATA[Stories by Adam Jones on Medium]]></description>
        <link>https://medium.com/@ajones1_999?source=rss-d0f5562985df------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*9MEw85IVeKbxlPSIuZCA7A.jpeg</url>
            <title>Stories by Adam Jones on Medium</title>
            <link>https://medium.com/@ajones1_999?source=rss-d0f5562985df------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 15:16:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ajones1_999/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[Understanding MySQL Multiversion Concurrency Control]]></title>
            <link>https://medium.com/@ajones1_999/understanding-mysql-multiversion-concurrency-control-6b52f1bd5b7e?source=rss-d0f5562985df------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b52f1bd5b7e</guid>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Adam Jones]]></dc:creator>
            <pubDate>Sun, 16 Sep 2018 17:39:27 GMT</pubDate>
            <atom:updated>2018-09-17T15:20:37.821Z</atom:updated>
            <content:encoded><![CDATA[<p>MySQL, under the InnoDB storage engine, allows writes and reads of the same row to not interfere with each other. This is one of those features that we use so often it kind of gets taken for granted, but if you think about how you would build such a thing it’s a lot more detailed than it seems. Here, I am going to talk through how that is implemented, as well as some ramifications of the design.</p><h4>Allowing Concurrent Change</h4><p>Unsurprisingly, given the title of this post, MySQL’s mechanism for allowing you to simultaneously read and write from the same row is called “Multiversion Concurrency Control”. They (of course) <a href="https://dev.mysql.com/doc/refman/8.0/en/innodb-multi-versioning.html">have documentation</a> on it, but that dives into internal technical details pretty fast.</p><p>Instead, let’s talk about it at a little higher level. This concept has been around for a long time (the best I can do hunting down an origin is a <a href="https://dspace.mit.edu/handle/1721.1/16279">thesis</a> from 1979). The overall answer for allowing concurrent reads and writes is pretty simple: writes create new versions of rows, reads see the version that was current when they started.</p><h4>Version tracking</h4><p>Obviously if we’re going to keep track of versions, we need something to differentiate them. This tool needs to distinguish one version from another, but ideally it would also make it easy to decide which version a read operation should see.</p><p>In MySQL, this “version enabling thing” is a transaction id. Every transaction gets one. Even your one-shot update queries in the console get one. These ids are incremented in a way that allows MySQL to determine that one transaction started before another. Every table under InnoDB essentially has a “hidden column” that stores the transaction id of the last write operation to change the row. So, in addition to the columns you may have updated, a write operation <em>also</em> marks the row with its transaction id. This allows read operations to know if they can use the row data, or if it has been changed and they need to consult an older version.</p><h4>Reading older version</h4><p>For the cases where your read operation hits on rows that have been changed, you’ll need an older version of the data. The transaction id comes into play here too, but there’s more info needed. Every time MySQL writes data into a row, it <em>also</em> writes an entry into the rollback segment. This is a data structure that stores “undo logs” used to restore the row to its previous state. It’s called the “rollback segment” because it is the tool used to handle rolling back transactions.</p><p>The rollback segment stores undo logs for each row in the database. Every row has <em>another</em> hidden column that stores the location of the latest undo log entry, which would restore the row to its state prior to the last write. When these entries are created, they are marked with the <em>outgoing</em> transaction id. By walking the undo log for a row and finding the latest transaction <em>before</em> a read transaction the database can identify the correct data to present to a transaction.</p><h4>Handling deletes</h4><p>Deletion is handled by a marker in the row to indicate a record was deleted. Delete operations <em>also</em> set the row’s transaction id to their transaction id, so the process above can present a pre-delete version of the row to read operations that started before the delete.</p><h4>When are versions deleted</h4><p>MySQL obviously cannot keep a record of every change that happens in the database for all time. It doesn’t need to, though. Undo logs can be removed as soon as the last transaction that could possibly want them completes.</p><p>Similarly, rows that have been marked as deleted can be outright abandoned once the oldest active transaction started after the deletion. These rows and undo logs are physically removed to reclaim their disk space by a “purge” operation that happens in its own thread in the background.</p><h4>What about indexes</h4><p>So, to recap, MySQL handles versions by keeping the row constantly up to date and storing diffs for as long as currently running queries need them. That’s only half the story though, indexes need to support consistent reads as well. Primary key indexes work much like the above description for actual database rows. Secondary indexes are a little different.</p><p>MySQL handles this in two ways: pages of index entries are marked by the last transaction id to write in them, and individual index entries have delete markers. When an update changes an indexed column, three things happen: the current index entry is delete marked, a new entry for the updated value is written, and that new entry’s index page is marked with the transaction id.</p><p>Read operations that find non-delete-marked entries in pages that predate their transaction id use that index data directly. If the operation finds either a delete marker <em>or</em> a newer transaction id, it looks up the row and traverses the undo log to find the appropriate value to use.</p><p>Similar to the purging of deleted rows from expired transactions, delete-marked index entries are also eventually reclaimed. Because there is always a fresh new entry to work with <em>somewhere</em> in the index, MySQL can be a little more aggressive at cleaning those up.</p><h4>What do I do with this information?</h4><p>So, given the above, what can we take home to make our lives better? A few things. Keep in mind with all of this that database performance can be very difficult to analyze. Each point below is just one potential piece of the story of what could be happening with your data.</p><ul><li>Big transactions are painful: Long running transactions don’t just tie up a connection, they force the database to preserve history for longer. If that transaction is reading through a large swath of the database subsequent writes will force it to read the rollback log, which may be in a different page of memory or even on disk.</li><li>Multi-statement transactions need to commit quickly: This is another variety of “big transactions are painful”, but it’s worth calling out. MySQL does not “kill” active transactions. If you open a transaction, query out data, then spend two hours in application code before committing, MySQL will faithfully preserve undo history for two hours. Every moment of an open transaction forces more undo history. Commit as quickly as you can and do your processing outside of transactions whenever possible.</li><li>Writes make index scans less useful. The whole point of an index is to answer questions about your data without actually looking at your data. Delete markers on index entries, and transaction stamps on index pages, force the database to read your data. Think carefully about using composite indexes with columns you aren’t querying. Your queries will pay the price for updates to those columns anyways.</li><li>Rapid fire writes magnify the penalties for reads. If you have a lot of data to write, especially <em>to the</em> <em>same row</em>, write it in chunks instead of one-by-one. Each write generates a transaction id, relevant undo logs, and makes a mess of secondary indexes. Chunking writes together increases the chances that reads will find valid index data, and lowers the size of undo logs they have to wade through. There’s an opposite extreme where one big write might have too much data, so it’s important to look for the happy middle ground here.</li><li>“Hot” rows are hot for all columns, not just updated ones. A row that stores a frequently updated counter forces more row transaction id updates and undo log entries. Queries that start before the counter is incremented, <em>even if they don’t use the counter</em>, still have to traverse undo logs for the row state when they started. That same logic applies to <em>extremely</em> frequently updated timestamps that aggregate change times across the relations to a row. If possible, batch those updates beforehand or consider storing them in a separate table you can join to when needed.</li><li>Consider separating reporting from direct/application use reads. Reporting queries tend to scan large sections of the database. They take a long time and thus force the preservation and consumption of more undo history. Most application behavior is more direct: it knows specific records to retrieve and goes straight for them. If you’re already using read replicas, consider dedicating one to reporting so that your application queries don’t pay the undo storage penalties of reporting.</li></ul><h4>Final thoughts</h4><p>It’s worth noting that this is not the only way to implement MVCC. PostgreSQL handles this task by storing the minimum and maximum transaction ids where a row should be visible. Under that scheme, updating a row sets the maximum transaction id on it and creates an entirely new row entry by copying the original and performing the update in that copy. This avoids the need for undo logs, but at the cost of copying all row data for each update.</p><p>The point here is that, for cases where you are really trying to push database performance, understanding a few of the bigger details of the internals can pay off. Many of the takeaways I listed are only going to be applicable in extreme use cases, but in those cases knowing how the database goes about versioning data can make understanding performance problems easier.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b52f1bd5b7e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the Elasticsearch Percolator]]></title>
            <link>https://medium.com/@ajones1_999/understanding-the-elasticsearch-percolator-4e5c15b2dc33?source=rss-d0f5562985df------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e5c15b2dc33</guid>
            <category><![CDATA[elasticsearch]]></category>
            <dc:creator><![CDATA[Adam Jones]]></dc:creator>
            <pubDate>Tue, 24 Apr 2018 15:49:35 GMT</pubDate>
            <atom:updated>2018-12-06T16:49:01.449Z</atom:updated>
            <content:encoded><![CDATA[<p>Elasticsearch is a powerful, feature-packed tool. Their <a href="https://www.elastic.co/guide/index.html">documentation</a> is great, but some pieces are a bit … out there. Beyond that, some of the functionality has changed significantly over the years, so third-party explanations might no longer be accurate.</p><p>One fantastic feature that is both unusual and has changed a lot is <em>percolation</em>. I’m going to try to explain that feature, in the context of its current implementation (version 6.2.4). You’ll need a basic understanding of Elasticsearch, specifically <a href="https://www.elastic.co/guide/en/elasticsearch/reference/6.2/mapping.html">mappings</a> and <a href="https://www.elastic.co/guide/en/elasticsearch/reference/6.2/search-request-body.html">search</a>.</p><h3>The Concept</h3><p>The normal workflow for Elasticsearch is to store <em>documents</em> (as JSON data) in an index, and execute <em>searches</em> (also JSON data) to ask the index about those documents.</p><p>Succinctly, percolation reverses that. You store <em>searches</em> and use <em>documents</em> to ask the index about those searches. That’s true, but it’s not particularly actionable information. How percolators are structured has evolved over the years, to the point where we can give a more useful explanation.</p><p>Now, percolation revolves around the <a href="https://www.elastic.co/guide/en/elasticsearch/reference/6.2/percolator.html">percolator</a> mapping field type. This is like any other field type, except that it expects you to assign a search document as the value. When you store data, the index processes this search document into an executable form and saves it for later.</p><p>The <a href="https://www.elastic.co/guide/en/elasticsearch/reference/6.2/query-dsl-percolate-query.html">Percolate Query</a> takes one or more documents and limits results to ones whose stored searches match at least one document. When searching, the percolate query works like any other query element.</p><h3>In Depth</h3><p>Under the hood, this is implemented in about the way you would expect: indexes with <em>percolate</em> fields keep a hidden (in memory) index. Documents listed in your percolate queries are first put in that index, then a normal query is executed against that index to see if the original percolate-field-bearing document matches.</p><p>An important point to remember is that this hidden index gets its mappings from the original percolator index. So indexes used for percolate queries need to have mappings appropriate for the original data <em>and</em> the query document data.</p><p>This introduces a bit of a management problem, in that your index data and the percolate query documents could use the same field in different ways. A simple answer to that is to use the <a href="https://www.elastic.co/guide/en/elasticsearch/reference/6.2/object.html">object type</a> to isolate the percolate-relevant mappings from normal document mappings.</p><p>Assuming the queries you are using were originally written for another index of actual documents, it makes the most sense to isolate the data going directly into the percolate index and give the root level over to mapping definitions for percolate query documents.</p><p>Also, because percolate fields are parsed into searches and saved at index time, you likely will need to reindex percolate documents after upgrading to take advantage of any optimizations to the system.</p><h3>An Example</h3><p>In my opinion, percolator examples are one of the prime contributors to making the tool hard to understand. They tend to be <em>too</em> simple, to the point where it’s hard to distinguish the parts.</p><p>In this example, we’re going to build out an index of saved term and price searches for toys. The idea behind it is that users should be able to put in a search term and a max price, then get notified as soon as something matching that term goes below this price. Users should also be able to turn these notifications on and off.</p><p>The mapping below implements a percolate index to support this feature. Fields related to the saved search itself are in the search object, while fields related to the original toys live at the root level of the mappings.</p><pre>{<br>  &quot;mappings&quot;: {<br>    &quot;_doc&quot;: {<br>      &quot;properties&quot;: {<br>        &quot;search&quot;: {<br>          &quot;properties&quot;: {<br>            &quot;query&quot;:   { &quot;type&quot;: &quot;percolator&quot; },<br>            &quot;user_id&quot;: { &quot;type&quot;: &quot;integer&quot; },<br>            &quot;enabled&quot;: { &quot;type&quot;: &quot;boolean&quot; }<br>          },<br>        },<br>        &quot;price&quot;:       { &quot;type&quot;: &quot;float&quot; },<br>        &quot;description&quot;: { &quot;type&quot;: &quot;text&quot; }<br>      }<br>    }<br>  }<br>}</pre><p>Here is what a document that represents a stored search would look like:</p><pre>{<br>  &quot;_id&quot;: 1,<br>  &quot;search&quot;: {<br>    &quot;user_id&quot;: 5,<br>    &quot;enabled&quot;: true&quot;,<br>    &quot;query&quot;: {<br>      &quot;bool&quot;: {<br>        &quot;filter&quot;: [<br>          { <br>            &quot;match&quot;: { <br>              &quot;description&quot;: { &quot;query&quot;: &quot;nintendo switch&quot; }<br>            }<br>          },<br>          { &quot;range&quot;: { &quot;price&quot;: { &quot;lte&quot;: 300.00 } } }<br>        ]<br>      }<br>    }<br>  }<br>}</pre><p>Note that we are <em>only</em> storing data inside the search object field. The mappings for price and description are just there to support percolate queries.</p><p>At query time, we want to use both the plain object fields and the “special” percolator field. This query would check, inside a user’s searches, to see which currently-enabled searches match the document.</p><pre>{<br>  &quot;query&quot;: {<br>    &quot;bool&quot;: {<br>      &quot;filter&quot;: [<br>        {<br>          &quot;percolate&quot; : {<br>            &quot;field&quot; : &quot;search.query&quot;,<br>            &quot;document&quot; : {<br>              &quot;description&quot; : &quot;Nintendo Switch&quot;,<br>              &quot;price&quot;: 250.00<br>            }<br>          }<br>        },<br>        { &quot;term&quot;: { &quot;search.enabled&quot;: true } },<br>        { &quot;term&quot;: { &quot;search.user_id&quot;: 5 } }<br>      ]<br>    }<br>  }<br>}</pre><p>Note that it combines percolate matching of a document against the queries stored in the field with regular term queries to limit which documents we test based on their enabled state and the user id.</p><h3>Some Additional Thoughts</h3><p>Because of the work involved in running queries as part of resolving a percolate filter, you might need to pay extra attention to shards/replicas for a percolate index. Each shard reduces the number of queries any one machine may have to run, by reducing the number of search-bearing documents to evaluate.</p><p>Percolate queries have an option to get documents from another index inside the cluster. This takes the form of a literal GET request, so there’s not much benefit in trying to keep shards from the two indices on the same nodes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e5c15b2dc33" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>