Cassandra
hard 38 minApache Cassandra spreads rows around a ring of equal nodes and copies each row to several of them.
See it run
Place a row on the ring, write with a closed node, repair a stale copy, follow a row to disk and back, and see a deleted row return.
Operations
Place a row
Hash the partition key, walk the ring, collect three different nodes.
Step 1 of 4
The ring
| 0-16 | 17-33 | 34-50 | 51-67 | 68-84 | 85-99 | |
|---|---|---|---|---|---|---|
| owner | node 1 | node 2 | node 3 | node 4 | node 5 | node 6 |
Six ranges, with small numbers so that we can follow. Each node owns one here.
Step 1: The ring
def replicas(key, rf=3): t = murmur3(key.partition) i = first_token_at_or_after(t) nodes = [] while len(nodes) < rf: if owner(i) not in nodes: nodes.append(owner(i)) i = next_token(i) return nodes- Waits for
- No lookup service
- Watch out for
- Hot keys
- Tokens for a node
- 16 by default
Only the partition key is hashed. Clustering columns sort inside.
In the real world
The same cassandra doing real jobs. Pick one and step through it.
One reading a second, 100 bytes each.
Step 1 of 3
Key: the sensor
| partition after a day | after a year | |
|---|---|---|
| sensor | 8.64 MB | 3.2 GB |
Too large
86,400 readings × 100 B is 8.64 MB a day, and 3.2 GB after a year in one partition.
Step 1: Key: the sensor
Common mistakes
The bugs interviewers watch for, with the fix beside each.
A partition without an end
criticalIt grows for years, reads slow down and one set of nodes carries it.
WrongPRIMARY KEY (sensor_id, reading_id)RightPRIMARY KEY ((sensor_id, day), reading_id)No repair
criticalCopies drift apart, and after the grace period deleted rows return.
Wrong# cron: nothingRightnodetool repair # every 1 to 3 daysnodetool repair --full -pr # every 1 to 3 weeksBatches for loading
majorOne coordinator carries rows of many partitions. Above 50 KiB such a batch fails.
Wrongfor row in rows: batch.add(insert, row)session.execute(batch)Rightexecute_concurrent_with_args(session, insert, rows, concurrency=50)A condition on the wrong key
majorIF NOT EXISTS checks the primary key. A new user_id never exists, so the same e-mail is taken twice.
WrongINSERT INTO users (user_id, email) VALUES (uuid(), 'a@x.com') IF NOT EXISTSRightINSERT INTO users_by_email (email, user_id) VALUES ('a@x.com', uuid()) IF NOT EXISTS
Interview tips
How to explain it
- Equal nodes, a ring, copies on the next ones.
- Each query chooses how many must answer.
- Appends on write, merge on read.
Memory trick
- R + W > RF.
- One query, one table.
- Repair before grace ends.
Reach for it when
- Writes are very many.
- Several regions must write.
- Data is ordered by time and expires.
Look elsewhere when
- Questions are free or need joins.
- Checks span several partitions.
- Rows are deleted all the time.