Cassandra
Apache Cassandra is an open-source, distributed wide-column database built for huge write volumes and high availability. Data is spread across many nodes with consistent hashing, every node is equal (there's no leader), and each piece of data is replicated to several nodes, often across several data centers. It grew out of Facebook in the late 2000s, combining Amazon Dynamo's approach to distribution with Google Bigtable's storage model.
The properties that define it:
- Leaderless and masterless: any node can accept any read or write. There's no primary to fail over, so losing a node, a rack, or even a whole data center doesn't stop writes.
- Linear horizontal scaling: add nodes and both capacity and throughput grow roughly in proportion. Clusters of hundreds of nodes holding petabytes are common at large companies.
- Write-optimized: writes are appended to a log and an in-memory table, never read-modify-written on disk, so they're cheap and fast.
- Tunable consistency: each query chooses how many replicas must respond, trading consistency for latency and availability.
- Query-first data model: tables are designed around the queries you'll run, with data denormalized so each query reads one partition. There are no joins.
In interviews, Cassandra is the classic answer for write-heavy, append-mostly data at large scale, like chat messages, activity feeds, event logs, IoT readings and time series, and for systems that must stay writable through failures. It's also the reference design for "design a distributed key-value store," so knowing its internals pays off twice.
The Data Model
Cassandra organizes data into keyspaces (which set replication) containing tables. You query it with CQL, which looks like SQL but only allows queries the data model can serve efficiently.
The heart of the model is the primary key, which has two parts:
- Partition key: decides which nodes store the row. All rows with the same partition key live together in one partition on the same replicas.
- Clustering columns: decide the sort order of rows within a partition.
CREATE TABLE messages_by_channel (
channel_id bigint,
bucket int, -- e.g. days since epoch, to bound partition size
message_id timeuuid, -- time-ordered unique ID
author_id bigint,
body text,
PRIMARY KEY ((channel_id, bucket), message_id)
) WITH CLUSTERING ORDER BY (message_id DESC);
-- Latest 50 messages in a channel today: one partition, already sorted
SELECT * FROM messages_by_channel
WHERE channel_id = 918 AND bucket = 20786
LIMIT 50;
Here (channel_id, bucket) is a composite partition key, and message_id is the clustering column. Reading the latest 50 messages touches one partition on one set of replicas and reads rows that are already stored in the right order.
CQL enforces what's cheap. You must give the full partition key, and you can only filter or range-scan on clustering columns in order. A query like WHERE author_id = 42 against this table is rejected unless you add ALLOW FILTERING, which scans every partition in the cluster and doesn't belong on a request path.
Design Tables Around Queries
Because there are no joins and few secondary indexes, the rule is one table per query pattern, with data duplicated as needed. If you also need "messages by author," you create messages_by_author with author_id in the partition key and write each message to both tables.
Writes are cheap, so denormalization is the intended trade: store data the way you'll read it.
Keep Partitions Bounded
A partition lives entirely on its replicas and is read as a unit, so unbounded partitions are the most common Cassandra mistake. A channel with ten years of messages in one partition becomes slow to read, compact and repair. The common guidance is to keep partitions well under about 100 MB and a few hundred thousand rows.
The fix is bucketing: add a time bucket (day, week or month) to the partition key, sized to the write rate. A busy channel might bucket by day, a quiet one by month. Reading recent history then means querying the current bucket and stepping back to older ones as needed.
When you propose Cassandra, write down the table with its partition key and clustering columns, and say how big a partition can get. "Partition by
(channel_id, day), cluster bymessage_id DESC. A very busy channel writes about 100,000 messages a day at 1 KB, so partitions stay around 100 MB at worst." That's the analysis interviewers want to see.
Architecture
The Token Ring
Cassandra places data with consistent hashing. The partition key is hashed (with Murmur3) into a 64-bit token, and the token space forms a ring. Each node owns ranges of the ring. A row's first replica is the node owning its token, and further replicas are the next distinct nodes walking clockwise around the ring.
To spread data evenly and make adding nodes smooth, each node owns many small ranges called virtual nodes (vnodes) rather than one big one (16 per node by default in Cassandra 4.0). When a node joins, it takes small slices from many existing nodes instead of half of one neighbor's data, and when one dies, its load spreads across many survivors.
Replication
The keyspace sets the replication factor (RF), usually 3, per data center:
CREATE KEYSPACE chat WITH replication = {
'class': 'NetworkTopologyStrategy',
'us_east': 3,
'eu_west': 3
};
NetworkTopologyStrategy places replicas on different racks (or availability zones) within each data center, so losing one rack never loses all copies. A component called the snitch tells Cassandra which node is in which rack and data center.
Gossip and Failure Detection
Nodes learn about each other through gossip: every second, each node exchanges state (who's up, who owns which tokens, load) with a few others, so news spreads through the cluster in a few rounds. A phi accrual failure detector turns heartbeat timing into a suspicion level instead of a hard timeout, which avoids flapping on a briefly slow network.
The Coordinator
The client driver sends each request to some node, which becomes the coordinator for it. Drivers are usually token-aware, so they pick a node that is itself a replica, saving a hop. The coordinator computes the replicas for the partition key, forwards the request, and waits for as many responses as the consistency level requires.
How Writes Work
But what is actually happening under the hood? On each replica, a write does two things:
- Append to the commit log on disk, a sequential write for durability.
- Insert into the memtable, an in-memory sorted structure for that table.
Then it acknowledges. No existing data is read, and nothing on disk is modified in place.
When a memtable fills up, it's flushed to disk as an SSTable (sorted string table): an immutable file of rows sorted by partition and clustering key, along with a partition index and a Bloom filter. Over time a table accumulates many SSTables, and compaction merges them in the background, keeping the newest version of each value and dropping data that's been deleted or expired. This is a log-structured merge tree (LSM tree), the same family as RocksDB, LevelDB and HBase.
A few consequences follow:
- Every write is an upsert.
INSERTandUPDATEboth just write new values. Inserting a row that already exists overwrites it silently, with no error. - Conflicts resolve by timestamp. Each cell carries a write timestamp, and when replicas or SSTables disagree, the newest timestamp wins (last write wins). That makes clock synchronization (NTP) important, and it means concurrent writes to the same cell silently lose one of them.
- Deletes are writes too. A delete writes a tombstone, a marker saying "this was deleted at time T." Tombstones are kept for
gc_grace_seconds(10 days by default) so every replica learns about the delete before it's purged; otherwise a replica that missed the delete could bring the data back. - Durability comes mostly from replication. By default the commit log is fsynced periodically (every 10 seconds) rather than on each write, so a write acknowledged by one node could be lost if that node loses power, but it's still on the other replicas.
This design is why Cassandra handles very high write rates: each write is a sequential append plus a memory insert, on each of a few replicas. A single node commonly sustains on the order of tens of thousands of writes per second, and clusters scale that out across nodes.
How Reads Work
Reads are more work than writes. A row's columns may be spread across the memtable and several SSTables, so a replica:
- Checks the memtable.
- For each SSTable, checks its Bloom filter, a compact in-memory structure that says "definitely not here" or "maybe here," to skip files that can't contain the partition.
- For SSTables that might, uses the partition index (with caches) to jump to the partition's location and read it.
- Merges the versions it found, keeping the newest timestamp for each cell and applying tombstones.
How many SSTables a read touches depends on the compaction strategy, which you choose per table:
| Strategy | How it works | Best for |
|---|---|---|
| Size-tiered (STCS) | Merge SSTables of similar size | Write-heavy tables; reads may touch many files |
| Leveled (LCS) | Organize into levels of non-overlapping files | Read-heavy, update-heavy tables; more compaction I/O |
| Time-window (TWCS) | Group SSTables by write-time window, never merge across windows | Time series with TTLs; whole old files expire at once |
| Unified (UCS, Cassandra 5.0) | One tunable strategy spanning the above | General use in newer versions |
Tombstones Hurt Reads
Because deleted data is represented by tombstones until compaction purges them, a workload that deletes heavily can make reads slow. A queue-like table where you insert jobs and delete them when done is the classic trap: reading the "front" of the queue has to skip over thousands of tombstones. Cassandra logs a warning when a query scans more than 1,000 tombstones and aborts it past 100,000 by default.
Using Cassandra as a queue is a well-known anti-pattern. If your design needs a queue, use Kafka or SQS. If you need expiring data, prefer TTLs with time-window compaction, so whole SSTables age out together instead of leaving tombstones scattered through live data.
Tunable Consistency
Every read and write specifies a consistency level: how many replicas must acknowledge before the coordinator answers.
| Level | Meaning (RF = 3) |
|---|---|
ONE |
1 replica |
QUORUM |
Majority of all replicas across all data centers |
LOCAL_QUORUM |
Majority in the coordinator's data center (2 of 3) |
EACH_QUORUM |
Majority in every data center (writes) |
ALL |
Every replica |
The coordinator always sends a write to all replicas. The consistency level only decides how many it waits for. The rest still receive the write, just later.
The key formula is R + W > RF. If the number of replicas you read from plus the number you write to exceeds the replication factor, every read overlaps with the latest successful write on at least one replica, so the read sees it. With RF = 3, QUORUM writes (2) plus QUORUM reads (2) gives 4 > 3. In a multi-region deployment, LOCAL_QUORUM for both gives the same guarantee within a region while avoiding cross-region latency on every request.
Some common choices:
LOCAL_QUORUM/LOCAL_QUORUM: the usual default. Read-your-writes within a region, tolerates one replica down per region.ONEwrites,ONEreads: lowest latency, highest availability, eventually consistent. Fine for metrics, logs and likes.ALL: rarely a good idea; a single node down makes the operation fail.
Quorums aren't the same as transactions, though. Two clients writing the same cell at the same time both succeed, and last write wins. And a write that fails at QUORUM (only one replica got it) isn't rolled back: it may still show up later. If you need "insert only if absent" or compare-and-set, Cassandra offers lightweight transactions (LWT):
INSERT INTO usernames (username, user_id) VALUES ('alice', 42) IF NOT EXISTS;
UPDATE accounts SET balance = 400, version = 8
WHERE account_id = 42
IF version = 7;
LWTs run a Paxos round among the replicas, which costs about four round trips instead of one and serializes contending writers, so they're for occasional uniqueness and coordination, not hot paths. Work is underway to add a more general consensus-based transaction protocol (Accord) to Cassandra, but in an interview, assume LWTs on a single partition are what you have.
Fault Tolerance and Repair
Because there's no leader, Cassandra stays writable as long as enough replicas for the consistency level are up. Replicas that miss writes catch up through three mechanisms:
- Hinted handoff: if a replica is down when a write arrives, the coordinator stores a hint and replays it when the replica comes back. Hints are kept for a limited window (3 hours by default). A node down longer needs repair.
- Read repair: when a read at a level above
ONEfinds replicas disagreeing, the coordinator sends the newest data to the stale ones. - Anti-entropy repair:
nodetool repair(or a scheduler like Cassandra Reaper) compares replicas range by range using Merkle trees, hash trees that pinpoint which ranges differ without shipping all the data, and streams the differences. Every table should be repaired at least once pergc_grace_seconds, or deleted data can come back.
When a node dies permanently, you replace it, and the new node streams its ranges from surviving replicas. When you add nodes, they stream the slices of the ring they take over, with no downtime.
Cassandra is an AP system in CAP terms when used at low consistency levels: during a partition, both sides keep accepting writes and reconcile later by timestamp. At
QUORUM, a minority side can't satisfy requests, so you trade some availability for consistency. Saying it this way, per consistency level, is more accurate than calling Cassandra "AP" outright.
Scaling and Performance
- Scale out by adding nodes. Throughput and storage grow close to linearly, as long as the partition key spreads load evenly.
- Hot partitions are still hot. All traffic for one partition key goes to its RF replicas. A celebrity's timeline or a huge channel needs bucketing or a different key, just like in DynamoDB.
- Node density: operators commonly keep a few TB of data per node so that streaming a replacement node and running repair stay manageable.
- Latency: single-partition reads and writes typically complete in single-digit milliseconds at the median, with tail latency driven by compaction, garbage collection pauses on the JVM and tombstones.
- ScyllaDB is a compatible reimplementation in C++ with a shard-per-core design, which avoids JVM garbage collection and often gets more throughput per node. Some large users have moved to it for tail latency; Discord, for example, has written about migrating its message store from Cassandra to ScyllaDB.
Sizing a Cluster
It's worth doing the arithmetic, because it often shows that storage, not throughput, decides the cluster size. Say an activity log takes 10,000 writes per second of 1 KB each, kept for 90 days, with RF = 3:
- Throughput: 10,000 writes × 3 replicas = 30,000 replica writes per second. At a conservative 10,000 writes per second per node, that's 3 nodes' worth of work.
- Storage: 10,000 × 1 KB = 10 MB/s, or about 864 GB per day. Times 3 replicas is about 2.6 TB per day, and 90 days is about 233 TB before compression.
- Nodes: at roughly 2 TB of data per node (leaving headroom for compaction, which can temporarily need extra disk), that's on the order of 100+ nodes. Compression (often 2-4x on text-like data) would bring it down a lot.
So the design question becomes retention and compression, not write capacity. Shorter TTLs, TWCS so expired windows drop as whole files, or tiering old data to S3 matter far more than adding nodes for speed.
Secondary Indexes and Materialized Views
Cassandra's original secondary indexes are local to each node, so a query by indexed value must ask every node, which doesn't scale for high-cardinality lookups. Cassandra 5.0's storage-attached indexes (SAI) are much better and also power vector search, but they're still best combined with a partition key restriction. Materialized views exist but are marked experimental. The safe interview answer is still a second, denormalized table maintained by the application.
Other Features
- TTL on any write:
INSERT ... USING TTL 86400expires data automatically, great for sessions, stories and caches. - Counters: a special column type for distributed increments. They're not idempotent, so a retried increment can double-count. Fine for approximate view counts, not money.
- Batches: a logged batch guarantees that all its statements eventually apply, which helps keep denormalized tables in sync, but it isn't isolated and is slower. Batches are for atomicity across tables, not for bulk loading performance. A batch within a single partition is applied atomically and in isolation.
- Multi-data-center replication is built in and active-active: every region takes writes locally.
Cassandra vs Alternatives
| Cassandra | DynamoDB | HBase | Postgres | |
|---|---|---|---|---|
| Topology | Leaderless ring | Managed, leader per partition | Region servers on HDFS, master | Single primary |
| Writes | Any replica, LWW | Leader per partition | One region server per row range | Primary only |
| Consistency | Tunable per query | Strong or eventual per read | Strong per row | Strong, ACID |
| Multi-region | Built-in active-active | Global tables | Replication add-on | Replicas, single writer |
| Operations | You run it (or managed: Astra, Keyspaces) | Fully managed | Heavy (HDFS, ZooKeeper) | Moderate |
Cassandra in an Interview
When to Use It
- Write-heavy, append-mostly data at large scale: chat messages, activity and audit logs, notifications, event histories, sensor readings.
- Time series with natural time bucketing and TTL-based expiry.
- Always-writable requirements: multi-region systems that must accept writes during an outage in another region.
- Known, simple access patterns that map to "read a partition, sorted by a clustering key."
Knowing Its Limitations
- No joins, few ad-hoc queries. Every new query pattern means a new table. Analytics go to Spark or a warehouse.
- No general transactions. Lightweight transactions handle single-partition compare-and-set, slowly. Money movement and inventory belong in a relational database.
- Last write wins. Concurrent updates to the same cell silently drop one, and clock skew matters.
- Deletes are expensive. Tombstones slow reads, and queue-like workloads perform badly.
- Reads cost more than writes, especially with many SSTables, and tail latency suffers during compaction and JVM pauses.
- Operational burden: repairs, compaction tuning, node replacement and capacity planning are on you unless you use a managed service.
Questions You Might Get
- "How would you store messages for a chat app?" Partition by
(conversation_id, time bucket), cluster by a time-ordered message ID descending,LOCAL_QUORUMreads and writes, and a separate table per extra query pattern. - "What happens if a replica is down during a write?" At
QUORUMwith RF = 3, two replicas suffice, the coordinator stores a hint for the third, and hinted handoff or repair brings it up to date. - "How do you guarantee a read sees the latest write?" Choose R + W > RF, typically
LOCAL_QUORUMfor both, and note that concurrent writes still resolve by last write wins. - "How do you enforce a unique username?" A lightweight transaction (
INSERT ... IF NOT EXISTS) on a table keyed by username, since it's rare and correctness matters there. - "Why are reads slow on this table?" Too many SSTables (consider leveled compaction), large partitions (bucket them), or tombstones from deletes (redesign to use TTLs and time-window compaction).
Summary
Cassandra is a leaderless, wide-column database that spreads partitions across a consistent-hashing ring and replicates each one to several nodes across racks and data centers. Writes append to a commit log and memtable and later become immutable SSTables merged by compaction, which makes writes fast and cheap. Reads merge versions across files, helped by Bloom filters and the right compaction strategy.
Consistency is tunable per query, with R + W > RF giving read-your-writes and lightweight transactions covering rare compare-and-set needs, while hinted handoff, read repair and Merkle-tree repair keep replicas converging. In an interview, reach for Cassandra when the workload is massive, write-heavy and query-predictable, design tables from the queries with bounded partitions, and be ready to explain the costs: last write wins, tombstones and no joins.