Skip to content

Unit 6 · Distributed Databases: Apache Cassandra

3 h contact · 6 h self study · lab Prerequisites: Unit 5 CLO 6

1. Setting the scene

Scenario: 4,000 writes per second, forever

SensorGrid writes \(20{,}000 / 5\ \text{s} = 4{,}000\) readings per second, day and night. The existing PostgreSQL server handles it on quiet days, but after the storm it fell behind, and when it was rebooted for an update, readings were lost.

The team needs a database that accepts writes on any node, grows by adding machines, and never has a single point of failure.

Guiding questions

  1. How can a database decide which machine stores a given row without asking a master?
  2. How many copies of each reading do we need, and how many must confirm a write?
  3. Where is the parallelism inside a distributed database?

2. Intended learning outcomes

# Outcome Bloom CLO
ILO 6.1 Describe Cassandra's peer to peer architecture and the role of the coordinator. UNDERSTAND 6
ILO 6.2 Explain data placement with partition keys, hashing and the token ring. UNDERSTAND 6
ILO 6.3 Compute quorum sizes and decide consistency levels for reads and writes. APPLY 6
ILO 6.4 Design a partition key for time series data that avoids hot spots. CREATE 6
ILO 6.5 Identify parallelism across nodes, across replicas and within a node. ANALYSE 6

3. Why Cassandra in a parallel computing module?

Cassandra is a real world distributed system designed for horizontal scalability, fault tolerance and high availability. It lets us study distributed memory, data partitioning, replication and parallel query execution through a concrete system.

What is Apache Cassandra?

A distributed NoSQL database for clusters of machines, with no single point of failure, that scales linearly by adding nodes. Key idea: data is distributed, replicated, and queried in parallel.

4. Architecture: a peer to peer cluster

flowchart LR
    N1["Node 1"] <-.->|"gossip"| N2["Node 2"]
    N2 <-.->|"gossip"| N3["Node 3"]
    N3 <-.->|"gossip"| N4["Node 4"]
    N4 <-.->|"gossip"| N1
    N1 <-.-> N3
  • There is no master; all nodes are equal.
  • Any node can accept reads and writes and act as coordinator for that request.
  • Nodes exchange state with a gossip protocol: every second, each node talks to a few others, and news spreads like a rumour in \(O(\log N)\) rounds.

5. Data placement: the token ring

Every row has a partition key. Cassandra hashes it (Murmur3) to a token, a 64 bit number, and places tokens on a ring:

\[ \text{token} = h(\text{partition key}) \in \left[-2^{63},\; 2^{63} - 1\right] \]

Each node owns a range of tokens. The next node clockwise from the token owns the key.

flowchart TB
    K["partition key<br/>sensor_id = 'S17', day = 18 Jul 2026"] -->|"Murmur3 hash"| T["token = 4.1 × 10¹⁸"]
    T --> RING
    subgraph RING["Token ring"]
      direction LR
      A["N1 owns<br/>(−2⁶³, −4.6e18]"] --> B["N2 owns<br/>(−4.6e18, 0]"] --> C["N3 owns<br/>(0, 4.6e18]"] --> D["N4 owns<br/>(4.6e18, 2⁶³)"] --> A
    end
    T -.->|"falls in N3's range"| C

Because a good hash spreads keys uniformly, each of \(N\) nodes receives about \(1/N\) of the data. Adding a node takes over part of one range, so only about \(1/N\) of the data moves (consistent hashing), unlike hash(key) mod N, where almost every key would move.

6. Partitioning: data parallelism across nodes

flowchart TB
    E["Events / rows"] --> H["hash(partition key)"]
    H --> N1["Node N1 · range A"]
    H --> N2["Node N2 · range B"]
    H --> N3["Node N3 · range C"]

Requests for different ranges are served in parallel. Good partition keys spread load and avoid hot spots. Partitioning is the key to scale out performance.

A bad key for SensorGrid

Partition key district puts all 2,000 sensors of Mitte on one node: that node receives 10 % of all writes while others idle, and the partition grows forever. A better key is (sensor_id, day): many small, evenly spread partitions, each bounded in size.

erDiagram
    READINGS_BY_SENSOR_DAY {
        text sensor_id PK "partition key part 1"
        date day PK "partition key part 2"
        timestamp ts "clustering column, DESC"
        float pm25
        float no2
        float temperature
        int noise_db
    }
CREATE KEYSPACE sensorgrid
  WITH replication = {'class': 'NetworkTopologyStrategy', 'berlin_dc': 3};

CREATE TABLE sensorgrid.readings_by_sensor_day (
    sensor_id   text,
    day         date,
    ts          timestamp,
    pm25        float,
    no2         float,
    temperature float,
    noise_db    int,
    PRIMARY KEY ((sensor_id, day), ts)
) WITH CLUSTERING ORDER BY (ts DESC);

One partition holds one sensor's day: \(86{,}400 / 5 = 17{,}280\) rows of about 100 bytes, roughly 1.7 MB, comfortably small.

7. Replication: fault tolerance

With replication factor RF = 3, each row is stored on three nodes: the owner and the next two nodes clockwise.

sequenceDiagram
    participant C as Client
    participant CO as Coordinator
    participant R1 as Replica N3
    participant R2 as Replica N4
    participant R3 as Replica N1
    C->>CO: INSERT reading
    par parallel writes
        CO->>R1: write
    and
        CO->>R2: write
    and
        CO->>R3: write
    end
    R1-->>CO: ack
    R2-->>CO: ack
    CO-->>C: success (2 acks)
    R3-->>CO: ack (late)

