System Design Part 3 Storage basics

B-Tree vs LSM-Tree: In-Place Updates vs Append-Only, and the Write, Read, and Space Amplification Trade-offs

Bill.Lin 25 min read

System Design series Part 3-3 | Previous: Indexes and B+Trees | Next: Transactions and Isolation Levels | Series map

Read first: Part 3-2 Indexes and B+Trees.

Scenario and problem

The SQL vs NoSQL post put product browsing history in a partitioned MySQL table: 100 million rows a day, about 5,800 a second at peak, which one server can handle. It also left a note: when the volume grows 10x, switch to something else.

Now a new version of the app adds “Recommended for you”, and view events grow to 1 billion a day, 60,000 a second at peak. Each one is still about 60 bytes:

Calculation (java WriteNapkin.java)
java
public class WriteNapkin {
    public static void main(String[] args) {
        long perDay = 1_000_000_000L;            // 1 billion a day after 10x growth
        long peak = 60_000;                      // rows per second at peak
        int rowBytes = 60;
        int pageBytes = 16 * 1024;
        System.out.printf("Data per day: %,.0f GB; kept for 90 days: %,.1f TB%n",
                perDay * rowBytes / 1e9, perDay * rowBytes * 90 / 1e12);
        System.out.printf("Raw data at peak: %,.1f MB/s%n", peak * rowBytes / 1e6);
        System.out.printf("B+Tree worst case (every row on a different page): %,d random page reads/s + %,.0f MB/s of page writes (doublewrite not counted)%n",
                peak, peak * (double) pageBytes / 1e6);
        for (int amp : new int[] {10, 30}) {
            System.out.printf("LSM with %dx write amplification: %,.0f MB/s, almost all sequential writes%n", amp, peak * rowBytes * (double) amp / 1e6);
        }
    }
}
text
Data per day: 60 GB; kept for 90 days: 5.4 TB
Raw data at peak: 3.6 MB/s
B+Tree worst case (every row on a different page): 60,000 random page reads/s + 983 MB/s of page writes (doublewrite not counted)
LSM with 10x write amplification: 36 MB/s, almost all sequential writes
LSM with 30x write amplification: 108 MB/s, almost all sequential writes

The raw data is only 3.6 MB a second; the problem is how a B+Tree writes. This table’s primary key is (member_id, viewed_at, product_id), so the 60,000 rows of one second are spread across the pages of hundreds of thousands of different members. When a page is not in the buffer pool, every row first has to read in a 16 KB page and change a few dozen bytes, and later the whole page is written back. The buffer pool merges several changes to the same page, so in practice it is not this bad; but once the data grows to terabytes and the hot pages no longer fit in memory, you get closer and closer to this worst case.

Switching to an increasing primary key concentrates inserts at the right edge of the tree, but then “the products a member viewed recently” needs a secondary index on (member_id, viewed_at), and that secondary index takes random inserts just the same. The problem only moves somewhere else (see the Index post).

After writes grow 10x1 / 5
After writes grow 10xView eventsMySQL B+TreeDiskLSM-TreeView eventsMySQL B+Tree5,800 rows/sOne server copesView eventsMySQL B+Tree60,000 rows/sRaw data only 3.6 MB/sMySQL B+TreeDiskPage read+writeWorst: 60k random reads/sView eventsMySQL B+TreeIncreasing PKIndex inserts still randomView eventsLSM-TreeDiskMemory firstBatch, in order36–108 MB/s, sequential
  1. Before: 100 million a dayBrowsing history sits in a partitioned MySQL table: 100 million rows a day, about 5,800 a second at peak. One server can handle it.
  2. Growing to 1 billion a dayAfter the recommendation feature launches, view events grow to 1 billion a day, 60,000 a second at peak. Each is about 60 bytes, so the raw data is only 3.6 MB a second.
  3. The problem is how B+Trees writeThe primary key is (member_id, viewed_at, product_id), so the 60,000 rows of one second are spread across the pages of hundreds of thousands of members. When a page is not in memory, every row means reading in a 16 KB page, changing a few dozen bytes, and writing the whole page back; the worst case is 60,000 random reads a second plus 983 MB/s of writes.
  4. Switch to an increasing primary key?With an increasing primary key, inserts concentrate at the right edge of the tree; but "the products a member viewed recently" then needs a secondary index on (member_id, viewed_at), which takes random inserts just the same. The problem only moves somewhere else.
  5. Make writes sequentialAn LSM-Tree first collects writes in memory, then writes them to disk sequentially in batches. Even at 10 to 30x write amplification, that is only 36 to 108 MB of sequential writes a second.

