LSM Storage, Compaction, Tombstones and Tracing

Article · 10:00

The write and read paths, SSTables and compaction strategies, tombstones and gc_grace_seconds, the queue anti-pattern, partition sizing and reading a trace.

The write path is why Cassandra's writes are cheap. A write goes to the commit log (sequential, durable) and the memtable (in memory), and it is acknowledged. That is all. There is no read, no in-place update, no index maintenance beyond the memtable. When a memtable fills it is flushed to an immutable SSTable on disk.

The read path is where the cost is. A read may have to merge data from the memtable and several SSTables, because a row's columns can be spread across all the SSTables written since it was first created. Bloom filters, partition indexes and the key cache narrow this down, and the number of SSTables touched is the main read-cost metric - it appears in nodetool tablehistograms and in a trace.

Compaction merges SSTables, discarding overwritten values and expired tombstones. The strategy choice is a real decision:

  • SizeTieredCompactionStrategy (STCS) - the default. Merges similarly-sized SSTables. Good write throughput, and a read may touch many SSTables. It also needs up to 50% free disk in the worst case, because it may merge the largest tables together.
  • LeveledCompactionStrategy (LCS) - keeps SSTables in levels so that a row is in at most one SSTable per level. Much better read performance and bounded disk overhead; significantly more write amplification. Right for read-heavy, update-heavy data.
  • TimeWindowCompactionStrategy (TWCS) - groups SSTables by time window. The correct choice for time-series data with a TTL, because a whole window's SSTable expires at once and is dropped without compaction. This is the strategy the capstone's event feed wants.

Tombstones are the thing that will surprise you. Because SSTables are immutable, a delete cannot remove data - it writes a tombstone, a marker saying "this is deleted as of timestamp T". Tombstones are necessary: without them, a delete could be resurrected by a replica that was down and still holds the old value.

Tombstones persist for gc_grace_seconds (10 days by default) before compaction may remove them, and that number exists to give repair time to propagate the delete to every replica. If you reduce gc_grace_seconds below your repair interval, deleted data comes back - which is the most consequential configuration trade-off in Cassandra.

Meanwhile tombstones are returned to the read path. A query reading a range that contains a hundred thousand tombstones does the work of reading a hundred thousand cells and returns nothing. tombstone_warn_threshold logs it; tombstone_failure_threshold aborts the query. A query that times out and reads zero rows is almost always tombstones.

Which makes a queue the canonical Cassandra anti-pattern: write a row, read it, delete it, repeat. Every delete leaves a tombstone at the front of the partition, so reading the next item means scanning all of them. It degrades steadily until it fails. Cassandra is not a queue, and the fix is not tuning - it is a different system for that workload.

Other tombstone sources that surprise people: inserting a null writes a tombstone (so prepared statements with unset-but-bound parameters generate them silently - use unset instead); a collection update writes one; a TTL expiry writes one; and a DELETE with a range or a partition-level delete writes a range tombstone.

Laboratory exercise 4 - a measured improvement.

Load at least ten million rows across your schema. Declare a baseline: five queries with p50, p95 and p99, plus nodetool tablehistograms for each table and the SSTables-per-read figure.

Compare the three compaction strategies on the same time-series data: measure write throughput, read latency, SSTables per read, and disk use under each. Then demonstrate TWCS dropping a whole expired window without compaction.

Build the queue anti-pattern deliberately: a table used as a queue, and measure the read latency as the tombstone count grows. Capture the tombstone_warn_threshold log line, then the failure threshold aborting a query. This is the module's central demonstration.

Demonstrate the gc_grace_seconds trap: with a three-node cluster, take a node down, delete a row, bring the node back after reducing gc_grace_seconds to zero and compacting, and show the deleted row resurrected.

Demonstrate the null tombstone: insert rows with an explicitly-bound null and with unset, and compare the tombstone counts.

Use tracing on your slowest query and act on what it shows.

Deliverable: the benchmark report with percentiles and SSTables-per-read at each step, the three-way compaction comparison, the TWCS window drop, the queue degradation curve with both threshold log lines, the resurrection demonstration, the null-versus-unset comparison, and traces before and after one fix.

