AlgoViz

Cassandra

hard 38 min

Apache Cassandra spreads rows around a ring of equal nodes and copies each row to several of them.

Video lesson · Chapter 1 of 5

Find a temperature reading

0:00 / 4:01

Cassandra in 80 seconds

1:20Reel coming soon

Theory

Read or listen first. About 2 min.

What it is

Apache Cassandra is an open-source database for a cluster of equal machines. It joins two ideas: the ring and copies of Amazon's Dynamo, and the partitioned, sorted rows of Google's Bigtable. Its language, CQL, looks like SQL without joins.

A row belongs to a partition. A hash of the partition key gives a token, and the token says which nodes keep the row. Inside a partition, rows are sorted by the clustering columns. People call this a wide-column store.

Why it exists

A database with one primary stops taking writes when that machine fails, until another takes over. It also limits writes to what one machine can do. Cassandra lets several copies accept each write, so a lost node, rack or data centre need not stop anything.

Storage fits that aim. A write is an addition to a log and to a table in memory, and files on disk are never changed, only merged later. So writes stay quick, and the cost appears in reads, in merging, and in keeping the copies equal.

A short history

  1. July 2008

    Facebook releases Cassandra as open source. It was built there for the search in the inbox.

  2. 17 February 2010

    Cassandra graduates from the incubator and becomes a top-level Apache project.

  3. 27 July 2021

    Version 4.0 is released, almost six years after version 3.0 of November 2015.

  4. 5 September 2024

    Version 5.0 is announced, with storage-attached indexes, trie structures, a vector type and unified compaction.

Words to know

Node
One Cassandra machine. All nodes have the same role.
Token
A number from hashing the partition key. It is a place on the ring.
Replication factor (RF)
How many nodes keep each row in one data centre.
Consistency level (CL)
How many copies must answer one query.
Coordinator
The node that received the request and asks the copies.
SSTable
A sorted file on disk that is never changed.
Tombstone
A mark that says a value was deleted.
Repair
Comparing copies and sending what is missing.

How it works

Step through the idea, or press Play.

Step 1 of 3

Model by query. One table for each question, keyed by what it gives

Understand it

Start here

The ring of beach huts

Six beach huts stand in a ring around a bay. Each hut keeps the tide notes of its own stretch of beach, and copies for the huts before it. Nobody is in charge. Imagine handing in a note at any hut.

Notes kept by three huts
123456no chief

The ideas behind it have their own pages: consistent hashing, LSM trees, consistency models. This page is about the product.

Fit

When to choose it

  • Heavy writes

    A write is an append and a change in memory. Adding nodes adds write capacity, when keys spread well.

  • No primary to lose

    With RF 3 and quorums, one lost copy is not noticed by clients.

  • Several data centres

    Each can serve reads and writes near its users, with its own number of copies.

  • Growth without a pause

    A new node takes ranges from others while the cluster works.

Choose it when

  • Writes are many and steady: events, readings, messages
  • Queries are known and start from a key
  • Data is ordered by time and can expire
  • Several regions must accept writes
  • You want to run it anywhere

Look elsewhere when

  • You need joins or free questions
  • Most writes need a check across partitions
  • The data fits one server
  • Rows are deleted all the time, as in a queue
  • Nobody will operate repairs and compaction

Architecture

The ring and the copies

Coordinator, three copies, a second data centre

An app with a driver sends a write to the coordinator, node 1 of a data centre. The coordinator sends it to three replicas, nodes 3, 4 and 5 on separate machines, and to one node of a second data centre that passes it on there.
Each thick box is one machine. Any of them could have been the coordinator.

Cassandra's partitioner hashes the key to a signed 64-bit token, from −263-2^{63} to 263−12^{63}-1. Each node has several tokens, so its share is many small ranges. These are virtual nodes, and the default is 16 for each node since 4.0. A joining node then takes a little from many others. More tokens spread work better but give every node more partners, so more pairs of failures matter.

  1. 1

    The client asks

    A driver keeps connections to many nodes. A token-aware driver hashes the key itself and goes straight to a copy.

  2. 2

    The coordinator routes

    It finds the copies of that token and sends them the request. It waits for as many as the level says.

  3. 3

    A copy writes

    It adds to the commit log and to the memtable, and answers.

  4. 4

    A flush

    A full memtable becomes an SSTable on disk, with an index and a Bloom filter.

  5. 5

    Compaction

    Files are merged in the background, and old versions and expired tombstones go.

  6. 6

    Other data centres

    The coordinator sends one copy of the write to each other data centre, and a node there passes it on.

A write with LOCAL_QUORUM

All copies get the write at once. The level only says how many answers to wait for.