Another family of data structures makes writes sequential by design: the LSM-Tree (Log-Structured Merge-Tree). RocksDB, Cassandra, ScyllaDB, and HBase all belong to this family. This post compares the trade-offs the two make in writes, reads, and space.

The simplest approach and its limits

The fastest way to write is to only append to the end of a file and never modify old data; for reads, a hash table in memory remembers where in the file the latest record for each key is. Bitcask, Riak’s storage engine, is exactly this design:

Implementation (java AppendOnlyStore.java)
java
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.HashMap;
import java.util.Map;

/** The simplest append-only store: every write goes to the end of the file, and an in-memory hash table remembers where each key's latest record is. */
public final class AppendOnlyStore implements AutoCloseable {

    private final FileChannel log;
    private final Map<String, Long> index = new HashMap<>();   // key -> position of the latest record in the file

    public AppendOnlyStore(Path file) throws IOException {
        log = FileChannel.open(file, StandardOpenOption.CREATE, StandardOpenOption.READ, StandardOpenOption.WRITE);
        long offset = 0;
        while (offset < log.size()) {                          // on reopen: replay the whole file from the start to rebuild the index
            Record record = readAt(offset);
            index.put(record.key(), offset);
            offset += record.sizeOnDisk();
        }
    }

    public void put(String key, String value) throws IOException {
        byte[] k = key.getBytes(StandardCharsets.UTF_8);
        byte[] v = value.getBytes(StandardCharsets.UTF_8);
        ByteBuffer buffer = ByteBuffer.allocate(8 + k.length + v.length)
                .putInt(k.length).putInt(v.length).put(k).put(v).flip();
        long offset = log.size();
        log.write(buffer, offset);                             // always write at the end: sequential writes
        log.force(false);                                      // make sure it reaches the storage device, so a crash cannot lose it
        index.put(key, offset);                                // the old record is still in the file, just no longer pointed to
    }

    public String get(String key) throws IOException {
        Long offset = index.get(key);
        return offset == null ? null : readAt(offset).value();
    }

    public long fileSize() throws IOException {
        return log.size();
    }

    private Record readAt(long offset) throws IOException {
        ByteBuffer header = ByteBuffer.allocate(8);
        log.read(header, offset);
        header.flip();
        int keyLength = header.getInt();
        int valueLength = header.getInt();
        ByteBuffer body = ByteBuffer.allocate(keyLength + valueLength);
        log.read(body, offset + 8);
        byte[] bytes = body.array();
        return new Record(new String(bytes, 0, keyLength, StandardCharsets.UTF_8),
                new String(bytes, keyLength, valueLength, StandardCharsets.UTF_8), 8 + keyLength + valueLength);
    }

    private record Record(String key, String value, int sizeOnDisk) {}

    @Override
    public void close() throws IOException {
        log.close();
    }

    public static void main(String[] args) throws IOException {
        Path file = Files.createTempDirectory("append-only-store").resolve("data.log");
        try (AppendOnlyStore store = new AppendOnlyStore(file)) {
            store.put("product:1", "price=100");
            store.put("product:2", "price=250");
            store.put("product:1", "price=80");                // overwrite: append a new record, the old one stays in the file
            System.out.println("File size after 3 writes: " + store.fileSize() + " bytes");
        }
        try (AppendOnlyStore reopened = new AppendOnlyStore(file)) {   // simulate a process restart
            System.out.println("After restart, product:1 = " + reopened.get("product:1"));
            System.out.println("After restart, product:2 = " + reopened.get("product:2"));
            System.out.println("3 records in the file, 1 of them stale; compaction has to reclaim the space");
        }
    }
}
text
File size after 3 writes: 77 bytes
After restart, product:1 = price=80
After restart, product:2 = price=250
3 records in the file, 1 of them stale; compaction has to reclaim the space