Replication keeps the system available during node failures; RF controls the trade off between durability, availability and storage:

\[ \text{storage} = \text{RF} \times \text{data size}: \qquad 3 \times 12.6\ \text{TB/year} \approx 38\ \text{TB/year} \]

8. Tunable consistency: ONE, QUORUM, ALL

For each operation the client chooses how many replicas must answer:

Level Replicas that must respond Latency Tolerates down replicas (RF = 3)
ONE 1 lowest 2
QUORUM \(\lfloor \text{RF}/2 \rfloor + 1 = 2\) medium 1
ALL RF = 3 highest 0

When is a read guaranteed to see the latest write? When the set of replicas written (\(W\)) and the set read (\(R\)) must overlap:

\[ R + W > \text{RF} \]

With RF = 3: QUORUM writes (\(W = 2\)) and QUORUM reads (\(R = 2\)) give \(4 > 3\), so every read overlaps at least one up to date replica. ONE and ONE gives \(2 \not> 3\): fast, but a read may return stale data.

flowchart LR
    CO["Coordinator"] --> R1["Replica 1 ✓"]
    CO --> R2["Replica 2 ✓"]
    CO --> R3["Replica 3"]
    R1 -.->|"ack"| CO
    R2 -.->|"ack"| CO

QUORUM is a common practical choice: it tolerates one failed replica and still gives consistent reads.

For SensorGrid: live dashboards read at ONE (freshness within a second is enough), alert rules write and read at QUORUM.

9. Request flow

sequenceDiagram
    participant Cl as Client
    participant Co as Coordinator
    participant A as Replica 1
    participant B as Replica 2
    participant C as Replica 3
    Cl->>Co: read or write (key)
    Co->>Co: token = hash(key)
    par to all replicas
        Co->>A: request
        Co->>B: request
        Co->>C: request
    end
    A-->>Co: reply
    B-->>Co: reply
    Co-->>Cl: answer at consistency level

Where is the parallelism?

  • Across nodes: partitions are distributed and requests are served in parallel.
  • Across replicas: concurrent reads from replicas and parallel write propagation.
  • Within each node: multithreaded execution and asynchronous I/O.

Parallelism exists both across machines and inside machines.

10. Mini pipeline: Kafka → Python → Cassandra

flowchart TB
    DEV["IoT devices / apps"] -->|"events (JSON)"| PR["Producer (Python)"]
    PR -->|"publish"| K[("Kafka topics")]
    K -->|"subscribe / poll"| CO["Consumer (Python)<br/>parse · validate · enrich<br/>features · window aggregates"]
    CO -->|"batched writes"| CA[("Cassandra cluster<br/>partition key · RF · consistency")]
from cassandra.cluster import Cluster
from cassandra.query import BatchStatement, ConsistencyLevel

session = Cluster(["cassandra-1", "cassandra-2"]).connect("sensorgrid")
insert = session.prepare(
    "INSERT INTO readings_by_sensor_day (sensor_id, day, ts, pm25, no2, temperature, noise_db) "
    "VALUES (?, ?, ?, ?, ?, ?, ?)")
insert.consistency_level = ConsistencyLevel.QUORUM

def write_batch(rows):
    """rows of ONE partition (same sensor and day) go into one batch"""
    batch = BatchStatement(consistency_level=ConsistencyLevel.QUORUM)
    for r in rows:
        batch.add(insert, (r["sensor_id"], r["day"], r["ts"], r["pm25"],
                           r["no2"], r["temperature"], r["noise_db"]))
    session.execute(batch)

Kafka decouples ingestion from storage (Unit 8); Python processes events and writes in batches; Cassandra stores scalable time series data.

11. Lab

Cassandra lab

Set up a Cassandra cluster in Docker, experiment with partition keys and replication, and insert and query data.

Instructions: github.com/bugmend/bigdataanalytics/tree/main/NoSQL

Extension: stop one node (docker stop) and repeat reads at ONE, QUORUM and ALL. Record which succeed.

12. Check your understanding

RF = 5. What is QUORUM, and which read/write combinations are strongly consistent?

QUORUM \(= \lfloor 5/2 \rfloor + 1 = 3\). Strong when \(R + W > 5\): QUORUM/QUORUM (\(6\)), ONE/ALL (\(6\)), ALL/ONE (\(6\)).

Why is consistent hashing better than hash mod N when a node is added?

With mod N almost every key changes its node when N changes; on a ring only the keys in the range taken over by the new node move, about \(1/N\) of the data.

Why is district a poor partition key?

It creates few, huge, unbounded partitions and uneven load (hot spots).

13. Key takeaways

  • Cassandra is peer to peer: any node coordinates, no single point of failure.
  • Partition key → hash → token ring decides placement; consistent hashing makes scaling cheap.
  • RF copies protect data; consistency levels trade latency for correctness; \(R + W > \text{RF}\) guarantees fresh reads.
  • Parallelism appears across nodes, across replicas and inside nodes.

If your portfolio stores data in Cassandra, justify the partition key, RF and consistency levels, and show a failure experiment.

Further reading

  • A. Lakshman, P. Malik (2010), Cassandra: A Decentralized Structured Storage System, ACM SIGOPS.
  • G. DeCandia et al. (2007), Dynamo: Amazon's Highly Available Key value Store, SOSP.
  • Apache Cassandra documentation: cassandra.apache.org/doc