Gossip tells nodes about each other. Every second a node exchanges state with a few others: who is up, which tokens they have, which schema version. Silence raises suspicion, described in failure detection.

Consistency

Choose a level for each query

Levels, with RF 3 in each of two data centres

LevelAnswers neededUse
ANYOne node, a hint counts (writes only)Rarely
ONE, TWO, THREE1, 2, 3Data that may be stale
LOCAL_ONE1 in this data centreQuick local reads
QUORUM4 of 6 over bothStrong across both, pays the distance
LOCAL_QUORUM2 of 3 hereThe usual choice
EACH_QUORUM2 of 3 in eachWrites that must be in both
ALLAll 6One lost node fails it
SERIAL, LOCAL_SERIALMajority with PaxosConditional writes
In the language shell, CONSISTENCY LOCAL_QUORUM sets the level for the session. In a program the driver sets it.

When a read sees the last write

R+W>RFQ=⌊RF2⌋+1RF=3:;2+2=4>3 ✓1+3=4>3 ✓1+1=2≯3R + W > RF \qquad Q = \left\lfloor \tfrac{RF}{2} \right\rfloor + 1 \qquad RF=3:; 2 + 2 = 4 > 3\ \checkmark \quad 1 + 3 = 4 > 3\ \checkmark \quad 1 + 1 = 2 \not> 3
The read set and the write set then share at least one copy. With RF 3 and quorums, one copy may be down.

Last write wins. Each value has a timestamp, usually from the client or coordinator clock, and the newest stays. Two people who change the same column at the same time lose one change silently, and a machine with a fast clock wins too often. Keep clocks in step.

Which level?

LOCAL_QUORUM is only strong inside one data centre. A user who moves to the other may read older data for a moment.

Storage

Inside one node: the write path

Commit log, memtable, SSTables

One Cassandra node. A write goes to the commit log on disk and to the memtable in memory. The memtable is flushed to SSTables on disk, which compaction merges.
No file is changed in place. Compaction writes new files and drops old ones.
  1. 1

    Commit log

    An append. By default (periodic) the write is acknowledged at once and the log is forced to disk every 10 seconds, so a single machine that loses power can lose the last seconds. Copies on other machines cover that. batch mode waits for the disk.

  2. 2

    Memtable

    A sorted structure in memory, one for each table.

  3. 3

    Flush

    When memtables use too much memory, or the commit log is near its maximum size, the memtable becomes an SSTable.

  4. 4

    SSTable

    Sorted by token and then by clustering columns. With it: a partition index, a summary, a Bloom filter, statistics.

So a write costs an append and an insertion into a sorted structure, O(log⁡n)O(\log n) in memory. It does not read from disk, unless it is conditional, a counter, or has an index to maintain.

Storage

The read path

  1. 1

    Row cache, if switched on

    Off by default. Useful only for a few hot rows.

  2. 2

    Memtables

    The active one and any that are being flushed.

  3. 3

    Bloom filters

    For each SSTable: the partition is certainly not here, or perhaps it is. A false positive costs a look, a false negative never happens.

  4. 4

    Index

    Find the place of the partition in the file.

  5. 5

    Merge

    Combine all versions, newest timestamp for each column, with tombstones applied.

Wasted looks with n files

extra≈n×pn=12, p=0.01:;0.12p=0.1:;1.2\text{extra} \approx n \times p \qquad n = 12,\ p = 0.01:; 0.12 \qquad p = 0.1:; 1.2
p is bloom_filter_fp_chance: 0.01 by default, and 0.1 for leveled compaction. Going from 0.1 to 0.01 needs about three times the memory.

A read may have to open several files, so reads are usually dearer than writes. Merging files is what keeps that number small.

Storage

Compaction strategies

StrategyIdeaGood forCost
Size-tiered (STCS)Merge 4 or more files of similar sizeMany writesExtra disk while merging; a row may be in many files
Leveled (LCS)Levels of files that do not overlap, each 10 times the lastMany reads and updatesMuch more writing
Time-window (TWCS)One set of files for each time windowTime series with TTLBad with late data, updates or deletes
Unified (UCS), from 5.0One strategy with settings that act like the othersRecommended for most new tablesNeeds 5.0
The default for a table is still STCS. For TWCS choose a window that gives about 20 to 30 windows in the lifetime of the data.

With TWCS and one TTL for all rows, a whole file becomes old at the same time and is simply deleted. For data kept 30 days use windows of one day; for 90 days, three days.

Modelling

One table for each query

Write the questions first. If orders are asked for by customer and by status, make two tables and write both. Storage is cheap here, joins do not exist.