The three writes take 77 bytes in total (26 + 26 + 25), and after product:1 is overwritten the old record is still in the file. On restart the whole file is replayed and the index ends up pointing at the latest record, so the read returns price=80.

The upside is obvious: writes are pure sequential I/O, and a read needs a single seek. The limits are just as obvious:

  1. Every key has to fit in memory: the hash table must stay fully resident
  2. No range queries: a hash table has no order, so “a member’s browsing history for November” means scanning the whole file
  3. The file grows forever: old versions stay around forever, so the file has to be split into segments that are merged periodically, dropping stale records (compaction)
  4. A restart replays the whole file: the bigger the file, the slower the startup (Bitcask keeps a separate hint file to speed this up)

The LSM-Tree keeps the append-only way of writing but sorts the file contents by key, which solves the first two problems at once.

Core mechanism

Write path: memory first, then sequential batch writes

flowchart LR
    W[Write] --> WAL["WAL<br/>sequential append, survives crashes"]
    W --> MT["Memtable<br/>sorted structure in memory"]
    MT -- flush when full --> L0["SSTable<br/>sorted by key, never modified once written"]
    L0 -- background compaction --> L1["merged into larger SSTables"]
  1. WAL: first append to the write-ahead log, so a crash loses nothing
  2. Memtable: write into a sorted structure in memory (commonly a skip list). The write is complete at this point, with no need to read any data on disk
  3. Flush: when the memtable is full it becomes read-only and is written out in order, in one batch, as an SSTable (Sorted String Table): a file sorted by key and never modified once written, with a block index and a Bloom filter. Once it is written, the matching WAL can be discarded
  4. Compaction: in the background, SSTables are continuously merged into new SSTables that keep only the latest version of each key, and then the old files are deleted

An update writes a new version, and a delete writes a tombstone (a deletion marker). Neither touches old data; old versions only truly disappear after compaction.

Read path: search from newest to oldest

Take RocksDB’s leveled structure as an example:

flowchart TD
    Q["Read a key"] --> M["1. Memtable"]
    M -- not found --> L0["2. L0 SSTables<br/>key ranges may overlap, so check each one from newest to oldest"]
    L0 -- not found --> L1["3. L1, L2 …<br/>files in one level have non-overlapping key ranges, so at most one file per level"]
    BF["Each SSTable asks its Bloom filter first:<br/>if the answer is 'definitely not here', skip it without reading the disk"]
    L0 -.- BF
    L1 -.- BF
  • The first version you find is the newest; if it is a tombstone, the key has been deleted
  • Bloom filters mean a key that does not exist almost never costs a disk read: a Bloom filter can mistake “not there” for “maybe there”, but never mistakes “there” for “not there”. See the Bloom filter post for how it works
  • Range queries lose out: Bloom filters do not help, so you have to open every sorted run that might cover the range at the same time and merge them as you read
  • The more sorted runs, the slower the reads: keeping the number of sorted runs down is compaction’s main job

Compaction: tiering and leveling

Compaction comes in two main strategies:

  • Tiering (size-tiered): wait until several sorted runs of similar size pile up, then merge them together into a bigger one. Each record is rewritten fewer times, but more sorted runs exist at the same time
  • Leveling (leveled): from L1 down, each level keeps only one sorted run, and data from the level above is merged into it as soon as it comes down. Reads check fewer files and less space is wasted, but the data already in the lower level is rewritten again and again with every merge

Compare the two with a simulation: 2 million writes over 1 million distinct keys (later writes are mostly overwrites); the memtable holds 10,000 entries; tiering merges every time 4 runs pile up; leveling allows at most 4 runs in L0, and each level after that holds 10 times as much as the one above:

Simulation (java -Xmx2g CompactionSimulation.java)
java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.TreeSet;