-- ==================================================================
-- THE WRITE PATH: commit log + memtable, acknowledge. That is all.
-- ==================================================================
--   write -> COMMIT LOG (sequential, durable)
--         -> MEMTABLE (memory)
--         -> acknowledged
--
--   memtable fills -> FLUSHED to an IMMUTABLE SSTABLE
--
-- No read, no in-place update, no index maintenance. This is why
-- Cassandra's writes are close to the theoretical minimum cost.
--   nodetool flush feed
--   nodetool tablestats feed.events_by_user_day

-- ==================================================================
-- THE READ PATH: where the cost is.
-- ==================================================================
-- A read may merge the memtable and SEVERAL SSTABLES, because a
-- row's columns can be spread across every SSTable written since the
-- row first appeared.
--   nodetool tablehistograms feed.events_by_user_day
--   Percentile  SSTables  Write Latency  Read Latency  Partition Size  Cell Count
--   50%             1.00         35.43 us      182.79 us           1916        42
--   95%             3.00         88.15 us      943.13 us          17084       310
--   99%             8.00        152.32 us     4866.32 us          73457      1331
--   Max            24.00       1131.75 us    43388.63 us        1629722     31045
--               ^^^^^^^^ 24 SSTABLES FOR ONE READ at the max. THE
--               main read-cost metric. Anything above ~10 at p99
--               wants a compaction strategy review.

-- ==================================================================
-- COMPACTION STRATEGY: a real decision.
-- ==================================================================
-- STCS - the DEFAULT. Merges similarly-sized SSTables.
ALTER TABLE events_by_user_day WITH compaction = {
  'class': 'SizeTieredCompactionStrategy', 'min_threshold': 4 };
--   + good write throughput
--   - a read may touch MANY SSTables
--   - NEEDS UP TO 50% FREE DISK in the worst case, because it may
--     merge the largest tables together. That is a provisioning
--     requirement people discover when the disk fills.

-- LCS - levels, so a row is in AT MOST ONE SSTable per level.
ALTER TABLE user_profile WITH compaction = {
  'class': 'LeveledCompactionStrategy', 'sstable_size_in_mb': 160 };
--   + much better reads, BOUNDED disk overhead (~10%)
--   - significantly MORE WRITE AMPLIFICATION
--   RIGHT FOR: read-heavy, update-heavy data.

-- TWCS - groups SSTables by TIME WINDOW.
ALTER TABLE events_by_user_day WITH compaction = {
  'class': 'TimeWindowCompactionStrategy',
  'compaction_window_unit': 'DAYS',
  'compaction_window_size': 1
} AND default_time_to_live = 2592000
  AND gc_grace_seconds = 10800;         -- see the caveat below
--
--   THE CORRECT CHOICE FOR TIME-SERIES WITH A TTL. A whole window's
--   SSTable expires AT ONCE and is DROPPED WITHOUT COMPACTION -
--   which means the tombstones never reach the read path at all.
--   This is what the capstone's event feed wants.
--
--   Requirements for it to work: writes must be roughly in time
--   order (no large backfills into old windows), and the TTL should
--   be uniform.
--   nodetool compactionstats
--   nodetool compactionhistory

-- ==================================================================
-- TOMBSTONES. The thing that will surprise you.
-- ==================================================================
-- SSTables are IMMUTABLE, so a delete cannot remove data. It writes
-- a TOMBSTONE: "deleted as of timestamp T".
--
-- They are NECESSARY: without them a delete could be RESURRECTED by
-- a replica that was down and still holds the old value.

DELETE FROM events_by_user_day
WHERE user_id = 7f3c... AND day = '2026-11-30'
  AND event_at = '2026-11-30 14:04:00+0000';
--   -> a tombstone, not a removal.

-- gc_grace_seconds: how long a tombstone MUST persist before
-- compaction may drop it. 10 DAYS by default.
ALTER TABLE events_by_user_day WITH gc_grace_seconds = 864000;
--
-- *** THE MOST CONSEQUENTIAL TRADE-OFF IN CASSANDRA ***
--   That number exists to give REPAIR time to propagate the delete
--   to EVERY replica.
--   IF gc_grace_seconds < YOUR REPAIR INTERVAL, DELETED DATA COMES
--   BACK.
--
--   The resurrection, step by step - demonstrate it:
--     1. node3 goes down
--     2. DELETE a row -> tombstone on node1, node2
--     3. gc_grace_seconds passes; compaction DROPS the tombstone
--     4. node3 comes back, still holding the ORIGINAL VALUE
--     5. there is no tombstone left to say it was deleted
--     6. THE ROW IS BACK. Repair propagates it to node1 and node2.
--
--   So: set gc_grace_seconds >= your repair interval, ALWAYS, and
--   run repair reliably. People reduce it to control tombstones and
--   resurrect data months later.