SQL
CREATE KEYSPACE shop WITH replication = {  'class': 'NetworkTopologyStrategy', 'dc_east': 3, 'dc_west': 3 };CREATE TABLE shop.orders_by_customer (  customer_id uuid,  order_date  date,  order_id    timeuuid,  status      text,  cents       bigint,  items       list<text>,  PRIMARY KEY ((customer_id, order_date), order_id)) WITH CLUSTERING ORDER BY (order_id DESC);-- Allowed: both parts of the partition key, then clustering columns from the left.SELECT * FROM shop.orders_by_customer WHERE customer_id = 123e4567-e89b-12d3-a456-426614174000   AND order_date = '2026-01-15' LIMIT 5;
The inner brackets are the partition key. What follows sorts the rows. Data centre names must match those of your cluster.

Rules for WHERE

RuleExample
All of the partition key, with equalitycustomer and date
Clustering columns from left to right, none skippedyear, then month
A range only on the last one usedmonth > 3
Order is fixed by the tableAnother order: another table
Page by the last key seenThere is no OFFSET
ALLOW FILTERING is a warningIt may read the whole cluster

Good partition keys

  • Many values, evenly used: user_id
  • With a bucket: (sensor_id, day)
  • Partition stays small for its whole life
  • Every query gives it

Bad partition keys

  • Few values: country, status
  • Grows for ever: sensor_id alone
  • One value for now: today
  • So fine that a page needs thousands

How big is a partition?

86,400 readingsday×100 B=8.64 MB a day365 days=3.2 GB in one partition86{,}400\ \tfrac{\text{readings}}{\text{day}} \times 100\ \text{B} = 8.64\ \text{MB a day} \qquad 365\ \text{days} = 3.2\ \text{GB in one partition}
One reading a second. A daily bucket is comfortable. A common rule of thumb is under 100 MB and 100,000 rows; the hard limit is 2 billion cells.

For a secondary question, storage-attached indexes (5.0) index columns of a table. They work best when the query also gives the partition key. Without it, many nodes must answer, so a second table is still the safe choice for a busy query.

Time series

Readings with a bucket and a TTL

SQL
CREATE TABLE iot.readings (  sensor_id   text,  bucket      text,          -- '2026-01-15-14': one hour  reading_id  timeuuid,  temperature double,  humidity    double,  PRIMARY KEY ((sensor_id, bucket), reading_id)) WITH CLUSTERING ORDER BY (reading_id DESC)  AND compaction = { 'class': 'TimeWindowCompactionStrategy',                     'compaction_window_unit': 'DAYS', 'compaction_window_size': 1 }  AND default_time_to_live = 2592000;      -- 30 daysINSERT INTO iot.readings (sensor_id, bucket, reading_id, temperature, humidity)VALUES ('s-1', '2026-01-15-14', now(), 23.5, 65.2);SELECT * FROM iot.readings WHERE sensor_id = 's-1' AND bucket = '2026-01-15-14'   AND reading_id >= minTimeuuid('2026-01-15 14:30:00+0000')   AND reading_id <= maxTimeuuid('2026-01-15 14:45:00+0000');SELECT TTL(temperature), WRITETIME(temperature) FROM iot.readings WHERE sensor_id = 's-1' AND bucket = '2026-01-15-14' LIMIT 1;
A range over several hours is one query for each bucket, sent in parallel.

Staying equal

Hints, read repair, repair

MechanismWhenLimit
Hinted handoffA copy was down during a writeHints are kept for up to 3 hours of downtime
Read repairA read finds copies that differOnly for rows that are read
RepairYou run it, or a scheduler doesMust finish within gc_grace_seconds
The first two are best effort. Only repair guarantees that copies become equal.

A hint, then read repair

Since 4.0 read repair is blocking: the answer waits until enough copies have the newest value. A table may set it to none.

Repair builds a tree of hashes, a Merkle tree, for each range on each copy, compares them, and sends only the ranges that differ. Incremental repair is the default type and looks at data written since the last one. Full repair looks at everything. The documentation offers a starting point: incremental every 1 to 3 days and full every 1 to 3 weeks.

Shell
nodetool status                      # up or down, load, owned sharenodetool repair shop                 # incrementalnodetool repair --full -pr shop      # full, only this node's primary rangesnodetool tablestats shop.orders_by_customernodetool compactionstatsnodetool tpstats                     # dropped messages are a warning

Deletes

Tombstones and zombies

A delete cannot simply remove a value: a copy that missed the delete would bring it back. So a delete is a write, a tombstone with a timestamp. It is kept for gc_grace_seconds, 864,000 seconds or 10 days by default, and then compaction may drop it.

How a zombie is made

Repair every copy within the grace period, or do not bring back a node that was away for longer.