/**
 * A simplified LSM compaction model: it only counts entries and stores no real values.
 * Each sorted run is a sorted set of distinct keys; a merge keeps only the latest entry for each key.
 */
public class CompactionSimulation {

    static final int MEMTABLE_ENTRIES = 10_000;
    static final int OPERATIONS = 2_000_000;
    static final int DISTINCT_KEYS = 1_000_000;   // writes in the second half mostly overwrite existing keys
    static final int RATIO = 4;                   // tiering: merge once a tier has 4 runs; leveling: at most 4 runs in L0
    static final int LEVEL_GROWTH = 10;           // leveling: each level holds 10 times as much as the one above

    interface Policy {
        void flush(long[] run);
        List<long[]> runs();
    }

    static long written;                          // total entries written to "disk" (flush + compaction)

    public static void main(String[] args) {
        run("Tiering (size-tiered)", new Tiering());
        run("Leveling (leveled)", new Leveling());
    }

    static void run(String name, Policy policy) {
        written = 0;
        Random random = new Random(42);
        TreeSet<Long> memtable = new TreeSet<>();
        TreeSet<Long> live = new TreeSet<>();
        long runSamples = 0;
        long runTotal = 0;
        int runMax = 0;
        for (int i = 0; i < OPERATIONS; i++) {
            long key = random.nextInt(DISTINCT_KEYS);
            memtable.add(key);
            live.add(key);
            if (memtable.size() == MEMTABLE_ENTRIES) {
                long[] run = memtable.stream().mapToLong(Long::longValue).toArray();
                written += run.length;                       // the flush itself writes once
                policy.flush(run);
                memtable.clear();
                int runs = policy.runs().size();             // the most runs one point lookup has to check
                runSamples++;
                runTotal += runs;
                runMax = Math.max(runMax, runs);
            }
        }
        long stored = policy.runs().stream().mapToLong(r -> r.length).sum();
        System.out.printf("%-22s write amplification %4.1fx | sorted runs avg %4.1f, max %2d | space amplification at end %4.2fx%n",
                name, (double) written / OPERATIONS, (double) runTotal / runSamples, runMax,
                (double) stored / live.size());
    }

    static long[] merge(List<long[]> runs) {
        long[] all = runs.stream().flatMapToLong(Arrays::stream).sorted().distinct().toArray();
        written += all.length;                               // the merged result is rewritten in full
        return all;
    }

    /** Once a tier has RATIO runs, merge them into one and put it in the next tier. */
    static final class Tiering implements Policy {
        final List<List<long[]>> tiers = new ArrayList<>();

        public void flush(long[] run) {
            add(0, run);
        }

        void add(int tier, long[] run) {
            while (tiers.size() <= tier) {
                tiers.add(new ArrayList<>());
            }
            tiers.get(tier).add(run);
            if (tiers.get(tier).size() == RATIO) {
                long[] merged = merge(tiers.get(tier));
                tiers.get(tier).clear();
                add(tier + 1, merged);
            }
        }

        public List<long[]> runs() {
            return tiers.stream().flatMap(List::stream).toList();
        }
    }

    /** L0 holds freshly flushed runs; from L1 on each level has one run, and a level over capacity is merged whole into the next. */
    static final class Leveling implements Policy {
        final List<long[]> level0 = new ArrayList<>();
        final List<long[]> levels = new ArrayList<>();       // levels.get(0) is L1

        public void flush(long[] run) {
            level0.add(run);
            if (level0.size() == RATIO) {
                List<long[]> inputs = new ArrayList<>(level0);
                if (!levels.isEmpty()) {
                    inputs.add(levels.get(0));
                }
                level0.clear();
                set(0, merge(inputs));
                cascade(0);
            }
        }

        void cascade(int level) {
            long capacity = (long) MEMTABLE_ENTRIES * RATIO * (long) Math.pow(LEVEL_GROWTH, level);
            if (levels.get(level).length > capacity) {
                List<long[]> inputs = new ArrayList<>(List.of(levels.get(level)));
                if (levels.size() > level + 1) {
                    inputs.add(levels.get(level + 1));
                }
                set(level, new long[0]);
                set(level + 1, merge(inputs));
                cascade(level + 1);
            }
        }

