Summary#
Apache Cassandra is a masterless, partitioned, wide-column database for huge write volumes and always-on availability.
- Data is spread around a token ring by hashing the partition key (consistent hashing with virtual nodes), and copied to
RFreplicas, usually 3 per data centre. - Any node can coordinate any request. Each read or write picks a consistency level (ONE, QUORUM, LOCAL_QUORUM, ALL), so you trade latency and availability against consistency per query.
- Writes go to a commit log and an in-memory memtable, then flush to immutable SSTables. This LSM design makes writes cheap, sequential and fast: often well under a millisecond on the node, and tens of thousands per second per node.
- Reads merge memtables and SSTables, so they cost more, and depend on compaction and good modelling.
Modelling is query-first. You design one table per access pattern, keyed so each query hits one partition, with clustering columns giving sorted order inside it. Big or hot partitions, tombstones and skipped repairs are the classic failure modes.
ScyllaDB is a C++ reimplementation with the same data model and query language. Discord moved trillions of messages to it, from 177 Cassandra nodes to 72 ScyllaDB nodes.
Why It Exists#
In 2007–2008 Facebook needed to store and search users' inbox messages: an enormous, constantly growing dataset with heavy writes, spread across data centres, that had to stay available when machines failed. Avinash Lakshman, one of the authors of Amazon's Dynamo paper, and Prashant Malik built Cassandra for this "Inbox Search" problem. They described it in "Cassandra: A Decentralized Structured Storage System" (LADIS 2009).
Cassandra combined two landmark designs:
- From Amazon Dynamo ("Dynamo: Amazon's Highly Available Key-value Store", DeCandia et al., SOSP 2007): a masterless ring with consistent hashing, replication to N nodes, sloppy quorums, hinted handoff, gossip membership, and anti-entropy repair. No single node is special, so there's no leader to fail.
- From Google Bigtable ("Bigtable: A Distributed Storage System for Structured Data", Chang et al., OSDI 2006): the wide-column data model (rows with many sorted columns) and the LSM storage engine (commit log, memtable, SSTables, compaction).
Facebook open-sourced Cassandra in 2008, and it became an Apache top-level project in 2010. Companies such as Netflix, Apple, Instagram, Discord and Bloomberg have used it for workloads with three traits:
- Write-heavy, ever-growing data: messages, events, time series, activity logs, IoT readings.
- Availability over strict consistency: keep accepting writes when nodes, racks or even a data centre fail.
- Known access patterns: "messages in a channel, newest first", "readings for a sensor in a time range", "a user's recent activity".
A single relational primary tops out around 5k–20k write transactions per second (Numbers to Know), and sharding it by hand is painful (Partitioning and Sharding). Cassandra makes horizontal scaling the default: add nodes, and the ring rebalances token ranges. Write capacity grows roughly linearly.
But don't reach for Cassandra just because a write number sounds big. A few thousand writes per second fit comfortably on one well-tuned Postgres. Cassandra earns its operational cost at sustained tens of thousands to millions of writes per second, at terabyte-to-petabyte scale, or when multi-data-centre active-active writes are required.
How It Works#
Architecture: the ring, coordinators and replicas#
A Cassandra cluster is a set of peer nodes, grouped into racks and data centres (DCs). There's no primary. Every node:
- owns some token ranges of the ring;
- stores replicas for those ranges, and for ranges before it, depending on the replication strategy;
- can act as coordinator for any client request;
- gossips cluster state with peers.
Drivers are token-aware. The DataStax drivers learn the ring and send each request directly to a replica of the partition, which then coordinates. That saves a hop. The coordinator forwards the request to the replicas, waits for as many responses as the consistency level requires, and answers the client.
Consistent hashing, the ring and virtual nodes#
Why not hash(key) mod N? With modulo placement, adding a node changes N, and almost every key moves: going from 4 to 5 nodes remaps about 80% of keys. Modulo also clumps badly when hashes or key distributions are uneven.
The ring. Cassandra's default Murmur3Partitioner hashes each partition key to a 64-bit token, between −2⁶³ and 2⁶³−1. Imagine those values on a circle.
- Each node is assigned tokens on the circle, and owns the range from the previous token (exclusive) up to its own (inclusive). A key belongs to the first node clockwise from its token.
- Adding a node inserts new tokens, and the new node takes over only the ranges it now owns, from its neighbours. Data movement is about 1/N of the dataset, not nearly all of it.
- Removing a node hands its ranges to neighbours.
That's consistent hashing (Consistent Hashing).
Virtual nodes (vnodes). With one token per node, ranges are uneven, and a new node takes load from only one neighbour. With vnodes, each physical node owns many tokens, spread randomly around the ring. Ownership evens out statistically. A joining node takes small slices from many nodes at once, so streaming is spread out. A bigger machine can own more tokens, for proportionally more data.
Early Cassandra defaulted to 256 vnodes per node. Cassandra 4.0 moved the default to 16, together with a token allocation algorithm that balances ownership for the keyspace's replication factor. Very high vnode counts made repair and streaming slower, and increased the chance that losing any two nodes would make some range unavailable at QUORUM.
Replica placement. Starting from the token's owner, the replication strategy walks clockwise to choose RF replicas:
SimpleStrategytakes the nextRF − 1distinct physical nodes. It's for single-DC tests only.NetworkTopologyStrategyplaces a configured number of replicas per data centre, and spreads them across distinct racks where possible (racks usually map to cloud availability zones). One rack or AZ outage then removes at most one replica.
Use it in production:
CREATE KEYSPACE chat WITH replication =
{'class': 'NetworkTopologyStrategy', 'us_east': 3, 'eu_west': 3};Consistent hashing elsewhere. The same idea appears all over system design:
- DynamoDB partitions, and Riak;
- distributed caches (Memcached client hashing, the Ketama algorithm);
- CDN and load-balancer affinity (Maglev-style hashing);
- request routing to stateful services. Discord routes all requests for a channel to the same data-service instance by consistent-hashing the channel ID. A chat system can assign users to chat servers by consistent-hashing user IDs, with the ring membership in ZooKeeper or etcd. That gives direct server-to-server delivery, at the cost of a full mesh of connections and careful reconnection when the ring changes (avoid thundering herds, and send to both owners during a move). A pub/sub layer is often simpler.
In an interview, reach for consistent hashing when you design a sharded stateful tier (a cache, a custom store, a routing layer) and must scale it without remapping everything. With a managed database that already does it, just mention it.
The data model: keyspaces, tables, partitions and rows#
- Keyspace: the top-level namespace, like a database in Postgres. It holds the replication settings (strategy and RF per DC), plus user-defined types.
- Table: has a schema of typed columns and a primary key. Writes may set any subset of columns. Unset columns take no storage, which is why Cassandra is called wide-column. Rows in one table can be sparse, and a partition can hold millions of rows.
- Partition: all rows sharing the same partition key. The partition is the unit of distribution (one token, one replica set) and the unit of efficient querying.
- Row: identified within its partition by the clustering columns. Rows are stored sorted by clustering columns on disk.
- Cell: a column value in a row. Every cell carries a write timestamp (microseconds, normally set by the coordinator or client), and optionally a TTL. Conflicting writes to the same cell are resolved by last write wins (LWW): the highest timestamp wins on read and compaction.
Loosely, a table looks like a big nested map: partition key → (sorted clustering key → {column: value with timestamp}). Types include text, int, bigint, uuid and timeuuid, timestamp, decimal, blob, collections (list, set, map), user-defined types, frozen types, counters, and since Cassandra 5.0 a vector type for embeddings.
Primary key anatomy:
-- partition key a; no clustering: one row per partition
CREATE TABLE t1 (a text, b text, c text, PRIMARY KEY (a));
-- partition key a; clustering b (sorted ascending within each a)
CREATE TABLE t2 (a text, b text, c text, PRIMARY KEY ((a), b))
WITH CLUSTERING ORDER BY (b ASC);
-- composite partition key (a, b); clustering c
CREATE TABLE t3 (a text, b text, c text, d text, PRIMARY KEY ((a, b), c));
-- partition key a; clustering b then c (same as PRIMARY KEY ((a), b, c))
CREATE TABLE t4 (a text, b text, c text, d text, PRIMARY KEY (a, b, c));- Partition key (the first part, in inner parentheses if composite): hashed to the token. Queries must supply it with equality to be efficient. A query without the partition key is a full-cluster scan, which Cassandra refuses unless you add
ALLOW FILTERING, and you almost never should. - Clustering columns: define the sort order inside the partition, and allow range queries and ordering on a prefix:
WHERE a = ? AND b > ? ORDER BY b DESC LIMIT 50. You must restrict clustering columns left to right. You can't skipband filter onc. - Static columns (
STATIC) are stored once per partition and shared by all its rows. Useful for per-partition metadata, such as a channel's name stored alongside its messages.
DynamoDB's model is the same idea: partition key plus sort key (DynamoDB).
Query-first data modeling#
Relational modelling starts from entities and relationships: normalise, then join at query time (Data Modeling). Cassandra has no joins, no foreign keys, no subqueries, and limited secondary indexing. So you invert the process:
- List the access patterns with their rates and latency targets. For example "get the 50 newest messages in a channel" (90% of reads), "messages before message X" (scrollback), "messages by a user" (rare).
- Design one table per pattern, keyed so each query reads one partition, ideally a contiguous slice of it.
- Denormalise. Duplicate data into each table that needs it. Writes become more numerous (one logical write updates several tables), but writes are cheap in Cassandra, and reads become single-partition lookups.
- Bound the partitions. Estimate the worst-case partition size and growth, and add a bucket to the partition key (time window, hash suffix) when needed.
- Choose clustering order to match the dominant read, for example newest first with
CLUSTERING ORDER BY (message_id DESC).
The four questions to ask for every table:
- Partition key: what determines where the data lives, and is it high-cardinality and evenly accessed?
- Partition size: how big can one partition get in the extreme case, and does it grow forever?
- Clustering key: what order do reads need?
- Denormalisation: which other tables need copies of this data to serve their own queries?
Worked example: chat messages, Discord style. Discord explained in 2017 that it moved messages from MongoDB to Cassandra. The obvious first schema:
CREATE TABLE messages (
channel_id bigint, message_id bigint, author_id bigint, content text,
PRIMARY KEY (channel_id, message_id)
) WITH CLUSTERING ORDER BY (message_id DESC);message_idis a Snowflake ID: a 64-bit, time-sortable unique ID with timestamp, worker and sequence bits (Unique ID Generation). Using it instead ofcreated_atgives chronological order and uniqueness. Two messages in the same millisecond would collide on a timestamp key, and in Cassandra a collision is a silent overwrite (an upsert), not an error.- One channel equals one partition, so "latest 50 messages" is a single-partition, sequential slice.
The problem: unbounded partitions. A busy channel accumulates millions of messages forever, in one partition. Large partitions (hundreds of MB to GBs) hurt compaction, repair, streaming, heap usage and read latency.
Discord's fix was to add a time bucket to the partition key:
CREATE TABLE messages (
channel_id bigint, bucket int, message_id bigint, author_id bigint, content text,
PRIMARY KEY ((channel_id, bucket), message_id)
) WITH CLUSTERING ORDER BY (message_id DESC);
-- bucket = floor((message_timestamp - DISCORD_EPOCH) / 10 days)- Each bucket covers a 10-day window, counted from Discord's own epoch (1 January 2015). Even the busiest channel's 10 days fit in a healthy partition, and partitions stop growing once their window passes.
- Recent messages are almost always in the current bucket, so the common query still hits one partition.
- Scrollback, or quiet channels whose last messages were weeks ago, walk backwards through buckets: query bucket N, then N−1, and so on, until the page is full. That's a small extra cost on the minority of queries.
That's query-first modelling in action. The partition key matches the access pattern (one channel), the clustering key matches the order (newest first), and the bucket bounds partition size.
Worked example: ticket browsing, Ticketmaster style. The seat-map view tolerates staleness: availability changes while users look, and the checkout path re-checks a strongly consistent store. A first schema:
CREATE TABLE tickets (event_id bigint, seat_id bigint, price bigint,
PRIMARY KEY (event_id, seat_id));One event is one partition. Simple, but a 50,000-seat stadium makes a large partition, and every venue-level page must aggregate across all seats (counts, minimum prices) on each request, for the hottest events.
Look at the UX instead. Users first see a venue map with sections (a summary per section), and then click a section to see its seats. Model exactly that:
CREATE TABLE tickets (event_id bigint, section_id bigint, seat_id bigint, price bigint,
PRIMARY KEY ((event_id, section_id), seat_id));
CREATE TABLE event_sections (event_id bigint, section_id bigint,
num_tickets bigint, price_floor bigint,
PRIMARY KEY (event_id, section_id));ticketspartitions by (event, section), so a section's seats are one small partition, and a popular event spreads across many partitions and nodes.event_sectionsis denormalised summary data. The venue view reads one partition of fewer than about 100 rows. Its counts may lag slightly, which is acceptable (sites often show "100+" rather than exact numbers).
Updates flow from the booking system: when a seat sells, update tickets, and adjust the section summary, asynchronously or in a batch. The authoritative "is this seat free?" check stays in the transactional system (Ticket Booking).
Partition sizing arithmetic. A rule of thumb is to keep partitions under about 100 MB, and ideally to tens of MB or less, with up to hundreds of thousands of rows. For chat:
- a busy channel posts 20 messages per second at about 300 bytes each;
- a day is about 1.7 million messages, about 520 MB, so per-day partitions would be too big for the very busiest channels;
- most channels post a few hundred messages a day, so 10-day buckets hold a few MB.
This skew is why some designs use adaptive buckets: small windows for hot channels, large ones for quiet channels, recorded in a metadata table. Size the bucket for the 99.9th-percentile entity, not the median.
Secondary access paths.
- Denormalised tables (
messages_by_author) are the classic answer, written alongside the main table (a loggedBATCHgives atomicity across tables, at some coordinator cost). - Materialised views let Cassandra maintain a re-keyed copy automatically. They've been marked experimental, because of consistency issues between base and view under failure, and many operators avoid them.
- Secondary indexes (2i) are local to each node, so a query must ask every node. They're acceptable only for low-cardinality columns combined with a partition key restriction.
- Storage-Attached Indexes (SAI), production-ready in Cassandra 5.0, index columns per SSTable with much lower overhead, and support numeric ranges, text and vector similarity (with ANN search on the
vectortype). They suit infrequent query patterns that don't justify another table. They're still slower than a partition-key read, because a query may touch many nodes. - External search. For full-text or ad-hoc search, stream changes (via CDC, or dual write) into Elasticsearch. Older integrations used Lucene plugins inside Cassandra.
The LSM write path#
Cassandra's storage engine is a log-structured merge tree (Storage Engines). It favours write speed over read speed. Every insert, update and delete is a new append, never an in-place modification. A write arriving at a replica:
- Commit log append. The mutation is appended to a sequential, per-node commit log on disk: the write-ahead log for crash recovery.
commitlog_sync: periodic(the default) fsyncs every 10 s. Acknowledged writes on a single node could be lost in a power failure within that window, but the other replicas cover it.batchorgroupmodes fsync before acknowledging, at a latency cost. - Memtable insert. The mutation is applied to the in-memory memtable for that table, a sorted structure keyed by partition and clustering key. Cassandra 5.0 added trie-based memtables, which are more memory-efficient.
- Acknowledge. The replica tells the coordinator it's done. No disk read happened, and no B-tree page was modified. That's why a node can absorb tens of thousands of writes per second per core-rich machine, with sub-millisecond local latency.
- Flush. When a memtable reaches its size threshold (or the commit log fills, or on a timer), it's written sequentially to disk as an immutable SSTable (sorted string table). Commit-log segments whose data is now flushed are recycled.
- Compaction. In the background, SSTables are merged into fewer, larger ones. That keeps the newest version of each cell and discards overwritten data and expired tombstones.
An SSTable is a set of files:
Data.db: the rows, sorted by token then clustering key, compressed in chunks (16 KB by default).Index.db: partition key to offset in the data file. Cassandra 5.0 has an alternative trie-indexed format, BTI.Summary.db: a sample of the index, held in memory.Filter.db: a Bloom filter over partition keys.CompressionInfo.db: chunk offsets.Statistics.db: min and max timestamps, tombstone estimates.TOC.txt.
Because SSTables are immutable, snapshots are just hard links: instant backups.
The read path and compaction, in depth#
The read path. To read a partition slice on one replica, Cassandra:
- Checks the memtable, which may hold the newest cells.
- Optionally checks the row cache. It's off by default, and only helps small, hot, read-mostly partitions.
- For each SSTable that might contain the partition:
- Bloom filter: "definitely not here" or "maybe here". This skips most SSTables. The false-positive rate is tunable via
bloom_filter_fp_chance(0.01 by default for most strategies), and is a memory trade-off. - Key cache or partition index: finds the partition's position in
Data.db, using the in-memory summary to jump to the right part of the index (or the trie index in BTI format). - Compression offsets: map the position to the compressed chunk, which is read and decompressed.
- Bloom filter: "definitely not here" or "maybe here". This skips most SSTables. The false-positive rate is tunable via
- Merges cells from all sources by clustering key, picking the highest timestamp per cell, and applying tombstones and TTL expiry.
- Returns the result to the coordinator.
The read's cost grows with the number of SSTables containing the partition. A partition written over months, under a compaction strategy that leaves it in 20 SSTables, costs up to 20 seeks and merges. Watch the SSTables per read histogram (nodetool tablehistograms). Below about 3–5 is healthy.
Compaction strategies decide which SSTables merge, and when. That's a classic read, write and space amplification trade-off:
| Strategy | How it works | Read amp | Write amp | Space amp | Fits |
|---|---|---|---|---|---|
| Size-Tiered (STCS), the long-time default | Merge roughly 4 SSTables of similar size | Higher; partitions spread across tiers | Low | High; needs up to about 50% free disk during big merges | Write-heavy, insert-mostly data |
| Leveled (LCS) | Levels L1, L2, ... of non-overlapping 160 MB SSTables, each about 10 times the previous | Low; about 90% of reads touch 1 SSTable | High; data rewritten level by level | Low (about 10%) | Read-heavy, update-heavy data |
| Time-Window (TWCS) | Group SSTables by write-time window (for example 1 day); STCS inside the active window; old windows never merge | Low for time-range reads | Low | Low; whole SSTables drop at TTL | Time series and TTL'd data written in time order |
| Unified (UCS, Cassandra 5.0) | Configurable, density-based sharded compaction that can behave like tiered or leveled | Tunable | Tunable | Tunable | The new general default to evaluate |
The Discord lesson from the read path: when compaction falls behind, SSTables pile up, reads touch more files and get slower, and slower reads leave less CPU and I/O for compaction. That's a vicious cycle. Running compaction harder just competes with live traffic. Discord's engineers took nodes out of rotation to let them compact offline, then brought them back to catch up via hints and repair, one node at a time. They called it a "gossip dance": workable, but toil. Good compaction choice, enough disk and CPU headroom, and bounded partitions prevent this.
LSM maths, briefly. For leveled compaction with fan-out 10, write amplification is roughly 10 times the number of levels, since each byte is rewritten about 10 times per level it descends, while read amplification is about 1 SSTable per level. Size-tiered has write amplification of roughly the number of tiers, but read amplification that grows with tiers. Patrick O'Neil et al.'s "The Log-Structured Merge-Tree (LSM-Tree)" (Acta Informatica, 1996) introduced the structure. RocksDB's tuning guides popularised these amplification trade-offs, and Instagram's "Rocksandra" (2018) swapped Cassandra's storage engine for RocksDB to cut tail latency.
Tunable consistency#
Each request carries a consistency level (CL): how many replicas must respond before the coordinator reports success. With replication factor RF:
| Level | Replicas that must respond | Use |
|---|---|---|
ANY (writes only) | Any node, even just a stored hint | Maximum write availability; the write may not be readable until a replica receives it |
ONE, TWO, THREE | 1, 2 or 3 replicas anywhere | Low latency, highest availability; may read stale data |
LOCAL_ONE | 1 replica in the local DC | Low-latency reads where staleness is fine, without cross-DC traffic |
QUORUM | ⌊RF_total / 2⌋ + 1 across all DCs | Strong-ish consistency in single-DC clusters |
LOCAL_QUORUM | Majority in the local DC | The default choice in multi-DC: strong within the DC, no cross-DC latency |
EACH_QUORUM (writes) | A majority in every DC | Cross-DC durability before acknowledgment; high latency |
ALL | Every replica | Rarely; any one replica down fails the request |
SERIAL, LOCAL_SERIAL | Paxos majority | Lightweight transactions (compare-and-set) |
The overlap rule. If W + R > RF, every read set overlaps every write set in at least one replica. That replica has the latest acknowledged write, and the coordinator returns the highest timestamp it sees. With RF=3, QUORUM writes (2) plus QUORUM reads (2) is 4 > 3: read-your-writes and monotonic reads, for a single client with a correct clock. ONE plus ONE gives 2 ≤ 3, so reads may miss the latest write: eventual consistency, but faster and more available. ALL writes plus ONE reads also satisfies the rule, but any replica failure blocks writes. See Quorums and Leaderless Replication.
Quorums don't give linearizability on their own. LWW by timestamp means clock skew between writers can make an older write win. A failed QUORUM write may still have reached one replica, and later be spread by read repair. That's a "partial write" that the client was told failed. Concurrent writers to the same cell aren't serialised. So Cassandra is AP by default, tunable towards C per query (CAP Theorem and PACELC). In PACELC terms, it's PA/EL: during partitions it favours availability, and otherwise it favours latency.
Transactions and atomicity. Cassandra has no multi-row ACID transactions.
- A write to one partition (any number of rows and cells) is atomic and isolated: readers see all of it or none.
- Logged batches guarantee that all statements eventually apply, across partitions or tables, via a batch log. They're not isolated, and they're expensive. Use them for keeping denormalised tables in step, not for bulk loading.
- Lightweight transactions (LWT),
INSERT ... IF NOT EXISTSandUPDATE ... IF col = ?, run Paxos among the replicas for that partition. That gives linearizable compare-and-set on a single partition, at about 4 round trips (improved by Paxos v2 in Cassandra 4.1), so expect several milliseconds and much lower throughput. Use them for uniqueness (claiming a username), not for hot paths. - Counters are a special column type supporting increments. They're not idempotent on retry, so a timeout makes the client unsure whether the increment applied.
General-purpose ACID transactions based on the Accord protocol (CEP-15) are being developed for a future major release. Check maturity before relying on them.
Gossip, failure detection, hinted handoff and repair#
A masterless database needs every node to know the cluster's state, and to heal divergence without a leader. Cassandra uses four cooperating mechanisms.
1. Gossip (membership and state).
- Every second, each node picks 1–3 peers, and exchanges state about every node it knows: status (joining, normal, leaving), tokens, schema version, load, DC and rack.
- Each node's state carries a generation (set when that node starts) and a version, a counter that increases as its state changes. A receiver keeps whichever (generation, version) pair is newer, so stale gossip is ignored. Collectively, these per-node versions behave like a vector of logical clocks for cluster state.
- Seed nodes are a configured list, two or three per DC, that new nodes contact to bootstrap. Gossip is biased to include seeds regularly. Seeds act as well-known meeting points, so the cluster doesn't split into isolated islands of gossip.
- Information spreads epidemically in O(log N) rounds. A 1,000-node cluster converges in a few seconds (Failure Detection and Gossip).
2. Failure detection (phi accrual). Rather than a fixed "dead after 10 s" timeout, each node runs a φ (phi) accrual failure detector (Hayashibara et al., "The φ Accrual Failure Detector", SRDS 2004) per peer.
- The detector records the inter-arrival times of gossip heartbeats.
- From them, it computes φ = −log₁₀(probability that a heartbeat this late would still arrive).
- When φ exceeds
phi_convict_threshold(8 by default, roughly a 1-in-10⁸ chance of a false conviction under the model), the node convicts that peer as down, and stops routing requests to it.
Conviction is local and reversible: as heartbeats resume, the peer is marked up. A down node stays in the ring. Cassandra doesn't rebalance data automatically when a node dies, because most outages are restarts or blips, and rebalancing terabytes for a 5-minute outage would be harmful. Permanently removing or replacing a node is an explicit operator action (nodetool decommission, removenode, or starting a replacement with replace_address_first_boot).
3. Hinted handoff (short outages). When a coordinator can't reach a replica during a write, it stores a hint locally: the mutation plus its target. The write can still succeed if the consistency level is met by the other replicas. When gossip reports the replica back up, the coordinator replays the hints to it.
- Hints are kept for at most
max_hint_window(3 hours by default). After that, the coordinator stops collecting hints for that node, which must then be fixed by repair. - Hints are an optimisation for fast recovery, not a guarantee. A coordinator can crash with undelivered hints.
CL=ANYaccepts a write even when only a hint was stored, which is maximally available but not readable until delivered.
4. Read repair and anti-entropy repair (convergence).
- Read repair: during a read at QUORUM, the coordinator asks one replica for data and the others for digests (hashes). If they disagree, it fetches full data, computes the merged newest version, returns it, and writes the newest version back to the stale replicas, blocking until they're repaired, for monotonic quorum reads. This heals data that's read. (The old probabilistic background read repair,
read_repair_chance, was removed in Cassandra 4.0.) - Anti-entropy repair (
nodetool repair) compares replicas for whole token ranges using Merkle trees: hash trees over ranges of data. Replicas exchange trees, find the differing leaves, and stream only those ranges. This heals data that's never read, and data missed beyond the hint window. Incremental repair marks SSTables as repaired, so later runs only process new data. It's much faster, and stable since Cassandra 4.0.
Operators schedule repairs with tools like Cassandra Reaper, which splits ranges into small segments and runs them continuously, because repair must finish within gc_grace_seconds (next section).
Gossip, repair and membership, in depth#
Bootstrapping a node.
- A new node contacts the seeds and learns the ring.
- It picks its tokens (vnodes, using the allocation algorithm).
- It streams the data for its new ranges from the current replicas.
- It joins as
NORMALonce complete. During streaming, writes for those ranges go to both old and new owners, so nothing is missed.
Streaming time is dominated by data volume per node. At about 100–200 MB/s of effective streaming throughput, a node with 2 TB takes roughly 3–6 hours to bootstrap or replace. That's a practical reason to keep per-node density moderate (often 1–2 TB for Cassandra; ScyllaDB handles more per node). Cassandra 4.0's zero-copy streaming sends entire SSTables when possible, which is much faster.
Decommissioning streams a node's data to its successors, then leaves. Replace brings up a new node, which takes over a dead node's tokens and streams their data from the surviving replicas.
Why repair is non-negotiable. Without repair:
- replicas drift: writes that missed a replica beyond the hint window are never copied;
- deleted data can come back (see tombstones);
- a later failure can expose stale replicas as the only copies.
A healthy cluster runs repair on every range at least once per gc_grace_seconds (10 days by default). Large clusters often use incremental repair continuously, plus full repairs periodically.
Clock discipline. LWW relies on timestamps, so NTP or chrony on every client and node is mandatory. A client whose clock runs 5 s fast issues writes that "win" over correct, later writes for 5 s. Its deletes can also mask newer writes. Some teams use server-side timestamps only (the coordinator assigns them), or use LWTs for the few cells that need ordering guarantees.
Speculative retry. To cut tail latency, the coordinator sends a read to an extra replica if the first doesn't respond within a percentile (speculative_retry = 99p by default), taking whichever answers first. That's similar to "The Tail at Scale" hedged requests (Dean and Barroso, CACM 2013). It turns one slow replica from a p99 spike into a small amount of extra load.
Snitches tell Cassandra the topology: which DC and rack each node is in. GossipingPropertyFileSnitch (each node declares its DC and rack, then gossips it), or the cloud-specific snitches. The dynamic snitch routes reads away from replicas with poor recent latency.
Tombstones#
Because SSTables are immutable, a delete can't erase data in place. Instead, Cassandra writes a tombstone: a marker with a timestamp saying "data older than this, at this scope, is deleted". Tombstones can cover:
- a cell (
DELETE col FROM ..., or setting a column tonull); - a row;
- a range of clustering keys (
DELETE ... WHERE pk = ? AND ck > ?); - a whole partition.
A TTL expiry turns a cell into a tombstone when it expires.
Why tombstones must linger. Suppose a delete reaches replicas A and B, but C is down. If A and B purged the tombstone at the next compaction, C, when it returns, still holds the old value. Repair or read repair then treats C's value as the newest surviving data, and copies it back to A and B. The deleted data is resurrected ("zombie data"). So tombstones are kept for gc_grace_seconds (10 days by default). Only after that, and once the data they shadow is in the same compaction, can they be purged. The rule follows: every replica must be repaired within gc_grace_seconds, or deletes can come back.
Why tombstones hurt reads. A read must scan past tombstones to find live data. A partition with 10 live rows and 200,000 tombstones makes every read process 200,000 markers: slow, heap-hungry and GC-heavy. Cassandra warns when a single query scans more than 1,000 tombstones (tombstone_warn_threshold), and aborts it at 100,000 (tombstone_failure_threshold).
Tombstone anti-patterns and fixes:
- Queue or "inbox then delete" tables. Insert a job, then delete it when done. The head of the partition becomes a graveyard, and reads of "the next job" scan ever-growing tombstones. Don't use Cassandra as a queue. Use Kafka or SQS. If you must, partition by time bucket and drop whole buckets.
- Writing nulls. Inserting
nullfor absent fields (common with ORMs or prepared statements binding every column) creates a cell tombstone per null. Leave columns unset instead. Drivers support unset values. - Frequent overwrites of collections.
UPDATE ... SET tags = {...}(a full overwrite of a collection) writes a range tombstone, and then the new values. Usetags = tags + {...}for appends. - Wide deletes followed by range reads, for example deleting old messages one by one and then paging the partition.
- TTL'd data is fine if it's written in time order with TWCS, because whole SSTables expire and are dropped without per-row tombstone scanning. With STCS or LCS, TTL'd data mixed with live data lingers.
ScyllaDB and the Discord migration#
ScyllaDB is a C++ reimplementation of Cassandra's data model, CQL protocol and SSTable formats. It was founded by the creators of the KVM hypervisor, and is built on their Seastar framework. Key design differences:
- No JVM, so no garbage-collection pauses. Cassandra's heap and GC tuning (G1, ZGC, heap sizes) is a perennial source of p99 spikes. ScyllaDB manages memory itself.
- Shard-per-core. Each CPU core owns a slice of the node's data, plus its own memtables, cache, and network and disk queues. Cores communicate by message passing, with no locks and no shared state. That uses modern many-core machines efficiently, so far fewer, larger nodes do the same work.
- Self-tuning schedulers. Compaction, streaming and repair run under an I/O and CPU scheduler that gives foreground queries priority, which reduces the "compaction competes with traffic" problem.
- Faster repair and streaming, and features such as tablets (dynamic, per-table range splitting) in newer versions, offered under ScyllaDB's own licensing and cloud terms.
Discord's story (2023). By early 2022, Discord stored trillions of messages on 177 Cassandra nodes, using the bucketed schema above, with QUORUM reads and writes. Two problems compounded each other:
- Hot partitions from popular channels. Live reads for a channel hit its newest bucket. A huge server's
@everyoneannouncement sends thousands of members to read the same partition on the same 3 replicas. Because QUORUM reads needed 2 of those 3 nodes, and those nodes also hosted thousands of quieter channels, one hot channel slowed unrelated queries on shared nodes. More buckets wouldn't help: the data itself was popular. - Operational fragility. Compaction fell behind (the vicious cycle above), demanding the manual "gossip dance". JVM GC pauses caused latency spikes, sometimes bad enough to require reboots.
Their solution had two independent parts:
- ScyllaDB for the storage layer: same schema, no GC, and shard-per-core efficiency. The result was 72 nodes instead of 177.
- Rust "data services" between the API and the database, to cut how many reads reach storage. Requests are routed by consistent hashing on
channel_id, so all requests for one channel meet in one service instance. That instance does request coalescing: the first request for a given message starts the database query, and identical requests arriving while it's in flight subscribe to the same result, instead of issuing their own queries. Thousands of reads become one.
Why coalescing instead of a cache? A cache would also absorb requests that arrive after the first query finished, but it brings TTLs, invalidation and staleness. Coalescing never serves an old result: it only merges requests that overlap in time. Discord gave up some hit rate for much simpler consistency. The data services shipped while Cassandra was still primary, and they reduced hot-partition incidents even before the migration finished.
The outcome reported: p99 read latency fell from a 40–125 ms range to a steady 15 ms, on fewer than half the nodes. The broader lesson is that a faster database and less database work solve different problems. ScyllaDB made each read cheaper; routing plus coalescing reduced the number of reads. This is the same insight as Scaling Reads: hot keys are a traffic problem, solved above the database.
Hard limits and numbers to know#
| Dimension | Practical guidance | Why |
|---|---|---|
| Partition size | Keep under ~100 MB and ~100,000 rows (hard cell limit ~2 billion) | Compaction, repair and reads handle a partition as a unit; huge partitions cause heap pressure and slow streaming |
| Cell / blob size | Keep values under ~1 MB (hard limit 2 GB, never approach it) | Large cells bloat memtables and SSTables; put blobs in object storage and store a pointer |
| Collections | Hundreds of elements, not millions | Collections are read whole; they're not a substitute for clustering rows |
| Data per node | ~1–2 TB for Cassandra, more for ScyllaDB | Bootstrap, replace and repair times grow with density |
| Write latency | p50 under 1 ms on the replica, 2–5 ms at QUORUM in one DC | Append-only path: commit log plus memtable |
| Read latency | p50 1–5 ms, p99 10–50 ms, depending on SSTables per read and cache | Read cost depends on the LSM shape |
| Throughput | Roughly 10k–50k writes/s per Cassandra node on modern hardware; ScyllaDB often several times that | Depends on row size, CL and compaction |
| Cluster size | Tens to low thousands of nodes per cluster | Gossip and schema agreement are fine at this scale; Apple runs very large fleets as many clusters |
| Tables per cluster | Low hundreds at most | Each table has memtable and metadata overhead per node |
Worked capacity example. A chat system ingests 50,000 messages/s at peak. Each message is about 300 bytes on disk after compression and overhead, with RF = 3, kept for 5 years.
- Raw write load: 50k × 3 replicas = 150,000 replica writes/s. At a conservative 15k writes/s per node with compaction headroom, that's about 10 nodes for throughput alone.
- Storage: average traffic is perhaps a third of peak, so ~17k msgs/s × 86,400 s × 365 × 5 ≈ 2.7 × 10¹² messages. × 300 B ≈ 800 TB logical, × 3 replicas ≈ 2.4 PB.
- At ~1.5 TB per node with 50% free space reserved for compaction (STCS needs more; LCS and UCS less), that's about 1,600 nodes on Cassandra, or a few hundred dense ScyllaDB nodes.
Storage, not throughput, sets the size. That is why message stores tier old data, compact aggressively, or move cold history to cheaper storage.
When to Use It#
Pick Cassandra (or ScyllaDB) when most of these hold:
- Write-heavy, high-volume data with known access patterns. Examples: messages, events, IoT readings, activity logs, time series, audit trails and feature-store lookups. Tens of thousands to millions of writes per second, on terabytes to petabytes.
- Queries go to a partition. "Recent messages in channel X", "readings for sensor Y yesterday", "orders of user Z". Every hot query names the partition key, and reads a slice ordered by the clustering keys.
- Availability beats strict consistency. The product tolerates eventual consistency, or tunable QUORUM within a region, and must accept writes even during node or AZ failures.
- Multi-datacenter, active-active writes. NetworkTopologyStrategy and LOCAL_QUORUM give low local latency in each region, with asynchronous cross-region replication and no single primary region.
- Linear horizontal scale with no single point of failure. Add nodes to add capacity, and no node is special.
- Large TTL'd time-series data, with TWCS dropping whole SSTables as they expire.
Pick something else instead when:
- You need ad-hoc queries, joins or aggregations. Use PostgreSQL at moderate scale, or a warehouse or OLAP store (ClickHouse, BigQuery, Druid) for analytics.
- You need multi-row ACID transactions. Payments, inventory and balances. Use PostgreSQL, or a distributed SQL database (CockroachDB, Spanner, YugabyteDB), as in Distributed Transactions.
- The scale is moderate. Under ~10k writes/s and a few TB, a single PostgreSQL primary with replicas is simpler and more flexible.
- You want managed, serverless key-value access on AWS. Use DynamoDB: it has a similar partition and sort key model and no operations work.
- Full-text or faceted search. Use Elasticsearch, fed from Cassandra by CDC or dual writes.
- Queue or work-list semantics. Use Kafka or SQS, to avoid tombstone graveyards.
- High-cardinality metrics with downsampling. Use a purpose-built time-series database, though Cassandra-backed TSDBs exist.
When NOT to Use It#
- Access patterns are unknown or changing weekly. Every new query may need a new table and a backfill. Early-stage products iterate faster on a relational database.
- The read pattern is "scan everything" or "filter by any column".
ALLOW FILTERINGon a large table is a full-cluster scan. - Strong consistency on every operation. Running everything at
ALLor with LWTs gives you a slow, less-available CP system. Pick a CP database designed for it. - Heavy delete or update churn on the same partitions. That creates tombstone and compaction problems.
- Small team, no operations capacity, and self-hosting. Repair, compaction tuning, JVM tuning, bootstrap and streaming all need expertise. Choose a managed offering, or another database.
- Huge blobs (images, video). Store them in S3 or GCS, and keep only the metadata in Cassandra.
How to Implement It#
- List access patterns first. For each, give the query, the expected QPS, the latency target, the row count per result, and the ordering. This drives every table (Data Modeling).
- Design one table per query.
- Choose a partition key that spreads load evenly, and bounds partition size; add a time bucket if needed.
- Choose clustering keys for the order you read.
- Denormalise freely, and keep the copies in sync with logged batches or an event pipeline.
- Size partitions and the cluster. Estimate rows per partition per bucket, bytes per row, write rate × RF, and the total storage including compaction headroom.
- Pick replication and consistency.
- Use NetworkTopologyStrategy with RF = 3 per DC.
- Default to LOCAL_QUORUM for reads and writes when you need read-your-writes.
- Use LOCAL_ONE for non-critical, high-volume reads.
- Reserve LWTs for the rare compare-and-set.
- Pick a compaction strategy per table. TWCS for TTL'd time series, LCS for read-heavy data with updates, UCS (Cassandra 5.0) as the modern default, and STCS for write-heavy, append-only data.
- Configure the drivers.
- Use token-aware, DC-aware load balancing, so requests go straight to a replica in the local DC.
- Use prepared statements, and leave values unset rather than null.
- Use idempotent writes, so retries and speculative execution are safe.
- Page large reads with
fetch_size.
- Operate it.
- Repair continuously with Reaper, well within
gc_grace_seconds. - Monitor pending compactions, SSTables per read, tombstones scanned, p99 latency per table, dropped mutations, hints, disk usage (keep under 50–70%) and GC pauses.
- Repair continuously with Reaper, well within
- Plan growth. Add nodes before disks pass ~60%, and add capacity ahead of peaks. Bootstrap streams data and adds load.
-- Messages: one partition per (channel, 10-day bucket), newest first
CREATE TABLE chat.messages (
channel_id bigint,
bucket int, -- (message_ts - DISCORD_EPOCH) / 10 days
message_id bigint, -- Snowflake: time-ordered, unique
author_id bigint,
content text,
attachments list<text>, -- object-storage URLs, not bytes
PRIMARY KEY ((channel_id, bucket), message_id)
) WITH CLUSTERING ORDER BY (message_id DESC)
AND compaction = {'class': 'UnifiedCompactionStrategy'}
AND default_time_to_live = 0
AND gc_grace_seconds = 864000; -- 10 days; repair must finish within this
-- Latest 50 messages in a channel's current bucket
SELECT message_id, author_id, content FROM chat.messages
WHERE channel_id = ? AND bucket = ? LIMIT 50;
-- Page older: messages before a cursor
SELECT message_id, author_id, content FROM chat.messages
WHERE channel_id = ? AND bucket = ? AND message_id < ? LIMIT 50;
-- Compare-and-set (Paxos LWT): claim a username exactly once
INSERT INTO chat.usernames (username, user_id) VALUES (?, ?) IF NOT EXISTS;| Technology | Fits when |
|---|---|
| Apache Cassandra (OSS) | You self-host, want the open-source ecosystem, and have operations skills; versions 4.1 and 5.0 bring SAI, UCS and tries |
| ScyllaDB | Same CQL model, but you want lower p99 (no GC) and fewer, denser nodes; self-hosted or ScyllaDB Cloud |
| DataStax Astra DB | Managed, serverless Cassandra with vector search; pay per use |
| Amazon Keyspaces | AWS-managed, Cassandra-compatible (CQL), serverless; some features differ (check LWT, batch and TTL support) |
| Azure Cosmos DB for Apache Cassandra | You're on Azure and want a CQL-compatible API with Cosmos's global distribution |
| Amazon DynamoDB | AWS-native, fully managed key-value or wide-column store with a similar modelling discipline; no CQL |
| Google Bigtable / HBase | A wide-column store with strongly consistent single-row operations and range scans by row key; Hadoop or GCP ecosystems |
| Cassandra Reaper, Medusa, cassandra-stress, nosqlbench | Repair scheduling, backups to object storage, load testing |
| Spark Cassandra Connector | Bulk analytics or backfills over Cassandra tables without hurting online latency (run it against an analytics DC) |
Trade-offs#
| Option | Pros | Cons | Pick when |
|---|---|---|---|
| Cassandra | Masterless, linear write scale, multi-DC active-active, tunable CL, mature OSS | Query-first modelling, no joins, eventual consistency by default, JVM GC tails, heavy operations (repair, compaction) | Huge write volume with known queries, and you can operate it |
| ScyllaDB | Same model and CQL, shard-per-core, lower p99, fewer nodes, faster repair | Different licensing and vendor dependence, smaller community, the same modelling constraints | You've hit Cassandra's latency or operations limits, or want fewer nodes |
| DynamoDB | Zero operations, serverless scaling, single-digit-ms latency, transactions, streams | AWS lock-in, cost at sustained high throughput, 400 KB items, hot partition limits | AWS shop that wants managed key-value at any scale |
| PostgreSQL (+ Citus) | SQL, joins, ACID, flexible queries, rich ecosystem | Single-writer limits; sharding adds complexity | Moderate scale, or relational and transactional data |
| Bigtable / HBase | Strong per-row consistency, ordered range scans, integrates with analytics | Single-region writes (Bigtable replication is eventual), HBase operations complexity | Range-scan-heavy, wide-row analytics on GCP or Hadoop |
| CockroachDB / Spanner | Distributed SQL with serializable transactions, multi-region | Higher write latency (consensus), cost, fewer writes/s per dollar | You need global ACID and SQL more than raw write throughput |
Common Pitfalls#
- Modelling like a relational database: normalised tables plus client-side joins, or
ALLOW FILTERINGin production. Each query should hit one partition of one table. - Unbounded partitions: partitioning by
user_idfor an event log that grows forever, or bychannel_idwithout a time bucket. - Low-cardinality partition keys: partitioning by
countryorstatus, so a few nodes hold all the data and serve all the load. - Using Cassandra as a queue, or deleting heavily and then range-reading. That creates tombstone storms past the 100k failure threshold.
- Not running repair, or running it less often than
gc_grace_seconds. Replicas drift, and deleted data resurrects. - Writing nulls from prepared statements, which creates a silent tombstone per column.
- Overusing LWTs. Paxos needs four round trips, so contended LWTs time out. Mixing LWT and non-LWT writes on the same cells breaks the guarantees.
- Large unlogged batches across partitions as a "bulk load" trick. That overloads the coordinator. Unlogged batches only help within one partition.
- Clock skew between clients, which silently reorders LWW writes. Run NTP everywhere.
- Disks over 70% full with STCS. Compaction needs free space, and can't complete without it.
- Secondary indexes (2i) on high-cardinality or very low-cardinality columns. They query every node. Prefer SAI (5.0), or a denormalised table.
- Too many tables, or materialised views in production. Views are still experimental, and can silently drift from the base table.
Real-World Examples#
- Discord: message storage on Cassandra. They started in 2017 with 12 nodes, and grew to 177 nodes holding trillions of messages. They then migrated to 72 ScyllaDB nodes, and added Rust data services with request coalescing (described above).
- Netflix: a long-time large Cassandra user, for viewing history, member data and many other services, running multi-region active-active. Netflix built and open-sourced tooling around it (Priam for operations, plus later data-abstraction layers on top of Cassandra).
- Apple: publicly described as running one of the largest Cassandra deployments, with a very large node count across many clusters. Apple engineers contribute heavily to the project.
- Instagram: used Cassandra for feeds, inbox and fraud data. Their engineers built Rocksandra (2018), which replaced Cassandra's storage engine with RocksDB, and reported large p99 read-latency reductions, partly from removing JVM GC pressure from the storage path.
- Uber, Spotify, Bloomberg and many others have publicly discussed Cassandra deployments for high-write workloads (for example, Spotify's personalisation data). Details vary by year and team, so verify a specific claim before quoting numbers.
Case studies that use this pattern#
- Chat System: message history partitioned by (conversation, time bucket), the Discord pattern.
- News Feed: precomputed feeds and post storage at write-heavy scale.
- Metrics Monitoring: time-bucketed series with TTL and TWCS.
- Ad Click Aggregator: high-volume event writes and aggregated counters.
- Key-Value Store: Dynamo-style replication, quorums, hinted handoff, Merkle-tree repair; Cassandra is the reference implementation.
- Ticket Booking: seat maps partitioned by (event, section), with the booking itself in a transactional store.
- Live Comments: comments per video partitioned by time bucket.
In the Interview#
Deep Dive: Repair, tombstones and zombie data, from first principlesShow
The invariant repair protects. Every write in Cassandra eventually reaches all RF replicas, or the cluster forgets it consistently. Three mechanisms aim at this, at different time scales:
- hinted handoff: seconds to hours;
- read repair: whenever data is read at a CL above ONE;
- anti-entropy repair: days.
Only anti-entropy repair is complete: it compares every range, whether or not it's read or hinted. That is why it's the backstop for every guarantee.
How a Merkle-tree repair works:
- The repair coordinator chooses a token range and its replicas.
- Each replica runs a validation compaction. It reads all data in the range, and builds a Merkle tree: leaves are hashes of sub-ranges (Cassandra builds trees of up to 2¹⁵ leaves per range by default), and each parent hashes its children.
- Trees are sent to the coordinator and compared top-down. Equal roots mean the range is identical, so it's done in one comparison. Otherwise, it descends only into the differing subtrees.
- For each differing leaf, the replicas stream that sub-range to each other, and the newer timestamps win when it's merged.
Cost: a full repair reads every byte on every replica, so it competes with live traffic for disk and CPU. A tree's granularity is fixed: with 2¹⁵ leaves over a 500 GB range, each leaf covers ~15 MB. One differing cell causes ~15 MB to stream (overstreaming). Subrange repair (Reaper splits ranges into many small segments) reduces both the per-session cost and overstreaming.
Incremental repair tracks which SSTables have already been repaired, so each run validates only new, unrepaired data. Before 4.0, it had correctness bugs: anticompaction issues, and repaired and unrepaired data mixing. Cassandra 4.0 reworked it (CASSANDRA-9143), and it's now the recommended routine repair. Periodic full repairs still catch bit rot or anything incremental might miss.
Preview repair (nodetool repair --preview) computes the differences without streaming, which is useful to measure how out of sync a cluster is.
The gc_grace contract, made precise. Let a delete at time t write tombstone T on replicas , with C missing it. Tombstones become purgeable after t + gc_grace_seconds.
- If a repair including C starts after t and completes before t + gc_grace, T is copied to C, and all three later purge it together. That's safe.
- If no such repair occurs, A and B purge T, and the next repair finds C's old value with no tombstone shadowing it. The repair copies it to A and B. The deleted data is back, often months later, and in a form that's hard to trace.
Hence the operator rule: schedule repair so every range completes at least once every gc_grace window, with margin. Default 10 days means "repair weekly". Lowering gc_grace (say, to 1 day on a TTL-only table) is safe only if you never issue explicit deletes, or you can guarantee repair inside that window. Tables with TTL only, and no explicit deletes, can often use small gc_grace, because every replica computes TTL expiry by itself from the cell's write time.
Why reading tombstones is so expensive. For a slice query WHERE pk = ? LIMIT 50, the storage engine merges iterators from the memtable and each SSTable, in clustering order. Every tombstone in the slice has to be materialised, both to shadow older cells in other SSTables and to be returned to the coordinator for reconciliation. Replicas can't drop tombstones in their response, because another replica may still hold the shadowed value.
A partition where the first 100,000 clustering positions are tombstones makes every "latest 50" read process 100,050 cells across replicas, and Cassandra aborts the query at tombstone_failure_threshold.
Three ways out:
- Model deletions away: time buckets, so old buckets are never read, plus TTL with TWCS, so whole SSTables expire.
- Range tombstones instead of many cell tombstones. One
DELETE WHERE pk = ? AND ck < Xwrites a single marker covering a range. - Unsafe tombstone purging, carefully.
unchecked_tombstone_compactionandtombstone_thresholdlet single-SSTable compactions drop tombstones once gc_grace has passed. But tombstones can only be purged if no older SSTable might still contain the data they shadow, which is why TWCS with time-ordered data makes this efficient and STCS often doesn't.
Debugging zombie data and tombstone pain:
nodetool tablestats(tombstones per slice, SSTables per read, partition size percentiles);nodetool tablehistograms;- the warning logs naming the query and partition that scanned too many tombstones;
sstablemetadatafor droppable-tombstone estimates;- tracing (
TRACING ONin cqlsh), which shows each replica's SSTable merges and tombstone counts for one query.
Deep Dive: Multi-DC operations, failure scenarios and consistency in practiceShow
Topology. A typical production layout is two or three DCs (regions), RF = 3 in each, with racks mapped to AZs. NetworkTopologyStrategy places each DC's three replicas on three different racks, so losing one AZ leaves two replicas per range in that DC. LOCAL_QUORUM (2 of 3) still succeeds.
Writes arrive at a coordinator in the local DC. It sends to its local replicas, and to one forwarding replica in each remote DC, which relays to its peers. That saves WAN bandwidth: one cross-region copy per DC instead of three.
Consistency levels across regions.
| Level | Acks needed (RF=3 in 2 DCs) | Latency | Survives |
|---|---|---|---|
| LOCAL_ONE | 1 local | ~1 ms | Anything but losing all local replicas |
| LOCAL_QUORUM | 2 local | ~2–5 ms | One local node or AZ down; whole remote DC down |
| EACH_QUORUM (writes) | 2 in every DC | Local plus WAN RTT (~60–150 ms) | One node per DC; not a DC outage |
| QUORUM | 4 of 6 global | WAN RTT | Fewer combinations; avoid across DCs |
| ALL | 6 | WAN RTT, slowest replica | Nothing down |
| SERIAL / LOCAL_SERIAL | Paxos quorum, global or local | 4 RTTs (Paxos v1), fewer with Paxos v2 in 4.1 | Same as the underlying quorum |
The usual choice is LOCAL_QUORUM writes plus LOCAL_QUORUM reads. That gives read-your-writes within a region, and eventual consistency across regions (lag is typically tens to hundreds of ms, and grows during WAN incidents). Users stuck to one region see consistent data. A user who fails over to another region may briefly see stale data, which is the PA/EL choice from CAP and PACELC, made explicitly. See Multi-Region Data for patterns like home regions and sticky routing.
Failure scenarios and what actually happens:
- One node dies (hardware).
- Gossip convicts it within seconds (φ > 8).
- Coordinators stop sending it reads, and store hints for its writes.
- LOCAL_QUORUM still succeeds with 2 of 3, and latency barely changes, thanks to the dynamic snitch and speculative retry.
- The operator replaces it. The new node streams its ranges from the surviving replicas, about 3–6 h for 2 TB.
- Run repair afterwards to catch anything hints missed.
- A whole AZ fails. One rack per range is gone, so every range still has 2 of 3 local replicas: LOCAL_QUORUM is fine. Hints accumulate for 3 h on every coordinator, with real disk usage. After the AZ returns, hint replay plus repair heal it. If it's down longer than the hint window, repair carries the load.
- A network partition isolates a DC. Each side keeps serving LOCAL_QUORUM traffic, both accepting writes. Cross-DC replication queues as hints, up to the window. After healing, hints replay and repair converges, with LWW resolving concurrent writes to the same cell. There are no conflicts in the user-visible sense, only lost updates: the write with the older timestamp silently loses. If the business can't tolerate that for some data, route its writes to a single home region, or use LWT at SERIAL (which then fails during the partition, i.e. it's CP).
- Slow node (bad disk or GC storm). This is worse than a dead node, because it's not convicted. The dynamic snitch steers reads away. Speculative retry hedges. Writes still wait for 2 of 3 acks, so one slow replica doesn't hurt QUORUM writes much, but two slow replicas in the same range do. Monitor per-node p99, and remove misbehaving nodes quickly.
- Coordinator overload. Large multi-partition
INqueries, unlogged batches across partitions, and big pages concentrate work on one coordinator. Use token-aware drivers, so the coordinator is a replica, and keep each request single-partition.
Write timeouts are ambiguous. A WriteTimeoutException at QUORUM means fewer than 2 acks arrived in time, not that the write failed. It may already be on one replica, and will propagate via hints or repair. So:
- Retries must be idempotent. Cassandra writes are naturally idempotent when you write the same values with the same primary key, but not counters, list appends or non-deterministic timestamps.
- Client timestamps (set once per logical write) make retries collapse to one version.
- There's no rollback. Unlike a SQL transaction, a "failed" write may become visible later. Design the UX for it, e.g. client-generated message IDs, so a retry produces the same row.
Lightweight transactions in practice. INSERT ... IF NOT EXISTS and UPDATE ... IF col = ? run Paxos among the partition's replicas: prepare/promise, read, propose/accept, then commit. Paxos v1 needs four round trips. Under contention, proposals collide and retry, so the latency of contended LWTs climbs steeply. Paxos v2 (Cassandra 4.1, CEP-14) cuts the round trips, and improves behaviour under contention.
Rules:
- Use LWTs for rare, low-contention compare-and-set operations: unique usernames, idempotency keys, leases.
- Never mix LWT and non-LWT writes to the same cells. The non-LWT writes bypass Paxos ordering.
- Read with SERIAL when you need to see in-progress Paxos state.
For high-contention ordering (seat inventory, balances), use a transactional store (Dealing with Contention).
Accord (CEP-15) is a leaderless, multi-partition transaction protocol, developed by Apple and DataStax engineers and others in the community, and targeted at a future Cassandra release. It aims at strict-serializable multi-key transactions in one round trip in the common case. Treat it as emerging, and check the release notes before relying on it in a design.
Backups. Snapshots (nodetool snapshot) are hard links to immutable SSTables. They're instant and cheap, and get uploaded to object storage by tools like Medusa. Point-in-time recovery comes from snapshots plus archived commit logs. Because SSTables are immutable, incremental backups simply copy new SSTables. Restores are per node, and must respect token ownership, which is a reason to practise them (Disaster Recovery).
Deep Dive: Hot partitions, ScyllaDB internals and capacity planning at scaleShow
Why hot partitions are structural. Consistent hashing spreads keys evenly, not load. If one channel receives 5% of all reads, those reads land on exactly RF nodes, however big the cluster. Adding nodes helps only the other 95%. The maths: with N = 100 nodes and RF = 3, a uniform workload puts 3% of traffic on each node (each node is a replica for 3% of the ranges). One key with 5% of the reads adds 5% ÷ 3 ≈ 1.7% of total traffic to each of its 3 replicas at LOCAL_ONE, or 3.3% each at QUORUM (2 of 3 replicas per read). That more than doubles their load, and their latency spikes. Every other partition on those 3 nodes suffers too. That is Discord's "unrelated queries got slow" symptom.
Mitigations, ordered by how early they cut the load:
-
Above the database:
- a CDN or edge cache for public content;
- an application cache with short TTLs (Caching Strategies);
- request coalescing keyed by query, for in-flight deduplication (Discord);
- consistent-hash routing, so coalescing actually sees the duplicates.
-
Consistency level: LOCAL_ONE for hot, tolerant reads spreads them over all 3 replicas, instead of requiring 2 per read.
-
Data model:
- split the partition with a sub-bucket (
(channel_id, bucket, shard), where shard = hash(message_id) mod k), and read with k parallel queries plus a merge; - replicate the hot data into k copies, and read a random one.
Both trade read fan-out or write amplification for spread.
- split the partition with a sub-bucket (
-
Rate limiting abusive clients at the gateway (Rate Limiting).
Hot writes (a counter for a viral post) need different tools: in-memory aggregation, then periodic flushes, or sharded counters summed on read (Scaling Writes).
Request coalescing, precisely. A coalescer holds a map from query key to a future/promise.
- On a request, if the key is present, await the existing future.
- Otherwise, insert a new future, run the query, complete the future with the result (or error), and remove the key.
Two subtleties:
- Errors propagate to every waiter. Avoid amplifying a transient failure by retrying inside the shared task, with backoff.
- Removal must happen on completion, or later requests receive stale data. That is exactly why coalescing has no invalidation problem.
The hit rate equals the fraction of requests arriving during an in-flight query. That's low for cold keys, and very high for hot ones, which is exactly where it matters. Routing by consistent hash on channel_id ensures all duplicates reach the same process. Without that, N instances each issue their own query, and coalescing only divides the load by N.
ScyllaDB internals in more depth:
-
Seastar's shared-nothing model:
- one thread pinned per core;
- each core owns a token sub-range of the node's data, plus its own memtable, row cache, commit-log segment and I/O queues;
- cooperative futures and continuations, instead of blocking threads;
- cross-core work by explicit message passing.
The result is no lock contention, and no cache-line bouncing across cores. With shard-aware drivers, the client sends each request to the exact core that owns the token, skipping an internal hop.
-
Memory management: no JVM, so no stop-the-world collection. ScyllaDB manages its row cache and memtables in its own allocator (log-structured memory with compaction of its own), and uses most of the RAM as cache instead of OS page cache.
-
Schedulers: a CPU scheduler and an I/O scheduler, with shares per class (queries, compaction, streaming, repair). The scheduler measures disk capability at setup (
iotune), then keeps the queue depth just below saturation, so foreground reads keep low latency while compaction uses the leftover bandwidth. Compaction falling behind, Discord's original pain, becomes a controlled backlog instead of a cliff. -
Workload prioritisation and tablets: in recent versions, ScyllaDB can assign different shares to different workloads (OLTP vs analytics). It's also moving from vnodes to tablets, small per-table ranges that the cluster splits, merges and moves dynamically, for faster scaling and balancing.
Is ScyllaDB "just faster Cassandra"? For the same modelling discipline, it typically delivers lower tail latency and higher throughput per node. Several companies have reported large node-count reductions, Discord among them, at 177 → 72. But it doesn't fix bad data models: an unbounded partition or a tombstone graveyard is as harmful in ScyllaDB as in Cassandra. Cassandra 4.x and 5.0 have also narrowed some gaps: a better GC story with ZGC/Shenandoah, trie memtables and BTI SSTables, UCS, zero-copy streaming and faster repair.
The decision tends to hinge on four factors:
- licensing and vendor considerations;
- managed-service choices (Astra vs ScyllaDB Cloud vs Keyspaces);
- existing operational expertise;
- whether p99 latency or node count is your binding constraint.
Capacity planning checklist (the interview version of "how many nodes?"):
- Throughput: peak writes/s × RF ÷ safe writes/s per node. Do the same for reads, at CL fan-out. Take the max.
- Storage: daily ingest × retention × RF × (1 + compaction headroom: 1.0 for STCS, ~0.2–0.3 for LCS/UCS) ÷ usable disk per node.
- Density limits: cap TB per node so replace and repair finish in hours, not days.
- Failure headroom: survive one AZ down (one third of each DC's capacity) at peak, with hints accumulating. Size to about 65% utilisation in normal operation.
- Growth: add nodes in rack-balanced increments (one per rack) well before disks pass 60%, because bootstrapping adds streaming load.
- Validate with cassandra-stress or nosqlbench, using your real schema, row sizes and CL. Synthetic benchmarks with tiny rows mislead.
Worked: 30k writes/s peak, 1 KB rows, RF 3, 1 year, LCS, 2 TB disks. Throughput: 90k replica writes/s ÷ 15k ≈ 6 nodes. Storage: average ~10k/s × 86,400 × 365 × 1 KB ≈ 315 TB logical. × 3 = 945 TB. × 1.25 ≈ 1.2 PB. ÷ 2 TB ≈ 590 nodes, plus failure headroom: ~700. Storage dominates again, which argues for:
- TTL'd retention,
- compression (LZ4 typically gives 2–4× on text),
- tiering cold data to object storage, or
- ScyllaDB's denser nodes.
Key Takeaways#
- Cassandra is a masterless, Dynamo-style, wide-column database. A Murmur3 token ring with vnodes places data, RF copies live on distinct racks per DC, and any node can coordinate.
- Primary key = partition key (placement) + clustering keys (order within the partition). Model one table per query, denormalise freely, and bound partition size (under ~100 MB) with time buckets.
- Writes are cheap: commit log, then memtable, then immutable SSTables. Reads pay the LSM costs (bloom filters, merges, compaction). Choose compaction per table: UCS as the default in 5.0, TWCS for TTL'd time series, LCS for read-heavy data.
- Consistency is per request. W + R > RF (LOCAL_QUORUM for both, at RF 3) gives read-your-writes. LWW timestamps resolve conflicts, so keep clocks in sync. LWT (Paxos) is for rare compare-and-set operations only.
- Healing works in layers: gossip plus phi-accrual detection, hinted handoff (3 h), read repair, and Merkle-tree anti-entropy repair. Repair must complete within gc_grace_seconds (10 days), or deleted data resurrects.
- Tombstones are the classic trap. Avoid queues, null writes and delete-then-scan patterns. Use TTL with TWCS, and buckets.
- Hot partitions are a traffic problem. Discord fixed theirs with ScyllaDB (177 → 72 nodes, p99 to ~15 ms) and Rust data services doing consistent-hash routing plus request coalescing. A faster database and less database work are complementary.
- Pick Cassandra or ScyllaDB for huge, write-heavy, partition-addressed, multi-region data. Pick PostgreSQL, DynamoDB, Elasticsearch, Kafka or a TSDB when you need SQL and transactions, zero operations, search, queue semantics or metric rollups.