AlgoViz

Cassandra

hard 38 min

Apache 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-1617-3334-5051-6768-8485-99
ownernode 1node 2node 3node 4node 5node 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 dayafter a year
sensor8.64 MB3.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

    critical

    It grows for years, reads slow down and one set of nodes carries it.

    Wrong
    PRIMARY KEY (sensor_id, reading_id)
    Right
    PRIMARY KEY ((sensor_id, day), reading_id)
  • No repair

    critical

    Copies drift apart, and after the grace period deleted rows return.

    Wrong
    # cron: nothing
    Right
    nodetool repair              # every 1 to 3 daysnodetool repair --full -pr   # every 1 to 3 weeks
  • Batches for loading

    major

    One coordinator carries rows of many partitions. Above 50 KiB such a batch fails.

    Wrong
    for row in rows: batch.add(insert, row)session.execute(batch)
    Right
    execute_concurrent_with_args(session, insert, rows, concurrency=50)
  • A condition on the wrong key

    major

    IF NOT EXISTS checks the primary key. A new user_id never exists, so the same e-mail is taken twice.

    Wrong
    INSERT INTO users (user_id, email) VALUES (uuid(), 'a@x.com') IF NOT EXISTS
    Right
    INSERT 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.