        void set(int level, long[] run) {
            while (levels.size() <= level) {
                levels.add(new long[0]);
            }
            levels.set(level, run);
        }

        public List<long[]> runs() {
            List<long[]> all = new ArrayList<>(level0);
            levels.stream().filter(r -> r.length > 0).forEach(all::add);
            return all;
        }
    }
}
text
Tiering (size-tiered)  write amplification  3.6x | sorted runs avg  5.5, max 11 | space amplification at end 1.71x
Leveling (leveled)     write amplification  6.4x | sorted runs avg  3.6, max  6 | space amplification at end 1.26x
  • Write amplification: how many times each write ends up written to disk in total (the flush plus every rewrite during compaction, WAL not counted). With tiering, data is rewritten roughly once each time it moves down a level; with leveling, every time data from above merges in, the data already in the lower level has to be rewritten along with it
  • Number of sorted runs: how many runs a point lookup has to check in the worst case. Tiering averages 5.5 and peaks at 11, swinging widely with the timing of merges; leveling is much steadier
  • Space amplification: entries on disk ÷ keys actually alive. Tiering has more stale versions that have not been merged away yet

This is a simplified model that only counts entries (it merges whole levels at a time and does not count bytes or compression), so use it only to see the direction. The practical figures in the RocksDB documentation: write amplification is usually 10–30x for leveled and 2–10x for universal (RocksDB’s name for tiering).

B+Tree writes have a WAL too

People often say “every B+Tree write is a random write”. That is not quite right. When an InnoDB transaction commits, it only has to write the redo log (a sequential append) to disk; the modified pages stay in the buffer pool and are written back later in the background. Before being written back, they first go to the doublewrite buffer, so a power loss halfway through a write cannot corrupt a page. So the random writes of a B+Tree are deferred and merged.

The trouble starts when the data is far larger than the buffer pool: every change may first have to read the page in, and modified pages have to be written back before they can collect several changes. That is where the worst case in the scenario comes from.

Trading off the three amplifications

B+Tree (InnoDB) LSM, leveling LSM, tiering
Write amplification Per page: changing a few dozen bytes still writes back a 16 KB page, plus the redo log and doublewrite Medium to high Low
Write I/O pattern Pages scattered everywhere, random writes Sequential Sequential
Point lookups Tree height of 3–4 levels, upper levels almost always in memory At most one file per level, Bloom filters skip the rest More runs to check
Range queries Sequential read along the linked list of leaf nodes Must merge several sorted runs Even more runs to merge
Space amplification Free space reserved in pages, half-full pages after splits Low High; merging the largest run needs temporary extra space
Deletes Marked as deleted first, reclaimed by background purge Write a tombstone, reclaimed only after compaction Same as leveling, reclaimed more slowly
Latency stability Spikes during page splits and heavy flushing Compaction competes for I/O; write stalls when it falls behind Compaction traffic swings even more

Reads, writes, and space cannot all be optimized at once; this observation is called the RUM conjecture (Read, Update, Memory). Picking a storage engine really means deciding which one to sacrifice.

Comparing options

Who uses which

Storage engine Structure Where you usually see it
InnoDB (MySQL), PostgreSQL B+Tree (PostgreSQL’s B-Tree indexes) General OLTP
RocksDB LSM, embedded library MyRocks (a MySQL storage engine), Kafka Streams state stores, TiKV
Cassandra, ScyllaDB, HBase LSM High-volume events and time series

The place Java developers most often run into an LSM without noticing is Kafka Streams: stateful operations (aggregate, join, windowing) are stored in a local RocksDB by default.

Cassandra compaction strategies

Strategy Family Good for
SizeTieredCompactionStrategy (STCS) Tiering Write-heavy workloads; the default when a table does not specify one
LeveledCompactionStrategy (LCS) Leveling Read-heavy workloads, rows that are updated often
TimeWindowCompactionStrategy (TWCS) Grouped by time window Time series, data with a TTL
UnifiedCompactionStrategy (UCS) Tunable between tiering and leveling From Cassandra 5.0; the docs recommend it for most new tables