-- TOMBSTONES ARE RETURNED TO THE READ PATH.
TRACING ON;
SELECT * FROM events_by_user_day
WHERE user_id = 7f3c... AND day = '2026-11-01';
--   Read 0 live rows and 184,203 tombstone cells
--        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
--   The work of reading 184,203 cells, to return NOTHING.
TRACING OFF;
--
--   cassandra.yaml:
--     tombstone_warn_threshold: 1000       -> logs a WARN
--     tombstone_failure_threshold: 100000  -> ABORTS the query
--
--   A QUERY THAT TIMES OUT AND READS ZERO ROWS IS ALMOST ALWAYS
--   TOMBSTONES. That one diagnostic sentence saves hours.

-- ==================================================================
-- THE QUEUE ANTI-PATTERN. The canonical one.
-- ==================================================================
CREATE TABLE job_queue (             -- DO NOT DO THIS
    shard int, job_id timeuuid, payload text,
    PRIMARY KEY (shard, job_id)
);
--   write a row, read the oldest, DELETE it, repeat.
--
--   Every delete leaves a TOMBSTONE AT THE FRONT OF THE PARTITION.
--   Reading the next item means SCANNING ALL OF THEM.
--   It degrades STEADILY and then FAILS.
--
--   day 1:   SELECT ... LIMIT 1   ->   2 ms,       12 tombstones
--   day 7:   SELECT ... LIMIT 1   -> 240 ms,   48,000 tombstones
--   day 14:  SELECT ... LIMIT 1   -> TombstoneOverwhelmingException
--
-- CASSANDRA IS NOT A QUEUE. The fix is not tuning - it is Kafka,
-- Pulsar, SQS or a Redis stream. Measure the curve in the lab; it is
-- the module's central demonstration.

-- ==================================================================
-- THE TOMBSTONE SOURCES THAT SURPRISE PEOPLE.
-- ==================================================================
-- 1. INSERTING A NULL WRITES A TOMBSTONE.
INSERT INTO events_by_user_day (user_id, day, event_at, event_id, kind, payload)
VALUES (7f3c..., '2026-11-30', '...', now(), 'login', null);
--                                                     ^^^^ a tombstone
--   So a PREPARED STATEMENT with a bound-but-empty parameter
--   generates one SILENTLY, on every write. In the driver, leave it
--   UNSET instead:
--     boundStatement.unset("payload")      -- no tombstone
--     boundStatement.setString("payload", null)  -- A TOMBSTONE
--   This is a real production surprise: millions of tombstones from
--   an optional field nobody sets.

-- 2. A COLLECTION update or replacement.
UPDATE user_profile SET tags = {'new'} WHERE user_id = 7f3c...;
--   A RANGE TOMBSTONE covering the whole collection, then the write.

-- 3. A TTL EXPIRY writes one. (TWCS is the answer.)

-- 4. A RANGE or PARTITION delete writes a range tombstone:
DELETE FROM events_by_user_day WHERE user_id = 7f3c... AND day = '2026-11-01';

-- Finding them:
--   nodetool tablestats feed.events_by_user_day | grep -i tombstone
--   Average tombstones per slice (last five minutes): 1842.0
--   Maximum tombstones per slice (last five minutes): 184203
--   sstablemetadata /var/lib/cassandra/data/feed/.../*-Data.db
--     -> Estimated droppable tombstones: 0.74   <- 74% droppable
--   nodetool garbagecollect feed events_by_user_day
--   nodetool compact feed events_by_user_day    -- a major compaction;
--     expensive, and with STCS it leaves ONE huge SSTable that will
--     not compact again for a long time. Use sparingly.

-- ==================================================================
-- PARTITION SIZING, measured.
-- ==================================================================
--   nodetool tablehistograms  -> Partition Size, Cell Count at Max
--   targets: < 100 MB, < 100,000 rows
--
-- Find the offenders:
--   nodetool toppartitions feed events_by_user_day 10000
--   (and in the logs: "Writing large partition feed/events_by_user_day:...")

Discussion

No questions on this topic yet. Sign in to ask the first one.