<?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"><channel><title><![CDATA[Kartik Patel]]></title><description><![CDATA[Distributed systems and database internals derived from first principles.]]></description><link>https://kartikpatel.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Fri, 04 Dec 2026 22:03:16 GMT</lastBuildDate><atom:link href="https://kartikpatel.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Leveled vs Tiered Compaction: Choosing Which Bill Your LSM Tree Pays]]></title><description><![CDATA[Every LSM tree pays for writes, reads and disk space. Compaction decides which bill gets big. Measured on a simulator, then mapped to RocksDB and Cassandra…]]></description><link>https://kartikpatel.hashnode.dev/leveled-vs-tiered-compaction</link><guid isPermaLink="true">https://kartikpatel.hashnode.dev/leveled-vs-tiered-compaction</guid><category><![CDATA[Databases]]></category><category><![CDATA[System Design]]></category><category><![CDATA[distributed systems]]></category><category><![CDATA[backend]]></category><category><![CDATA[data structures]]></category><dc:creator><![CDATA[Kartik Patel]]></dc:creator><pubDate>Thu, 03 Dec 2026 14:54:37 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6b0eb80d6182b3fdea5e8bf5/d29cfa94-5eca-43bc-86b0-ef452af328c0.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Picture a feature store for a recommendations system. A batch job recomputes every user's features a few times a day and writes them back to Cassandra. Same keys, new values, over and over.</p>
<p>Live data is 400 GB per node, on a 1.6 TB disk. The dashboard has shown the disk at about 55% for weeks. Then one night a node runs out of disk in the middle of a compaction, and nothing about the traffic changed.</p>
<p>Nobody misconfigured anything. That's what <strong>size-tiered compaction</strong> does to a workload that overwrites its keys, and it's the default Cassandra gives a table if you don't pick a strategy.</p>
<p>In <a href="https://kartikpatel.hashnode.dev/why-lsm-trees-exist">Part 1</a> we saw that compaction is what keeps an LSM tree readable. This article is about <em>how</em> you compact, because that one choice decides where your costs land. We'll look at the two classic strategies, measure them on the same workloads, and then look at the hybrid that most modern engines are moving to.</p>
<p>Everything here is backed by one Python script you can run (link at the end).</p>
<hr />
<h2>1. Three bills, and you only get to shrink two</h2>
<p>Every LSM tree pays three costs, and compaction decides how big each one is:</p>
<ul>
<li><strong>Write cost</strong> (write amplification): how many times each byte is rewritten on its way down the tree. This is disk bandwidth, and on SSDs it's also drive wear.</li>
<li><strong>Read cost</strong>: how many sorted runs a lookup or a range scan has to check. Bloom filters (<a href="https://kartikpatel.hashnode.dev/bloom-filters-in-lsm-trees">Part 2</a>) make point lookups cheap, but a range scan still has to open every run.</li>
<li><strong>Space cost</strong> (space amplification): disk used divided by live data. Old versions of a key and deleted keys sit on disk until compaction reaches them.</li>
</ul>
<p>Merging eagerly keeps reads and space small, but rewrites data more often. Merging lazily saves writes, but leaves more runs and more stale copies around. Researchers call this the <strong>RUM conjecture</strong> (Read, Update, Memory): you can make two of the three small, not all three.</p>
<p>The two classic strategies sit at opposite ends.</p>
<hr />
<h2>2. Leveled: merge early, keep it tidy</h2>
<p>This is what RocksDB and LevelDB do by default, and what we built in Part 1.</p>
<pre><code class="language-plaintext">L0   [f][f][f][f]                       ← fresh flushes, overlapping
L1   [ a–f ][ g–m ][ n–s ][ t–z ]       ← one sorted run, split into files
L2   [a–b][c–d][e–f] ... [y–z]          ← 10× bigger, still one sorted run
L3   ...                                ← 10× bigger again
</code></pre>
<p>The rule: <strong>every level below L0 is one sorted run.</strong> No two files in a level overlap.</p>
<p>When a level gets bigger than its target, the engine picks <strong>one file</strong> from it and merges that file into the files it overlaps in the next level. Because the next level is 10× bigger, one file's key range overlaps about 10 files there. So pushing one file down means rewriting about 11 files' worth of data.</p>
<p>That's the write cost: roughly up to 10 rewrites per level, for every byte, at every level it passes through.</p>
<p>What you get in return:</p>
<ul>
<li><strong>Reads are cheap.</strong> One file per level, so a lookup checks L0 plus one file per level.</li>
<li><strong>Space is cheap.</strong> About 90% of the data sits in the last level. Even if every key in the upper levels were a stale copy, that's only about 11% extra.</li>
<li><strong>Each compaction is small.</strong> One file plus its neighbours, not a whole level. You never need much free disk to run one.</li>
</ul>
<hr />
<h2>3. Tiered: merge late, write less</h2>
<p>This is Cassandra's size-tiered strategy (STCS) and RocksDB's universal compaction.</p>
<pre><code class="language-plaintext">small    [r][r][r][r]        ← 4 similar-sized runs? merge them into one
medium   [ run ][ run ]      ← wait for 4 of these
large    [   run   ]
</code></pre>
<p>The rule: <strong>wait until you have several runs of similar size (4 by default in Cassandra), then merge them all into one bigger run.</strong> Never merge a small run into a big one.</p>
<p>Each byte gets rewritten <strong>once per size tier</strong>, not ~10 times per level. That's why tiered compaction is the write-friendly choice.</p>
<p>What it costs:</p>
<ul>
<li><strong>More runs to check.</strong> Each tier can hold several runs, so a lookup or scan may touch many more of them.</li>
<li><strong>Stale copies pile up.</strong> If a key is updated often, a copy of it lives in <em>every</em> run that got written since the last merge. Four big runs can mean four copies of most of your data.</li>
<li><strong>Big merges need big free space.</strong> The merged output has to be fully written before the inputs are deleted. When the biggest tier merges, you briefly need room for the inputs <strong>and</strong> the output.</li>
</ul>
<hr />
<h2>4. Measured side by side</h2>
<p>I wrote a simulator that runs real sorted runs through each strategy: RocksDB-style leveled (L0 trigger of 4, levels 10× apart) and Cassandra-style size-tiered (merge 4 similar-sized runs). Same memtable size, same stream of writes.</p>
<h3>Workload 1: insert-only (4M new keys, like an event log)</h3>
<table>
<thead>
<tr>
<th></th>
<th>Leveled</th>
<th>Tiered</th>
</tr>
</thead>
<tbody><tr>
<td>Bytes written per byte inserted</td>
<td>12.8×</td>
<td><strong>4.4×</strong></td>
</tr>
<tr>
<td>Runs a lookup checks (average / worst)</td>
<td><strong>3.5 / 6</strong></td>
<td>6.3 / 12</td>
</tr>
<tr>
<td>Disk used / live data</td>
<td>1.00×</td>
<td>1.00×</td>
</tr>
<tr>
<td>Biggest single compaction (% of live data)</td>
<td><strong>12%</strong></td>
<td>100%</td>
</tr>
</tbody></table>
<p>Tiered writes about <strong>3× less</strong>. With no overwrites, there are no stale copies, so space looks the same. But notice the last row: at some point tiered compaction merges <strong>all of your data at once</strong>, so for a while it needs double the disk. That's where the well-known Cassandra and ScyllaDB rule of thumb comes from: <strong>keep about 50% of the disk free with size-tiered compaction.</strong></p>
<h3>Workload 2: update-heavy (4M writes over 400K keys, like the feature store)</h3>
<table>
<thead>
<tr>
<th></th>
<th>Leveled</th>
<th>Tiered</th>
</tr>
</thead>
<tbody><tr>
<td>Bytes written per byte inserted</td>
<td>7.6×</td>
<td><strong>3.5×</strong></td>
</tr>
<tr>
<td>Runs a lookup checks (average / worst)</td>
<td><strong>3.3 / 5</strong></td>
<td>6.1 / 12</td>
</tr>
<tr>
<td>Disk used / live data (average)</td>
<td><strong>1.12×</strong></td>
<td>2.18×</td>
</tr>
<tr>
<td>Peak disk during compaction / live data</td>
<td><strong>1.34×</strong></td>
<td><strong>4.30×</strong></td>
</tr>
</tbody></table>
<p>(Write cost is lower than in workload 1 for both, because overwritten versions get dropped during merges instead of being carried down.)</p>
<p>This is the feature store from the intro. On average, tiered compaction keeps 2.2× the live data on disk: 870 GB of a 1.6 TB disk, the "55%" on the dashboard. But every so often it merges four big runs that each hold a copy of nearly every key. For that merge it needs <strong>4.3× the live data</strong>, about 1.7 TB. The disk is 1.6 TB.</p>
<p>The "50% free" rule doesn't save you here. It assumes the biggest merge is about the size of your data. With heavy overwrites, it can be several times that.</p>
<p>Leveled compaction pays 2× more writes, but its disk use barely moves.</p>
<blockquote>
<p><strong>Leveled pays in writes. Tiered pays in disk space, and in big, sudden bursts of it.</strong></p>
</blockquote>
<hr />
<h2>5. The hybrid: tiered on top, leveled at the bottom</h2>
<p>Two facts point to a better design:</p>
<ol>
<li><strong>Writes cost about the same at every level.</strong> Each level rewrites each byte a similar number of times, whatever its size.</li>
<li><strong>Space and reads are decided at the bottom.</strong> The last level holds about 90% of the data, so that's where stale copies and lookups pile up.</li>
</ol>
<p>So use tiered merging for the small upper levels, where it saves writes, and keep <strong>the last level as a single sorted run</strong>, where it keeps space and reads under control. This is called <strong>lazy leveling</strong> (from the Dostoevsky paper, Dayan and Idreos, SIGMOD 2018).</p>
<table>
<thead>
<tr>
<th>Update-heavy workload</th>
<th>Leveled</th>
<th>Tiered</th>
<th><strong>Hybrid</strong></th>
</tr>
</thead>
<tbody><tr>
<td>Bytes written per byte inserted</td>
<td>7.6×</td>
<td>3.5×</td>
<td><strong>5.4×</strong></td>
</tr>
<tr>
<td>Runs a lookup checks (average)</td>
<td>3.3</td>
<td>6.1</td>
<td><strong>3.7</strong></td>
</tr>
<tr>
<td>Disk used / live data (average)</td>
<td>1.12×</td>
<td>2.18×</td>
<td><strong>1.15×</strong></td>
</tr>
</tbody></table>
<p>On insert-only, the hybrid wrote 7.7× vs 12.8× for leveled. So it keeps much of tiered's write saving while keeping almost all of leveled's space efficiency.</p>
<p>One caveat from the simulator: my hybrid merges into the last level in one go, so its biggest merge is still large. Production versions avoid that by doing the bottom merge <strong>in pieces</strong>, a few files at a time, and freeing inputs as they go. That's exactly what Cassandra's and ScyllaDB's newer strategies do (section 7).</p>
<hr />
<h2>6. A special case: data that expires</h2>
<p>Metrics, logs and IoT readings have a shape no general strategy handles well: data arrives in time order, is almost never updated, and gets deleted by age (a TTL).</p>
<p>Merging that data is pure waste. You rewrite rows that will be deleted in a few days anyway.</p>
<p>The fix is to <strong>not merge across time at all</strong>:</p>
<ul>
<li><strong>Cassandra's TimeWindowCompactionStrategy (TWCS)</strong> groups SSTables into time windows (say, one per day). Inside the current window it compacts normally; once the window closes, it compacts it down to one file and never touches it again. When every row in a file has expired, the whole file is <strong>dropped</strong>. No merge, no rewrite.</li>
<li><strong>RocksDB's FIFO compaction</strong> goes further: it just deletes the oldest files once the total size passes a limit.</li>
</ul>
<p>One warning from production: TWCS assumes data really is written in time order. If an application updates or deletes old rows, those writes land in today's window while the originals sit in an old one, and the old files can no longer be dropped cleanly.</p>
<hr />
<h2>7. What production engines actually do</h2>
<p><strong>RocksDB</strong></p>
<ul>
<li><strong>Leveled is the default</strong>, and it's already a small hybrid: L0 is tiered. Flushed files pile up until <code>level0_file_num_compaction_trigger</code> (4) of them exist, then they merge into the level below together.</li>
<li><code>level_compaction_dynamic_level_bytes</code> is now on by default. It sizes levels from the bottom up, so the last level always holds about 90% of the data. With it turned off, my simulator's update-heavy run used <strong>1.75×</strong> the live data instead of 1.12×, because the database's size didn't line up with the fixed level targets and a "middle" level ended up holding stale copies of most keys.</li>
<li><strong>Universal compaction</strong> is RocksDB's tiered strategy. Its <code>max_size_amplification_percent</code> defaults to 200, which means the database can grow to <strong>3× the live data</strong> before a full merge is forced, and that full merge temporarily needs double the disk again.</li>
<li><strong>Write stalls</strong> are how leveled compaction tells you it's falling behind. RocksDB slows writes at 20 L0 files and stops them at 36, and does the same when pending compaction bytes pass 64 GB (slow) and 256 GB (stop). If you see stalls, compaction can't keep up with your write rate.</li>
</ul>
<p><strong>Cassandra and ScyllaDB</strong></p>
<ul>
<li><strong>STCS</strong> is still the default if a table doesn't specify a strategy. It merges once 4 similar-sized SSTables exist.</li>
<li><strong>LCS</strong> (leveled, 160 MB SSTables, levels 10× apart) is the recommended choice for read-heavy tables and tables with lots of updates and deletes. The feature store belongs here.</li>
<li><strong>TWCS</strong> for time series and TTL data, as above.</li>
<li><strong>UCS</strong> (Unified Compaction Strategy, Cassandra 5.0) is now the recommended strategy for new tables. It mixes tiered and leveled behaviour, splits data into shards so merges are smaller and run in parallel, and can switch between tiered-like and leveled-like settings <strong>without a full recompaction</strong>. Changing strategy used to mean rewriting the whole table.</li>
<li><strong>ScyllaDB's Incremental Compaction (ICS)</strong> keeps size-tiered's low write cost, but merges big runs fragment by fragment and frees space as it goes. ScyllaDB's rule of thumb drops from 50% free disk to about 30%.</li>
</ul>
<p><strong>Watch it in production.</strong> For leveled: L0 file count, pending compaction bytes and write stall time. For tiered: disk free compared to the size of your largest SSTables, not just the percentage used. In Cassandra, <code>nodetool compactionstats</code> shows pending compactions and <code>nodetool tablestats</code> shows SSTable counts per table.</p>
<hr />
<h2>8. How to choose</h2>
<table>
<thead>
<tr>
<th>Your workload</th>
<th>Pick</th>
<th>Why</th>
</tr>
</thead>
<tbody><tr>
<td>Read-heavy, or keys updated and deleted often (profiles, carts, feature stores)</td>
<td><strong>Leveled</strong></td>
<td>Low space overhead, few runs per read, small compactions</td>
</tr>
<tr>
<td>Write-heavy, mostly new keys, disk to spare (event ingestion, audit logs)</td>
<td><strong>Tiered</strong></td>
<td>Lowest write cost; keep plenty of disk free</td>
</tr>
<tr>
<td>Heavy writes <em>and</em> you care about disk</td>
<td><strong>Hybrid</strong> (UCS, ICS, lazy leveling)</td>
<td>Most of tiered's write saving, most of leveled's space efficiency</td>
</tr>
<tr>
<td>Time-ordered data that expires</td>
<td><strong>TWCS / FIFO</strong></td>
<td>Drop whole files instead of merging</td>
</tr>
</tbody></table>
<p>If you're unsure, start leveled. Its failure mode is slow: write amplification and stalls that show up on dashboards. Tiered's failure mode is sudden: a disk that fills up in one night.</p>
<hr />
<h2>The short version</h2>
<ol>
<li>Compaction decides how big three bills get: <strong>writes</strong>, <strong>reads</strong> and <strong>disk space</strong>. You can keep two of them small, not all three.</li>
<li><strong>Leveled</strong> keeps one sorted run per level. It rewrites data more (12.8× in our insert test), but keeps reads and space tight and every compaction small.</li>
<li><strong>Tiered</strong> merges runs of similar size. It writes about 3× less, but leaves more runs to read and can need several times your live data in disk space when keys are overwritten (4.3× at peak in our update test).</li>
<li><strong>Hybrids</strong> use tiered merging on top and a single sorted run at the bottom. They keep most of tiered's write savings with leveled's space efficiency, and modern engines (Cassandra UCS, ScyllaDB ICS) do the big merges in pieces.</li>
<li>For data that expires by time, don't merge at all: <strong>TWCS or FIFO</strong> drop whole files.</li>
</ol>
<hr />
<h2>What's next</h2>
<p>This is part 3 of <strong>LSM trees from first principles</strong>. Next up: <strong>deletes</strong>. In an LSM tree, a delete is just another write, and the tombstones it leaves behind can quietly slow down reads and keep disk space from coming back.</p>
<p><strong>Code for this article:</strong></p>
<ul>
<li><a href="https://github.com/dev64-kartik/storage-engine-articles/blob/main/simulations/03-compaction/compaction_sim.py"><code>compaction_sim.py</code></a>: leveled (with and without dynamic level sizing), size-tiered and lazy leveling on insert-only and update-heavy workloads</li>
</ul>
<p><strong>Further reading</strong></p>
<ul>
<li>Athanassoulis et al., <em>Designing Access Methods: The RUM Conjecture</em>, EDBT 2016</li>
<li>Dayan, Idreos, <em>Dostoevsky: Better Space-Time Trade-Offs for LSM-Tree Based Key-Value Stores</em>, SIGMOD 2018</li>
<li>RocksDB wiki, <em>Leveled Compaction</em>, <em>Universal Compaction</em> and <em>Write Stalls</em></li>
<li>Apache Cassandra docs, <em>Compaction overview</em> and <em>Unified Compaction Strategy</em></li>
<li>ScyllaDB blog, <em>Maximizing Disk Utilization with Incremental Compaction</em>, 2020</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Bloom Filters in LSM Trees: How Databases Make "Not Found" Cheap]]></title><description><![CDATA[A few bits per key turn eight disk reads into almost none. Then a smarter split of the same memory cuts the waste by another 3x.]]></description><link>https://kartikpatel.hashnode.dev/bloom-filters-in-lsm-trees</link><guid isPermaLink="true">https://kartikpatel.hashnode.dev/bloom-filters-in-lsm-trees</guid><category><![CDATA[Databases]]></category><category><![CDATA[System Design]]></category><category><![CDATA[distributed systems]]></category><category><![CDATA[backend]]></category><category><![CDATA[data structures]]></category><category><![CDATA[storage]]></category><dc:creator><![CDATA[Kartik Patel]]></dc:creator><pubDate>Wed, 02 Dec 2026 05:49:33 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6b0eb80d6182b3fdea5e8bf5/2570c19a-fda3-4369-b3a5-5eb99dc2b05f.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Picture an event pipeline that deduplicates by event ID. Every incoming event asks the store one question: <em>have I seen this ID before?</em> At 40,000 events per second, that's 40,000 lookups per second, and about 99% of them get the same answer: <strong>no</strong>.</p>
<p>On a B+tree, "no" is cheap: walk one path from root to leaf and you're done. On an LSM tree, "no" is the <strong>most expensive answer there is</strong>. And yet RocksDB, Cassandra and ScyllaDB answer it with almost no disk reads at all.</p>
<p>The trick is a Bloom filter. This article covers why LSM trees need one, how to size it, and one idea most production setups leave on the table: spending the same filter memory <strong>unevenly</strong> across levels makes "not found" about <strong>3× cheaper</strong> again.</p>
<p>Everything here is backed by one Python script you can run (link at the end).</p>
<hr />
<h2>1. Why "not found" is the worst-case read</h2>
<p>In <a href="https://kartikpatel.hashnode.dev/why-lsm-trees-exist">Part 1</a> we built an LSM tree: writes go to a memtable, get flushed as sorted SSTable files, and compaction merges them down through levels that grow 10× each step.</p>
<p>That design makes writes cheap by making <strong>reads</strong> look in many places. A key could be in:</p>
<pre><code class="language-plaintext">memtable                     (RAM)
L0: file 1, file 2, file 3, file 4   ← overlapping, check each one
L1, L2, L3, L4               ← one sorted run per level, check one file each
</code></pre>
<p>A lookup checks newest to oldest and <strong>stops at the first hit</strong>. So a key that exists is usually found early. A key that <em>doesn't</em> exist never gets a hit. It has to check every place, all the way to the bottom.</p>
<p>Even with every SSTable's index cached in memory, checking a file still means reading one data block from disk. With 4 L0 files and 4 levels, that's <strong>8 random reads to say "no"</strong>.</p>
<p>For the dedup pipeline: 40,000 × 99% × 8 ≈ <strong>317,000 random reads per second</strong>, spent on answering "this key isn't here". That's a big share of what even a fast NVMe drive can deliver, and none of it returns any data.</p>
<p>What we want is a way to ask each file <em>"could this key be in you?"</em> <strong>without touching the disk</strong>.</p>
<hr />
<h2>2. A Bloom filter in 60 seconds</h2>
<p>A Bloom filter is a bit array plus a few hash functions. One filter per SSTable, built when the file is written, kept in memory.</p>
<p><strong>Adding a key:</strong> hash it k times, and set those k bits to 1.</p>
<p><strong>Looking up a key:</strong> hash it the same k times, and check those bits.</p>
<pre><code class="language-plaintext">bit array:   0 0 1 0 0 0 0 1 0 0 0 0 0 1 0 0
             0 1 2 3 4 5 6 7 8 9 ...