In Java

1. Before switching databases

First make sure you have done the cheap optimizations:

  • Batch writes (rewriteBatchedStatements, see the SQL vs NoSQL post)
  • Fewer secondary indexes, no random primary keys (see the Index post)
  • Partition by date, and remove expired data with DROP PARTITION
  • Aggregate in the application before writing, for example recording a member who views the same product several times within 1 minute only once

Only when all of these are done and napkin math still shows more than one server can handle is it worth taking on the operating cost of another database.

2. Design the table around the query

sql
CREATE TABLE product_view_event (
    member_id   bigint,
    view_month  text,          -- 'yyyyMM', computed in Taipei time
    viewed_at   timestamp,
    product_id  bigint,
    PRIMARY KEY ((member_id, view_month), viewed_at, product_id)
) WITH CLUSTERING ORDER BY (viewed_at DESC, product_id ASC)
  AND default_time_to_live = 7776000          -- 90 days
  AND compaction = {'class': 'TimeWindowCompactionStrategy',
                    'compaction_window_unit': 'DAYS',
                    'compaction_window_size': 3};
  • Partition key (member_id, view_month): one member’s records for one month go in the same partition, so “recently viewed products” reads just one partition. The month is there to put an upper bound on the partition: with only member_id, a heavy user’s partition would grow forever
  • Clustering viewed_at DESC: inside the partition, rows are already sorted from newest to oldest, so LIMIT 50 just reads from the start with no sort
  • default_time_to_live: data expires automatically after 90 days, no DELETE needed
  • TWCS with a 3-day window: 90 days ÷ 3 days = 30 windows, within the 20–30 the docs recommend. The data in one window is eventually merged into one SSTable, and once the whole window has expired the entire file can be dropped instead of being cleaned up row by row

Compute the partition key in one place, shared by writes and queries:

java
import java.time.Duration;
import java.time.Instant;
import java.time.YearMonth;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/** Partition key for view events: one partition per member per month, so no single partition grows forever. */
public final class ViewEventBuckets {

    private static final ZoneId ZONE = ZoneId.of("Asia/Taipei");
    private static final DateTimeFormatter MONTH = DateTimeFormatter.ofPattern("yyyyMM");

    private ViewEventBuckets() {
    }

    public static String monthOf(Instant viewedAt) {
        return YearMonth.from(viewedAt.atZone(ZONE)).format(MONTH);
    }

    /** The months to read for a query over [from, to], newest first: query the latest month first and stop once you have enough rows. */
    public static List<String> monthsBetween(Instant from, Instant to) {
        YearMonth first = YearMonth.from(from.atZone(ZONE));
        List<String> months = new ArrayList<>();
        for (YearMonth m = YearMonth.from(to.atZone(ZONE)); !m.isBefore(first); m = m.minusMonths(1)) {
            months.add(m.format(MONTH));
        }
        return months;
    }

    public static void main(String[] args) {
        Instant now = Instant.parse("2026-11-22T05:00:00Z");
        System.out.println(monthOf(now));
        System.out.println(monthOf(Instant.parse("2026-11-30T17:30:00Z")));          // already December 1 in Taipei time
        System.out.println(monthsBetween(now.minus(Duration.ofDays(90)), now));
    }
}
text
202611
202612
[202611, 202610, 202609, 202608]

The second line is the time zone trap: 17:30 on November 30 UTC is already December 1 in Taipei. If writes and queries each compute the month in a different time zone, data “disappears”. At query time, run this once per month, in the order monthsBetween returns:

sql
SELECT product_id, viewed_at
FROM product_view_event
WHERE member_id = ? AND view_month = ?
LIMIT 50;

Start reading from the most recent month and stop once you have 50 rows; most of the time only one partition needs to be queried.

3. Writes: blind writes and idempotency

Cassandra’s INSERT does not check first whether the row exists: if the primary key does not exist the row is inserted, and if it does the row is overwritten (an upsert). The write path never needs to read the disk, which is one of the reasons LSM writes are fast.

