Cassandra in depth
Cassandra makes writes cheap and pays later, in compaction, tombstones and repair. Learn where each cost lands, so deleted data stays deleted and reads stay fast.
Updated since you finished it. We changed this lesson after you marked it done. Your progress is kept.
What broke
Uber runs Cassandra as an internal service. In 2023 it had tens of thousands of nodes and tens of millions of queries per second. Clusters ranged from 6 to 450 nodes. 1
Teams that used it reported a strange problem: "data inconsistency due to data resurrection". Data they had deleted came back. Uber's write-up names the usual causes: "Frequent data deletions and downed nodes". 1
The fix was repair, the background job that makes replicas agree. Uber's repairs were slow. Its p99 repair time was "tens of days". 1 With Cassandra's default grace period of 10 days, a repair that takes tens of days cannot keep up. 7 8 Uber's post does not say which grace period it used.
So Uber made repair part of Cassandra itself, like compaction. It works through the ring node by node and needs no outside control plane. The p99 repair time fell to "just under a single-digit number of days". 1
Some use cases that relied heavily on lightweight transactions saw higher error rates "every other week". The cause was in node replacement. The new node kept looking up the old node's hostname. When that lookup failed, its view of pending ring changes no longer matched the other nodes. 1
None of this is a bug in your queries. It is how Cassandra stores and deletes data. This lesson shows the parts you must run yourself.
The idea in simple words
You already know two halves of Cassandra. Quorums and leaderless replication covers consistency levels, hints, read repair and Merkle-tree repair. B-tree vs LSM-tree covers the memtable, SSTables and compaction. Data modelling for NoSQL covers partition keys and time buckets.
This lesson joins them. Cassandra never changes a file on disk. So a delete cannot remove data. It writes a marker instead, a tombstone. 7 Every replica must see that marker before any replica throws it away.
The key idea. In Cassandra, a delete is a write that must reach every replica before its grace period ends. Compaction cleans up, and repair makes sure there is nothing left to bring back. You must run both well.
How it works
The write path
A write first goes to a commit log on disk, added at the end. Then it goes into the memtable in memory. 2 By default the commit log uses "periodic" sync. The write is acknowledged at once, and the log is synced every 10 seconds. A crash can lose up to that period, or more if a sync is late. 2
When the memtable is full, Cassandra flushes it to a new SSTable. That file is never written again. So one partition is usually spread over several SSTables. 2
The read path
A read must merge the memtable and every SSTable that may hold the partition. 3 Each SSTable has a Bloom filter. It says "surely not here" or "maybe here", so most files are skipped. 3 For a file that may have it, a partition index points to the data's place in the file. 2
The read keeps the newest value for each cell, by timestamp. A tombstone hides every older value. 7 So a read for live rows must still step over tombstones.
The default false-positive chance is 0.01 for most tables and 0.1 for leveled ones. Going from 0.1 to 0.01 roughly triples the filter's memory. 3
Tombstones and the grace period
Step through one delete. Use Next and Back, or the ← and → keys.
- Three replicas hold row 7. You delete it at QUORUM. A and B write a tombstone with a newer timestamp. C is down and misses the delete. It stays down for days, past the 3-hour hint window.
- Reads still work. A QUORUM read merges the answers and keeps the newest one. The tombstone (t=2) beats the row (t=1), so the row stays deleted.
- The default gc_grace_seconds is 10 days. After it, compaction on A and B may drop the tombstone and the old row. C still has row 7, with no tombstone.
- Now repair compares the replicas. Nothing says row 7 was deleted. C's copy looks like live data, so it is copied back to A and B.
- The fix: repair every node before gc_grace_seconds runs out. C then receives the tombstone while A and B still have it.
The grace period is the table setting gc_grace_seconds. Its default is 864000 seconds, which is 10 days. 7 After that, compaction may drop the tombstone. It needs every older SSTable for that partition in the same compaction. 7 An expired TTL also becomes a tombstone. 4
By default, Cassandra does not run repair for you. 8 Since 5.0.8 it has a built-in scheduler, Auto Repair, but you must turn it on. 10 With the default grace period, the docs say to repair every node at least once every 7 days. 8 If you lower gc_grace_seconds, repair must run more often. You can also set only_purge_repaired_tombstones, so only repaired tombstones are dropped. 7
Too many tombstones
A scan keeps the tombstones it sees in memory. That can hurt performance and even exhaust the heap. 9 So cassandra.yaml sets two limits. By default, tombstone_warn_threshold is 1,000 and tombstone_failure_threshold is 100,000. A read that scans more than 1,000 tombstones logs a warning. More than 100,000 and the read fails. 9
The classic way to reach them is a queue in a table. Workers read the oldest rows in a partition and delete them. Every read for "the next job" now walks past all recent deletes. The yaml file links to a DataStax post about this anti-pattern. 9 Use a real queue or log instead. See queues vs logs.
Large partitions
A partition lives on one set of replicas. A huge one cannot be spread across the cluster. Cassandra 5.0 has guardrails, partition_size_warn_threshold and partition_size_fail_threshold. They are off by default. 9 The fix is in the key, for example a time bucket. The NoSQL modelling lesson shows how.
Compaction strategies
| Strategy | Best for | Watch out for |
|---|---|---|
| Size-tiered (STCS) | The default, a fallback. Data that is not strict time series, or when LCS costs too much I/O. 4 | Reads touch more SSTables. |
| Leveled (LCS) | Read-heavy tables, or many updates and deletes. 4 | Not for immutable time series. 4 |
| Time window (TWCS) | TTL'ed, mostly immutable time series. 4 | Out-of-order writes and USING TIMESTAMP mix old and new data. 5 |
| Unified (UCS) | Recommended for new workloads. 4 | New in 5.0. 10 |
TWCS merges each closed window into one SSTable, then leaves it alone. When everything in it expires, Cassandra can drop the whole file. 5 Aim for about 20 to 30 windows. With a 90-day TTL, 3-day windows fit. 5
UCS has one scaling setting. Tiered values act like STCS, leveled values like LCS. Its default, T4, is STCS with a threshold of 4. 6
Lightweight transactions and counters
INSERT ... IF NOT EXISTS and UPDATE ... IF use Paxos. The docs warn of "a non-negligible performance cost". 12 The legacy Paxos (v1), still the default, needs about 4 round trips for a write. Paxos v2 needs about 2. 9 Cassandra 4.1 added v2. 10
INSERT INTO usernames (name, user_id)
VALUES ('asha', 42)
IF NOT EXISTS; -- check [applied] in the resultCounters are a special column type. Apart from its primary key, a table with a counter can hold only counters. You cannot set a value or give it a TTL. 13 Counter updates are not idempotent. After a timeout, a retry "may or may not lead to an over count". 13
The token ring
Each node owns tokens on a hash ring. With virtual nodes, a node owns many small ranges. 11 Cassandra 4.0 cut the default num_tokens from 256 to 16. 10 A smarter token allocator now spreads data well with few tokens. Many tokens tie many nodes together and raise the risk of an outage. 11
ScyllaDB calls itself "a drop-in replacement for Apache Cassandra 3.11", with some 4.0 features. 14 Check its table for the features you use.
Trade-offs
| Choice | Good for | Cost |
|---|---|---|
Lower gc_grace_seconds | Yes Fewer tombstones to scan. | Repair must finish inside the shorter window. Otherwise zombies. 8 |
| TTL instead of deletes, with TWCS | Yes Whole files expire. 5 | Breaks with out-of-order writes. 5 |
| Lightweight transactions | Yes Check-and-set in one partition. | More round trips than a plain write. 9 |
| Counters | Yes Fast increments. | Retries can over count. 13 |
| Commit log in batch mode | Yes A write is acknowledged only after the log is synced to disk. 2 | Each write waits for that sync. |
Simple rule: if a table has deletes, schedule repair inside gc_grace_seconds before you go live. If a table works like a queue, move it out of Cassandra.
At work: how a senior uses this
- For each table, write down how rows die: delete, TTL, or never. Pick the compaction strategy from that answer.
- Alert when repair has not finished on every node within the grace period. Missing it is silent until data comes back.
- Watch tombstone warnings in the logs. Each one names a query that scans too much.
- Before a design review, ask, "Does any read step over many deleted rows?" Queues, inboxes and "latest status" tables are the usual suspects.
- Use lightweight transactions only where a race costs money or trust, such as unique usernames. Measure their latency.
- Keep the same
num_tokenson every node in a data centre. A new node with a different value owns a different share of data. 10
With AI
What to ask the agent
"Here is our Cassandra schema and every query. For each table, tell me how rows are removed, the compaction strategy you would pick, and why. Flag any table that behaves like a queue."
"Write a test on a 3-node cluster. Stop one node, delete a row, set gc_grace_seconds to 60, compact the others, start the node and run repair. Show whether the row comes back."
"Find every counter update and IF condition in this code. For each, say what happens on a timeout and a retry."
What to check yourself
- Repair is scheduled, finishes, and alerts on failure, at least once per
gc_grace_seconds. - The agent's compaction advice matches your Cassandra version. UCS needs 5.0.
- No code retries a counter update blindly.
- Version-specific defaults the agent quotes, like
num_tokensorpaxos_variant, match yourcassandra.yaml. - A test that "proves" deletes work also includes a node that was down during the delete.
Check yourself
Your progress is saved only in this browser. Export it to keep it safe.
You have finished 5 lessons. Your progress lives only in this browser. Export a copy so you don’t lose it.
Go deeper
Show 14 sources and related lessons
- Runtian Liu, Gopal Mor and Jaydeepkumar Chovatia, “How Uber Optimized Cassandra Operations At Scale”, Uber blog (20 July 2023) (opens in a new tab)
Uber's Cassandra service at tens of thousands of nodes. See the sections on lightweight transaction errors and on building repair into Cassandra after deleted data came back. - Apache Cassandra documentation: Storage Engine (opens in a new tab)
The commit log and its sync modes, memtable flushes, and the files that make up one SSTable. - Apache Cassandra documentation: Bloom Filters (opens in a new tab)
How a read skips SSTables that cannot hold the partition, and the default false-positive chance per compaction strategy. - Apache Cassandra documentation: Compaction overview (opens in a new tab)
The four strategies and when the docs suggest each one, plus how gc_grace_seconds and TTLs turn into tombstones. - Apache Cassandra documentation: Time Window Compaction Strategy (opens in a new tab)
Time windows, dropping whole expired SSTables, and the writes that break it. - Apache Cassandra documentation: Unified Compaction Strategy (UCS) (opens in a new tab)
One strategy with a scaling setting that can act tiered (like STCS) or leveled (like LCS). - Apache Cassandra documentation: Tombstones (opens in a new tab)
Why a delete is a write, the 10-day grace period, zombies, and when compaction may drop a tombstone. - Apache Cassandra documentation: Repair (opens in a new tab)
Repair is run by you, not by Cassandra. How often to run it so deleted data does not come back. - Apache Cassandra, conf/cassandra.yaml (cassandra-5.0 branch, GitHub) (opens in a new tab)
The default config with comments. See num_tokens, the tombstone safety thresholds and paxos_variant. - Apache Cassandra, NEWS.txt (cassandra-5.0 branch, GitHub) (opens in a new tab)
Release notes. The 4.0 change of num_tokens from 256 to 16, Paxos v2 in 4.1, UCS in 5.0, and Auto Repair in 5.0.8. - Apache Cassandra documentation: Dynamo (opens in a new tab)
The token ring, virtual nodes, and why many tokens per node raise the risk of an outage. - Apache Cassandra documentation: Data Manipulation (opens in a new tab)
INSERT, UPDATE and DELETE, the cost of IF conditions, and counter batches. - Apache Cassandra documentation: Data Types (opens in a new tab)
See "Counters" for what counters cannot do and why a retried update can over count. - ScyllaDB documentation: ScyllaDB and Apache Cassandra Compatibility (opens in a new tab)
A feature-by-feature table of what ScyllaDB supports from Cassandra.
Case studies: Discord: Moving trillions of messages from Cassandra to ScyllaDB
Related: Quorums and leaderless replication · B-tree vs LSM-tree · Data modelling for NoSQL · Sharding and consistent hashing · Consensus and Raft
Before this: Quorums and leaderless replication, B-tree vs LSM-tree and Data modelling for NoSQL. Related: Sharding and consistent hashing and Consensus and Raft, for what Paxos-style agreement costs.