add("evt:42")     → bits 2, 7, 13   → set to 1

lookup("evt:42")  → bits 2, 7, 13   → all 1   → MAYBE here  (go read the file)
lookup("evt:99")  → bits 4, 7, 11   → bit 4 is 0 → DEFINITELY NOT here (skip the file)
</code></pre>
<p>Two properties make it a perfect fit:</p>
<ul>
<li><strong>It never says "no" to a key that's there.</strong> If the key was added, its bits are 1. So skipping a file on "no" is always safe.</li>
<li><strong>It sometimes says "maybe" to a key that isn't there</strong>, because other keys happened to set the same bits. That's a <strong>false positive</strong>, and it costs one wasted disk read.</li>
</ul>
<p>There's also a reason Bloom filters suit LSM trees better than almost any other structure: <strong>you can't delete from a Bloom filter</strong>, but you never need to. SSTables are immutable. When compaction rewrites files, it builds fresh filters for the new files and throws the old ones away.</p>
<hr />
<h2>3. How many bits per key?</h2>
<p>The only knob that really matters is <strong>bits per key</strong>: how much memory you give the filter for each key in the file. I built real filters with 1 million keys and queried them with 1 million keys that weren't in them:</p>
<table>
<thead>
<tr>
<th>Bits per key</th>
<th>Hash functions</th>
<th>False positive rate</th>
</tr>
</thead>
<tbody><tr>
<td>4</td>
<td>3</td>
<td>14.7%</td>
</tr>
<tr>
<td>6</td>
<td>4</td>
<td>5.6%</td>
</tr>
<tr>
<td>8</td>
<td>6</td>
<td>2.2%</td>
</tr>
<tr>
<td><strong>10</strong></td>
<td><strong>7</strong></td>
<td><strong>0.81%</strong></td>
</tr>
<tr>
<td>12</td>
<td>8</td>
<td>0.32%</td>
</tr>
<tr>
<td>16</td>
<td>11</td>
<td>0.05%</td>
</tr>
<tr>
<td>20</td>
<td>14</td>
<td>0.007%</td>
</tr>
</tbody></table>
<p>Two rules come out of this table, and they're the only ones you need to remember:</p>
<blockquote>
<p><strong>10 bits per key ≈ 1% false positives.Every extra ~5 bits per key cuts false positives by 10×.</strong></p>
</blockquote>
<p>If you want it as one formula, with b = bits per key:</p>
<p>$$\text{false positive rate} \approx 0.6185^{b}$$</p>
<p>That's not a fitted curve. Both rules fall out of it, and it matched every measured row above to within a few percent.</p>
<p>That's why 10 bits per key is the standard RocksDB setting: it's the knee of the curve. Going from 10 to 20 bits doubles the memory to save less than 1% of reads.</p>
<h3>How many hash functions? Aim for half full</h3>
<p>For a fixed 10 bits per key, I varied the number of hash functions:</p>
<table>
<thead>
<tr>
<th>Hash functions</th>
<th>Bits set to 1</th>
<th>False positive rate</th>
</tr>
</thead>
<tbody><tr>
<td>1</td>
<td>10%</td>
<td>9.5%</td>
</tr>
<tr>
<td>3</td>
<td>26%</td>
<td>1.7%</td>
</tr>
<tr>
<td>5</td>
<td>39%</td>
<td>0.95%</td>
</tr>
<tr>
<td><strong>7</strong></td>
<td><strong>50%</strong></td>
<td><strong>0.83%</strong></td>
</tr>
<tr>
<td>10</td>
<td>63%</td>
<td>1.0%</td>
</tr>
<tr>
<td>16</td>
<td>80%</td>
<td>2.7%</td>
</tr>
</tbody></table>
<p>Too few hashes, and each lookup checks too few bits, so a random key passes easily. Too many, and the array fills up with 1s, so every check passes. The sweet spot is exactly where <strong>half the bits are 1</strong>: each probe is a coin flip, and a missing key has to win every flip. That works out to about <strong>0.7 × bits per key</strong> hash functions (7 for 10 bits).</p>
<hr />
<h2>4. Same memory, smarter split</h2>
<p>Here's where it gets interesting. Bloom filters cost real memory. At 10 bits per key, <strong>1 billion keys need 1.25 GB of RAM</strong> per node, just for filters. Memory is the budget, so the question becomes: are we spending it well?</p>
<p>RocksDB, by default, gives <strong>every level the same bits per key</strong>. Let's look at what that buys in a 4-level tree where each level is 10× bigger than the one above:</p>
<table>
<thead>
<tr>
<th>Level</th>
<th>Share of keys</th>
<th>Share of filter memory</th>
<th>False positive rate</th>
</tr>
</thead>
<tbody><tr>
<td>L1</td>
<td>0.09%</td>
<td>0.09%</td>
<td>0.8%</td>
</tr>
<tr>
<td>L2</td>
<td>0.9%</td>
<td>0.9%</td>
<td>0.8%</td>
</tr>
<tr>
<td>L3</td>
<td>9%</td>
<td>9%</td>
<td>0.8%</td>
</tr>
<tr>
<td>L4</td>
<td>90%</td>
<td><strong>90%</strong></td>
<td>0.8%</td>
</tr>
</tbody></table>
<p>A missing key gets checked against all four levels, so the wasted reads <strong>add up</strong>: 4 × 0.82% ≈ <strong>3.3% of a disk read</strong> per lookup.</p>
<p>Now notice the imbalance. L4 eats 90% of the memory but contributes only a quarter of the wasted reads. L1 contributes the same quarter for 0.09% of the memory.</p>
<p><strong>Memory is priced per key, so a bit per key is 1,000× cheaper on L1 than on L4.</strong> That suggests a trade: take a tiny bit of memory from the huge last level, and give it to the small levels, where it buys a lot.</p>
<p>That's exactly what the <strong>Monkey</strong> paper (Dayan, Athanassoulis and Idreos, SIGMOD 2017) worked out. The best split makes each level's false positive rate <strong>proportional to its size</strong>: the big level keeps a slightly higher rate, and the small levels get very low ones. I ran both splits on real filters, with the same total memory, and 1 million lookups for missing keys:</p>
<table>
<thead>
<tr>
<th>Level</th>
<th>Uniform bits/key</th>
<th>Tuned bits/key</th>
<th>Tuned false positive rate</th>
</tr>
</thead>
<tbody><tr>
<td>L1</td>
<td>10</td>
<td>23.9</td>
<td>0.001%</td>
</tr>
<tr>
<td>L2</td>
<td>10</td>
<td>19.1</td>
<td>0.01%</td>
</tr>
<tr>
<td>L3</td>
<td>10</td>
<td>14.3</td>
<td>0.11%</td>
</tr>
<tr>
<td>L4</td>
<td>10</td>
<td><strong>9.5</strong></td>
<td>1.05%</td>
</tr>
<tr>
<td><strong>Wasted reads per missing key</strong></td>
<td><strong>0.0327</strong></td>
<td></td>
<td><strong>0.0117</strong></td>
</tr>
</tbody></table>
<p>L4 gave up just <strong>half a bit per key</strong> (10 → 9.5). Its false positive rate barely moved (0.8% → 1.05%). But because L4 is so large, that half bit paid for <strong>4 to 14 extra bits per key</strong> on every level above it, and those levels' false positives practically vanished.</p>
<p>Same RAM. <strong>2.8× fewer wasted disk reads.</strong></p>
<p>And it gets better as the tree grows. Every new level adds another 0.8% of waste under the uniform split. Under the tuned split, new levels are small and cheap to protect, so the total stays flat:</p>
<table>
<thead>
<tr>
<th>Levels</th>
<th>Uniform (wasted reads per lookup)</th>
<th>Tuned</th>
</tr>
</thead>
<tbody><tr>
<td>3</td>
<td>0.025</td>
<td>0.012</td>
</tr>
<tr>
<td>5</td>
<td>0.041</td>
<td>0.012</td>
</tr>
<tr>
<td>7</td>
<td>0.057</td>
<td>0.012</td>
</tr>
</tbody></table>
<blockquote>
<p><strong>With uniform bits per key, the cost of "not found" grows with the number of levels. With a size-proportional split, it doesn't.</strong></p>
</blockquote>
<hr />
<h2>5. What production engines actually do</h2>
<p><strong>RocksDB</strong></p>
<ul>
<li><strong>10 bits per key</strong> is the usual starting point (<code>NewBloomFilterPolicy(10)</code>), giving about 1% false positives.</li>
<li>Since <code>format_version=5</code> (the default in modern RocksDB), its Bloom filter keeps all of a key's probes <strong>inside one 64-byte CPU cache line</strong>. A lookup costs one cache miss instead of up to seven, at the price of a slightly higher false positive rate.</li>
<li><code>optimize_filters_for_hits</code> skips building filters for the last level entirely. In our 4-level tree that saves <strong>90% of filter memory</strong>. It's a great trade <em>when lookups almost always find their key</em>: the key is in the last level anyway, so its filter would only ever say "maybe". It's a terrible trade for the dedup pipeline. Every missing key would now pay a full disk read at the last level: wasted reads go from 0.033 to 1.03 per lookup, <strong>about 30× worse</strong>. Know your hit ratio before you flip this switch.</li>
<li><strong>Ribbon filters</strong> (<code>NewRibbonFilterPolicy</code>) are a drop-in alternative that saves about <strong>30% of filter memory</strong> for the same false positive rate, but uses 3–4× more CPU, mostly while building the filter. Filters for the lower levels are built in background compaction and then live for a long time, so the common setup is a hybrid: fast Bloom filters for freshly flushed files, Ribbon for the levels below.</li>
<li>RocksDB uses the same bits per key on every level by default, so the tuned split from section 4 isn't built in. Its filter policy API is told which level a file is being built for, though, so you can implement the split yourself.</li>
</ul>
<p><strong>Cassandra</strong></p>
<p>Cassandra sets a false positive target per table with <code>bloom_filter_fp_chance</code>, and the default depends on the compaction strategy: <strong>0.01 for size-tiered, 0.1 for leveled</strong>. That's section 4's lesson in a config default. A read under leveled compaction touches few SSTables, so each one can afford a looser filter. Size-tiered compaction leaves many overlapping SSTables per read, and every one of them adds its false positives to the total. Cassandra's docs also warn that memory grows non-linearly as you push the target lower, which is the same knee you saw in section 3.</p>
<p><strong>Watch it in production.</strong> Don't guess your false positive rate; measure it. RocksDB exposes it through the <code>BLOOM_FILTER_USEFUL</code>, <code>BLOOM_FILTER_FULL_POSITIVE</code> and <code>BLOOM_FILTER_FULL_TRUE_POSITIVE</code> statistics. Cassandra reports it per table in <code>nodetool tablestats</code>, alongside the filter's memory use.</p>
<hr />
<h2>6. What a Bloom filter can't do</h2>
<ul>
<li><strong>It doesn't help range scans.</strong> "Give me all events between 10:00 and 10:05" can't be answered by hashing one key. RocksDB's partial answer is a <strong>prefix Bloom filter</strong>: with a prefix extractor configured, it can skip files for scans like "all keys starting with <code>user:42:</code>".</li>
<li><strong>It doesn't make hits cheaper.</strong> A key that exists still costs one real read. The filter only removes the <em>wasted</em> reads before it.</li>
<li><strong>It needs to stay in memory.</strong> If filters get evicted from the block cache, checking a filter becomes a disk read itself, and the whole point is lost. This is why filter memory is the budget everything in section 4 is optimising.</li>
</ul>
<hr />
<h2>The short version</h2>
<ol>
<li>In an LSM tree, a key that doesn't exist has to be checked in <strong>every</strong> level and every L0 file. Without help, "not found" costs one disk read per place.</li>
<li>A Bloom filter per SSTable answers "definitely not here" from memory. It never misses a real key; it sometimes says "maybe" to a missing one.</li>
<li><strong>10 bits per key ≈ 1% false positives</strong>, and every ~5 more bits cut that by 10×. Use about 0.7 × bits per key hash functions, which leaves the filter half full.</li>
<li>Giving every level the same bits per key wastes memory on the huge last level. A <strong>size-proportional split</strong> of the same memory cut wasted reads <strong>2.8×</strong> in our 4-level test, and keeps the cost flat as the tree grows.</li>
<li>In production: know your hit ratio before using <code>optimize_filters_for_hits</code>, consider Ribbon filters to save memory, and measure the real false positive rate.</li>
</ol>
<hr />
<h2>What's next</h2>
<p>This is part 2 of <strong>LSM trees from first principles</strong>. Next up: <strong>compaction strategies</strong>, leveled vs tiered, and how one dial trades write amplification against read cost and disk space.</p>
<p><strong>Code for this article:</strong></p>
<ul>
<li><a href="https://github.com/dev64-kartik/storage-engine-articles/blob/main/simulations/02-bloom-filters/bloom_sim.py"><code>bloom_sim.py</code></a>: real Bloom filters, the bits-per-key and hash-count sweeps, and the uniform vs tuned split across LSM levels</li>
</ul>
<p><strong>Further reading</strong></p>
<ul>
<li>Bloom, <em>Space/Time Trade-offs in Hash Coding with Allowable Errors</em>, Communications of the ACM, 1970</li>
<li>Dayan, Athanassoulis, Idreos, <em>Monkey: Optimal Navigable Key-Value Store</em>, SIGMOD 2017</li>
<li>Dillinger, Walzer, <em>Ribbon filter: practically smaller than Bloom and Xor</em>, 2021</li>
<li>RocksDB blog, <em>Ribbon Filter</em>, 2021</li>
<li>Apache Cassandra docs, <em>Bloom Filters</em></li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Why LSM Trees Exist: The Disk Math Behind Every Write-Heavy Database]]></title><description><![CDATA[Deriving the log-structured merge tree from one constraint: small random writes are expensive.]]></description><link>https://kartikpatel.hashnode.dev/why-lsm-trees-exist</link><guid isPermaLink="true">https://kartikpatel.hashnode.dev/why-lsm-trees-exist</guid><category><![CDATA[Databases]]></category><category><![CDATA[System Design]]></category><category><![CDATA[distributed systems]]></category><category><![CDATA[backend]]></category><category><![CDATA[data structures]]></category><category><![CDATA[storage]]></category><dc:creator><![CDATA[Kartik Patel]]></dc:creator><pubDate>Tue, 01 Dec 2026 16:00:54 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6b0eb80d6182b3fdea5e8bf5/54fa438d-d963-49de-8282-cd23590eff9e.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>If you've ever put a random UUID primary key on a busy MySQL table, you've probably seen this graph.</p>
<p>For weeks, insert latency is flat and boring. Then one day the p99 starts climbing. Nothing changed in the code. Traffic didn't spike. Disk utilisation is pinned at 100%, but the amount of data you're inserting per second is tiny: a few megabytes.</p>
<p>The table didn't get slower because it got bigger. It got slower because it got <strong>bigger than memory</strong>, and from that moment every insert started costing a random disk read and a random disk write.</p>
<p>This is the problem the log-structured merge tree (LSM tree) was invented to solve. In this article we won't just describe an LSM tree. We'll <strong>derive</strong> it: start from what a disk actually charges you for, and arrive at the LSM design one forced step at a time. By the end you'll know why RocksDB, Cassandra, ScyllaDB, HBase, CockroachDB's Pebble and Kafka Streams' state stores all look the way they do, and when you should <em>not</em> use one.</p>
<p>Everything here is backed by two small Python scripts you can run yourself (links at the end).</p>
<hr />
<h2>1. What a disk actually charges you for</h2>
<h3>Spinning disks: you pay for the arm</h3>
<p>A hard disk is a spinning platter with an arm that moves across it. To read or write a random location, two slow mechanical things happen:</p>
<ol>
<li><strong>Seek.</strong> The arm moves to the right track: about 4–9 ms.</li>
<li><strong>Rotation.</strong> You wait for the right sector to spin under the head. At 7,200 rpm one rotation takes \(60/7200 = 8.33\) ms, so on average you wait half of that: 4.17 ms.</li>
</ol>
<p>Add them up and a random I/O costs <strong>roughly 10 ms</strong>. That gives the number every storage engineer remembers:</p>
<blockquote>
<p><strong>A spinning disk does about 100 random I/Os per second.</strong></p>
</blockquote>
<p>Now compare two ways of writing data:</p>
<ul>
<li><strong>Random 16 KB writes:</strong> \(100 \times 16\text{ KB} \approx 1.6\) MB/s</li>
<li><strong>Sequential writes:</strong> the arm stays put and the platter streams data at about 200 MB/s</li>
</ul>
<p>That is a gap of more than <strong>100×</strong>, for the same disk, the same bytes. The only difference is <em>where</em> the bytes go.</p>
<h3>SSDs: no arm, but the gap didn't disappear</h3>
<p>"That's a 1990s problem," you might say. "We run on NVMe now." Partly true. An SSD has no moving parts, so the seek penalty is gone. But three costs remain.</p>
<p><strong>1. You can't write less than a page.</strong> Flash and databases both work in pages (4–16 KB). Changing a 200-byte row still means writing the whole page.</p>
<p><strong>2. You can't overwrite in place.</strong> Flash can only be <em>erased</em> in big blocks (often several MB). So the SSD's firmware writes your new page somewhere fresh and marks the old one stale. Later, garbage collection copies the still-live pages out of a block so it can erase it. Small random writes scatter live and dead pages across every block, so the drive ends up copying a lot. Large sequential writes fill whole blocks that later die together (when a file is deleted), so there's almost nothing to copy.</p>
<p><strong>3. Every I/O has a fixed overhead.</strong> System call, queueing, the device's own bookkeeping. Fewer, bigger I/Os amortise it.</p>
<p>I measured the third point on a cloud VM's virtual SSD, writing the same 64 MB with different I/O sizes (<code>O_DIRECT</code>, so the OS cache can't help):</p>
<table>
<thead>
<tr>
<th>I/O size</th>
<th>Random MB/s</th>
<th>Sequential MB/s</th>
<th>I/Os needed for 64 MB</th>
</tr>
</thead>
<tbody><tr>
<td>16 KB</td>
<td>227</td>
<td>273</td>
<td>4,096</td>
</tr>
<tr>
<td>64 KB</td>
<td>468</td>
<td>566</td>
<td>1,024</td>
</tr>
<tr>
<td>256 KB</td>
<td>724</td>
<td>775</td>
<td>256</td>
</tr>
<tr>
<td>1 MB</td>
<td>795</td>
<td>637</td>
<td>64</td>
</tr>
<tr>
<td>4 MB</td>
<td>703</td>
<td>745</td>
<td>16</td>
</tr>
</tbody></table>
<p>Look at the columns, not the rows. Random vs sequential barely matters on this device. <strong>I/O size</strong> matters about 3×.</p>
<p>So here's the modern version of the rule:</p>
<blockquote>
<p><strong>On SSDs, "sequential" really means "large". The device rewards you for writing big, contiguous chunks it can later throw away whole.</strong></p>
</blockquote>
<p>Keep that sentence in mind. The entire LSM design follows from it.</p>
<hr />
<h2>2. Where a B+tree pays the bill</h2>
<p>A B+tree (InnoDB, PostgreSQL indexes, most relational databases) is an <strong>update-in-place</strong> structure. Every key has exactly one home: a specific leaf page. To insert a row you:</p>
<ol>
<li>Find the leaf page that owns the key.</li>
<li>If it's not in the buffer pool (RAM), <strong>read it from disk</strong>: one random read.</li>
<li>Modify it in memory. It's now dirty.</li>
<li>Eventually, when the buffer pool needs room, <strong>write the whole page back</strong>: one random write.</li>
</ol>
<p>While the table fits in memory, steps 2 and 4 rarely happen, and life is great. That's the flat part of the graph.</p>
<p>Now let the table grow past memory. Say the table has \(\mathit{S}\) leaf pages and the buffer pool holds \(\mathit{B}\) of them. With random keys, each insert hits a random page, and the chance it's already cached is \(B/S\). So the chance it costs a disk trip is \(1 - B/S\).</p>
<p>Each of those trips eventually writes back a full page of \(\mathit{P}\) bytes, to store one row of \(\mathit{r}\) bytes. That gives the B+tree's write amplification for random inserts:</p>
<p>$$\text{WA}_{\text{B+tree}} \;\approx\; \left(1 - \frac{B}{S}\right) \cdot \frac{P}{r}$$</p>
<p>Plug in real numbers: 16 KB InnoDB pages, 200-byte rows, buffer pool holding 5% of the table:</p>
<p>$$\text{WA} \approx 0.95 \times \frac{16384}{200} \approx 78$$</p>
<p><strong>Every byte you insert costs about 78 bytes of disk writes</strong>, plus one random read and one random write per insert. And that's before page splits, and before InnoDB's doublewrite buffer, which writes every dirty page twice to protect against torn pages.</p>
<p>I simulated exactly this: a B+tree with 400,000 leaf pages, an LRU buffer pool of 20,000 pages, and 2 million random 200-byte inserts.</p>
<pre><code class="language-plaintext">B+tree, random keys:    1,900,665 random page reads, 1,900,665 random page writes
   bytes written per byte inserted:   77.9x   | random write I/Os per insert: 0.950