That is also why sending the same primary key again any number of times gives the same result, and retrying right after a network timeout is safe (idempotency is covered in detail in Part 5). The precondition is that viewed_at must be the time the event happened, sent up by the client; if you use the server’s current time when it receives the request, a retry creates a duplicate record with a different primary key.

INSERT ... IF NOT EXISTS goes through Paxos instead and costs far more; it does not belong on a high-frequency write path.

Pitfalls and gotchas

  • Load tests that are too short: when an LSM first starts taking writes, compaction has not built up any work yet, so the numbers look great. You only see the real write capacity once compaction reaches a steady state
  • Compaction cannot keep up with writes: when the number of L0 files or the amount of data pending compaction crosses a threshold, RocksDB first slows writes down and then stops them completely (a write stall). Monitor pending compaction, not just write latency
  • No headroom left on disk: during a merge, the old files cannot be deleted until the new file has been written. RocksDB universal compaction’s max_size_amplification_percent defaults to 200, which means 100 bytes of data may need 300 bytes during compaction
  • Using Cassandra as a queue: constantly inserting and then deleting fills the partition with tombstones. Tombstones scanned during a read have to be held in memory; above tombstone_warn_threshold (default 1,000) a warning is logged, and above tombstone_failure_threshold (default 100,000) the query fails outright
  • Setting gc_grace_seconds very low to clear tombstones: the default of 10 days is the time a failed node has to recover and catch up on deletes. Lower it without running repair within that window, and deleted data can “come back to life” from other replicas. The docs’ advice: lowering it suits only tables that have no explicit deletes and rely entirely on TTL expiry
  • TWCS with out-of-order writes: backfilling old data with USING TIMESTAMP, or read repair triggered when old data is read, mixes new and old data in the same SSTable, so the files of old windows can no longer be dropped whole
  • TWCS without a TTL: data does not disappear just because its window has passed. Cassandra 5.0 has a guardrail (zero_ttl_on_twcs_enabled) aimed at exactly the tables that use “TWCS with default_time_to_live at 0”
  • Read-modify-write on an LSM: an operation like stock = stock - 1, which has to read before it writes, loses the blind-write advantage and needs extra concurrency control. Keep this kind of data in a relational database

Security

  • Delete is not erase: an LSM DELETE only writes a tombstone; the old value is still in the SSTable and is truly dropped only after compaction, and only once gc_grace_seconds has passed. A B+Tree delete also marks first and lets background purge reclaim the space, with no guarantee that the original bytes are overwritten. Add the WAL, binlog, snapshots, and backups, and when a user asks for their personal data to be deleted, that data is actually still scattered across many places. A common approach is crypto-shredding: encrypt each user’s personal data with its own key and destroy the key on deletion, so every copy becomes unreadable ciphertext at once (key management is in Part 8)
  • Tombstones can be turned into an attack: if an API lets users add to and remove from a list without limit, an attacker who repeats the operations can pile up huge numbers of tombstones in the matching partition. If the partition is shared (say, the comment list of a product), reads fail for everyone; even if it is only the attacker’s own partition, the tombstones put heap pressure on the nodes that serve the query. Rate limit writes (Part 8 Abuse Prevention), and do not let user actions map directly onto large numbers of deletes
  • Data files are ordinary files: SSTables, snapshots, and backups sit directly on disk, and anyone who gets the files can read their contents with tools. Encrypt the disks, and make access to backups and snapshots as strict as access to the database itself

When to use it, and when not to

  • B+Tree (relational databases): read-heavy, needs transactions and range queries, data is often updated in place, stable latency required. Most business systems fall into this category
  • LSM: high write volume that is mostly inserts (events, logs, time series, IoT), data large enough to need compression, writes that can be blind writes with no read first
  • Do not switch just because “write volume is high”: do the napkin math first, and finish the cheap optimizations: batch writes, leaner indexes, partitioning
  • Do not use LSM for: heavy deletes or queue-like access patterns, data that needs read-modify-write and multi-row transactions

References

Comments