Reads must step over tombstones. By default a query warns at 1,000 and fails at 100,000 of them. So do not build a queue with deletes. Prefer TTL with TWCS, or drop whole partitions.

Correct writes

Batches and lightweight transactions

ToolGivesDoes not give
One statement in one partitionAtomic and isolatedA check of the old value
Logged batch, one partitionAtomic and isolated; runs as unloggedSpeed for bulk loading
Logged batch, several partitionsAll will be applied in the end, or noneIsolation: others see it half done
Unlogged batchFewer round trips to one partitionAll or nothing
Counter batchSeveral counters in one requestSafe retries
Lightweight transaction (LWT)Compare and set in one partitionLow cost
For loading many rows, send single inserts in parallel. A batch over several partitions of more than 50 KiB fails by default.

An LWT uses Paxos: prepare, propose, commit, with a read between. The default variant (v1) needs four round trips for a write. paxos_variant: v2, available since 4.1, needs two and is the recommended one. It must be switched on as the documentation describes.

SQL
-- Unique e-mail: make it the key. (A condition on user_id would not check the e-mail.)INSERT INTO shop.users_by_email (email, user_id) VALUES ('sam@example.com', uuid()) IF NOT EXISTS;-- Compare and set. Read the stock first, then:UPDATE shop.inventory SET stock = 95 WHERE product_id = 'p-1' IF stock = 100;-- [applied] = False gives the current value: read again and retry.-- A lock that frees itself after 30 seconds.INSERT INTO shop.locks (name, holder) VALUES ('report', 'w-1') IF NOT EXISTS USING TTL 30;UPDATE shop.locks USING TTL 30 SET holder = 'w-1' WHERE name = 'report' IF holder = 'w-1';DELETE FROM shop.locks WHERE name = 'report' IF holder = 'w-1';
A lock that expires can end while its holder still works. Protect the work itself, for example with a growing number checked by the storage.

Regions

Several data centres

NetworkTopologyStrategy gives each data centre its own number of copies and puts them on different racks where it can. With LOCAL_QUORUM a write waits for two local copies and the other data centre catches up afterwards. If a whole data centre is lost, the others go on, and writes that had not crossed yet are missing until it returns.

Local and each quorum

Operations

Defaults and daily care

SettingDefaultRemember
num_tokens16It was 256 before 4.0
commitlog_sync_period10 s, periodic modeNot forced to disk for each write
max_hint_window3 hoursLonger away: repair
gc_grace_seconds10 daysRepair more often than this
read_request_timeout5 sOn the server side
write_request_timeout2 sA timeout does not mean not written
Multi-partition batchFails above 50 KiBKeep batches small
  1. 1

    Watch

    Latency at the 99th percentile, dropped messages, pending compactions, hints, tombstones read, largest partition.

  2. 2

    Keep disk room

    Size-tiered compaction may need about as much free space as the files it merges.

  3. 3

    Add and remove one node at a time

    Let streaming finish, then run cleanup on the others.

  4. 4

    Back up with snapshots

    A snapshot links the files that never change. A wrong delete is copied to all replicas, so copies are not a backup.

  5. 5

    Upgrade in a rolling way

    One node after another, and no schema changes while versions are mixed.

Decide

Trade-offs and neighbours

What you gain

  • Scale: add nodes for data and writes.
  • No single point of failure in the cluster.
  • Writes: appends and memory.
  • Data centres: active in several at once.
  • Choice: a consistency level for each query.

What you pay

  • No joins: data is copied into several tables.
  • No free questions: a table for each query.
  • Reads: several files, merged.
  • Operations: repair, compaction, tombstones.
  • Learning: query-first modelling is unusual.

Compared with neighbours

AlikeDifferentChoose the other for
PostgreSQLTables, a query language, typesJoins, transactions, one primaryRelations, money, smaller data
MongoDBHorizontal scale, replicationDocuments, free queries, one primary for each shardChanging questions
DynamoDBPartition and sort keys, high write rateManaged, leader for each partition, AWS onlyNo servers to run

Summary

The whole topic in one minute.

Cassandra is a ring of equal nodes. The partition key chooses the nodes, the clustering columns choose the order, and each query chooses how many copies must answer. If read copies plus write copies are more than the replication factor, a read sees the last confirmed write.

The price is paid in modelling and care: one table for each query, partitions kept small, deletes handled with respect, and repair finished before tombstones are dropped.

  • Equal nodes on a token ring; the partition key picks the copies.
  • R + W > RF gives reads that see the last write; LOCAL_QUORUM is the usual level.
  • Writes are appends; reads merge files; compaction keeps the files few.
  • One table for each query, with bounded partitions.
  • Deletes are tombstones: repair within 10 days or old data returns.
  • LWT is compare and set in one partition, and it is dear.

Sources