</code></pre>
<p>The formula predicted 0.95 and 78×. The simulation measured 0.950 and 77.9×.</p>
<h3>Why auto-increment keys "fix" it</h3>
<p>Run the same simulation with <strong>monotonic keys</strong> (auto-increment IDs, timestamps):</p>
<pre><code class="language-plaintext">B+tree, monotonic keys:         0 random page reads,    24,692 random page writes
   bytes written per byte inserted:    1.0x   | random write I/Os per insert: 0.012
</code></pre>
<p>Every insert goes to the rightmost leaf. That one page stays hot in memory, fills up with 81 rows, and gets written once. Write amplification drops from 78× to 1×.</p>
<p>This is the real reason behind the classic advice "don't use UUIDv4 as a MySQL primary key." It's not about the 16 bytes. It's that random keys turn every insert into random I/O once the table outgrows RAM. (It's also why UUIDv7 and ULIDs, which start with a timestamp, became popular.)</p>
<p>But you don't always get to choose your keys. A secondary index on <code>user_id</code>, a messages table keyed by <code>(channel_id, message_id)</code>, an events table keyed by <code>(item_id, ts)</code>: these are random inserts by nature. You need a structure that doesn't care.</p>
<hr />
<h2>3. Deriving the LSM tree, one step at a time</h2>
<p>Let's design a storage engine with one rule:</p>
<blockquote>
<p><strong>Never do a small random write.</strong></p>
</blockquote>
<h3>Step 1: Just append</h3>
<p>The simplest structure that obeys the rule is a log. Every write goes to the end of a file. Writes are perfect: purely sequential, write amplification of 1.</p>
<p>Reads are terrible. To find a key you scan the whole file: \(\mathit{O}(n)\).</p>
<h3>Step 2: Sort in memory, flush in bulk</h3>
<p>We need the data on disk to be <strong>sorted</strong>, so reads can binary search. But sorting on disk means moving things around, which means random writes.</p>
<p>So sort in <strong>memory</strong> instead. Keep an in-memory sorted structure (the <strong>memtable</strong>; usually a skip list). When it reaches a size limit (say 64 MB), write it out in one go as an immutable, sorted file: a <strong>Sorted String Table</strong>, or <strong>SSTable</strong>.</p>
<p>That flush is one long sequential write.</p>
<p>Memory is volatile, so to survive a crash every write also goes to an append-only <strong>write-ahead log</strong> (WAL) first. That's sequential too. Once the memtable is flushed, its WAL can be deleted.</p>
<p>Now we have a write path made entirely of sequential writes:</p>
<pre><code class="language-plaintext">write(k, v)
   │
   ├──► WAL (append, sequential)          ← durability
   │
   └──► memtable (sorted, in RAM)
            │  full?
            ▼
        SSTable file (sorted, immutable, written once, sequentially)
</code></pre>
<h3>Step 3: Too many files, so merge them</h3>
<p>After a day of traffic you have hundreds of SSTables. Each is sorted, but a read might have to check every one of them, newest first, because a key could live in any of them.</p>
<p>The fix: periodically <strong>merge</strong> SSTables into fewer, bigger ones. Merging sorted files is a streaming operation: read several sorted inputs sequentially, write one sorted output sequentially. Like the merge step of merge sort. Old versions of a key and deleted keys get dropped on the way. This is <strong>compaction</strong>.</p>
<p>Compaction obeys our rule. It reads big chunks and writes big chunks. No small random writes anywhere.</p>
<h3>Step 4: Don't merge everything every time</h3>
<p>The naive version, "merge everything into one big file after each flush", rewrites the whole database every flush. With \(\mathit{N}\) bytes of data and a memtable of \(\mathit{M}\) bytes, each flush costs \(\mathit{O}(N)\). That's far too much.</p>
<p>The fix is to arrange files in <strong>levels</strong> that grow geometrically by a factor \(\mathit{T}\) (typically 10):</p>
<pre><code class="language-plaintext">memtable   64 MB      (RAM)
L0         a few freshly flushed SSTables
L1         ~256 MB    ┐
L2         ~2.5 GB    │ each level ~T = 10× bigger than the one above,
L3         ~25 GB     │ and holds one sorted run, split into files
L4         ~250 GB    ┘
</code></pre>
<p>When a level gets too full, pick one file from it and merge it into the overlapping files of the next level down. Data trickles down level by level.</p>
<p>How many levels do we need? Each level is \(\mathit{T}\) times bigger, so:</p>
<p>$$L \;\approx\; \log_T \frac{N}{M}$$</p>
<p>With 250 GB of data, a 64 MB memtable and \(T = 10\), that's \(\log_{10}(4000) \approx 3.6\), so 4 levels.</p>
<p>And what's the write cost? Each byte is written once at flush, and then again every time it moves down a level. Moving a file into a level that's \(\mathit{T}\) times bigger rewrites up to \(\mathit{T}\) times as much overlapping data. So:</p>
<p>$$\text{WA}_{\text{LSM}} \;\lesssim\; 1 + T \cdot L$$</p>
<p>(Both engines also write every byte to a WAL once, so I'm leaving that out of the comparison.)</p>
<p>That's an upper bound. Real levels aren't always full, so the actual number is lower. My simulation of a leveled LSM with \(T = 10\) on the same 2 million random inserts measured:</p>
<pre><code class="language-plaintext">LSM (leveled, T=10), random keys:
   bytes written per byte inserted:   15.5x   | 1 MB sequential write I/Os per insert: 0.0030
</code></pre>
<p>That's it. That's the LSM tree. We didn't pick it from a menu. Every piece was forced by the rule "never do a small random write":</p>
<table>
<thead>
<tr>
<th>Piece</th>
<th>Why it exists</th>
</tr>
</thead>
<tbody><tr>
<td>WAL</td>
<td>Memory is volatile, and appending is the only cheap durable write</td>
</tr>
<tr>
<td>Memtable</td>
<td>Sorting must happen somewhere that random access is free: RAM</td>
</tr>
<tr>
<td>SSTable</td>
<td>Flushing a sorted memtable is one big sequential write</td>
</tr>
<tr>
<td>Compaction</td>
<td>Many files make reads slow; merging sorted files is sequential</td>
</tr>
<tr>
<td>Levels with ratio \(\mathit{T}\)</td>
<td>Merging everything every time costs \(\mathit{O}(N)\) per flush</td>
</tr>
</tbody></table>
<hr />
<h2>4. Putting the two side by side</h2>
<p>Same workload, 2 million random inserts of 200 bytes:</p>
<table>
<thead>
<tr>
<th></th>
<th>B+tree</th>
<th>LSM tree (leveled)</th>
</tr>
</thead>
<tbody><tr>
<td>Bytes written per byte inserted</td>
<td><strong>77.9×</strong></td>
<td><strong>15.5×</strong></td>
</tr>
<tr>
<td>Shape of each write</td>
<td>16 KB, random</td>
<td>1 MB+, sequential</td>
</tr>
<tr>
<td>Write I/Os per insert</td>
<td>0.95</td>
<td>0.003</td>
</tr>
<tr>
<td>Random reads per insert</td>
<td>0.95</td>
<td>0</td>
</tr>
</tbody></table>
<p>Notice something surprising. <strong>The LSM tree still rewrites every byte 15 times.</strong> It is not "write once". What it does is turn ~2 million small random I/Os into ~6,000 large sequential ones.</p>
<p>That's the core trade:</p>
<blockquote>
<p><strong>An LSM tree writes more bytes than you'd think, but in far fewer, far larger I/Os. A B+tree writes each update in place, but each one is a small random I/O on a full page.</strong></p>
</blockquote>
<h3>What that means on real hardware</h3>
<p><strong>On a spinning disk</strong> (10 ms per random I/O, 200 MB/s sequential), the same 2 million inserts take:</p>
<ul>
<li>B+tree: about <strong>10.6 hours</strong>, roughly 53 inserts per second</li>
<li>LSM: about <strong>1 minute</strong>, roughly 34,000 inserts per second</li>
</ul>
<p>That 600× gap is exactly why the LSM tree was invented in the first place. Patrick O'Neil's 1996 paper was motivated by a bank's <strong>history table</strong>: every transaction appends a 50-byte row, and indexing it by account ID with a B-tree roughly doubled the I/O cost of the whole transaction. On 1990s disks, disk arms, not capacity, were the expensive resource.</p>
<p><strong>On an SSD</strong>, IOPS are plentiful, so the fight moves to <strong>bytes written</strong>, because flash wears out. Take a write-heavy node handling 5,000 random inserts per second of 200-byte rows (the kind of event stream any recommendations or activity-feed system produces). That's only 1 MB/s of real data.</p>
<ul>
<li>B+tree: \(0.95 \times 5000 \times 16\text{ KB} \approx 78\) MB/s of page writes → <strong>6.7 TB per day</strong></li>
<li>LSM: \(15.5 \times 1\text{ MB/s} \approx 15.5\) MB/s → <strong>1.3 TB per day</strong></li>
</ul>
<p>On a 3.84 TB drive rated for one full drive write per day, the B+tree burns through its endurance budget <strong>1.7× faster than allowed</strong>. The LSM uses about a third of it. Plus the B+tree pays a random read for nearly every insert, competing with your real read traffic.</p>
<p>This is not just a thought experiment:</p>
<ul>
<li><strong>Facebook</strong> moved its main social-graph database (UDB) from InnoDB to MyRocks, MySQL on top of RocksDB. The tier was limited by flash space, and after the migration they reported using <strong>half the storage</strong> of compressed InnoDB. Their 2020 VLDB paper reports instance sizes <strong>62.3% smaller</strong> and fewer I/O operations than InnoDB.</li>
<li><strong>Discord</strong> stores trillions of messages in Cassandra-family databases (first Cassandra, now ScyllaDB). Both are LSM-based. Chat is the textbook LSM workload: a firehose of small inserts that are rarely updated.</li>
<li><strong>Kafka Streams</strong> keeps its local state stores in RocksDB, and <strong>CockroachDB</strong> built Pebble, its own LSM engine. When you need an embedded engine that ingests fast, the default answer today is an LSM.</li>
</ul>
<hr />
<h2>5. There's no free lunch: what the LSM tree gives up</h2>
<p>We optimised the write path. The costs moved somewhere else.</p>
<p><strong>1. Reads got more expensive.</strong> A key can now be in the memtable, in any L0 file, or in any level. A naive point lookup checks each place in turn, and a lookup for a key that <em>doesn't exist</em> has to check all of them. The fixes are <strong>Bloom filters</strong> (skip a file without touching disk) and per-file indexes. That's the next article.</p>
<p><strong>2. Space amplification.</strong> Old versions of a key and deleted keys (tombstones) sit on disk until compaction reaches them. Leveled compaction keeps this to about 10% extra; other compaction styles trade more space for less write amplification.</p>
<p><strong>3. Compaction is background work that can fall behind.</strong> If writes come in faster than compaction can merge, L0 fills up, reads slow down, and RocksDB eventually <strong>stalls writes</strong> on purpose to let compaction catch up. If you run an LSM in production, "pending compaction bytes" and write stalls are the metrics you'll learn to watch.</p>
<p><strong>4. Write amplification didn't disappear.</strong> 15× is a lot better than 78×, but it isn't 1×. Tuning that number (leveled vs tiered compaction, the size ratio \(\mathit{T}\)) is a whole article of its own.</p>
<h3>So when does a B+tree still win?</h3>
<ul>
<li><strong>Read-heavy workloads</strong> where predictable single-I/O point reads matter more than ingest speed.</li>
<li><strong>Monotonic keys.</strong> As we saw, a B+tree with auto-increment keys writes about 1×. Hard to beat.</li>
<li><strong>The working set fits in memory.</strong> If \(B/S \approx 1\), the B+tree's write amplification formula goes to nearly zero.</li>
<li><strong>Heavy in-place updates of the same hot rows,</strong> which a buffer pool absorbs well.</li>
</ul>
<hr />
<h2>The short version</h2>
<ol>
<li>Disks charge per I/O, not per byte. On HDDs that's the arm; on SSDs it's page size, erase blocks and per-I/O overhead. <strong>Small random writes are the most expensive thing you can ask for.</strong></li>
<li>A B+tree with random keys and a table bigger than RAM pays roughly one random read and one random full-page write per insert: write amplification \(\approx (1 - B/S) \cdot P/r\), about <strong>78×</strong> for 200-byte rows on 16 KB pages.</li>
<li>An LSM tree refuses to do small random writes: buffer sorted in memory, flush sequentially, merge in the background across levels that grow by \(\mathit{T}\). It still rewrites each byte about \(T \cdot L\) times at most, but in <strong>big sequential chunks</strong>.</li>
<li>The price is paid on reads (fixed with Bloom filters), space (old versions), and background compaction that has to keep up.</li>
</ol>
<hr />
<h2>What's next</h2>
<p>This is the first article in the series <strong>LSM trees from first principles</strong>. Next up: <strong>Bloom filters</strong>, and how to work out exactly how many bits per key to spend on each level, which turns out to have a surprisingly elegant answer.</p>
<p><strong>Code for this article</strong> (run them yourself):</p>
<ul>
<li><a href="https://github.com/dev64-kartik/storage-engine-articles/blob/main/simulations/01-why-lsm/write_cost_sim.py"><code>write_cost_sim.py</code></a>: B+tree buffer pool vs leveled LSM, same workload</li>
<li><a href="https://github.com/dev64-kartik/storage-engine-articles/blob/main/simulations/01-why-lsm/io_size_bench.py"><code>io_size_bench.py</code></a>: measure how I/O size affects throughput on your own disk</li>
</ul>
<p><strong>Further reading</strong></p>
<ul>
<li>O'Neil, Cheng, Gawlick, O'Neil, <em>The Log-Structured Merge-Tree (LSM-Tree)</em>, Acta Informatica, 1996</li>
<li>Matsunobu, Dong, Lee, <em>MyRocks: LSM-Tree Database Storage Engine Serving Facebook's Social Graph</em>, VLDB 2020</li>
<li>Discord Engineering, <em>How Discord Stores Trillions of Messages</em>, 2023</li>
</ul>
]]></content:encoded></item></channel></rss>