Data Modeling

This is the most important staff-level skill for Cassandra. Bad data models cause production incidents. Good data models make Cassandra look magical. Parts 4–6 described an engine that is superb at exactly one thing — reading a contiguous, sorted slice of one partition — and pays dearly for everything else. This part turns that into design rules. The consequence worth internalizing is that the primary key is the query plan: there is no planner, no JOIN and no efficient global index to rescue a table whose key doesn't match the question being asked, so you design one table per read query and accept the denormalization that implies.

The Fundamental Shift: Model for Access Patterns, Not for Normalization

Relational — model the domain

In a relational database, you model the domain: normalize your data into tables that reflect real-world entities and relationships, then write any query you like using JOINs and indexes.

Cassandra — model the queries

In Cassandra, you model the queries: for each distinct read query your application needs, you design a table whose physical layout allows that query to be answered by scanning one contiguous partition — or at most a handful of known partitions.

Why the Difference?

  1. Cassandra has no JOINs. There is no server-side query planner that combines data from multiple tables.
  2. Cassandra has no global secondary indexes that work efficiently at scale (the built-in secondary index scans every node — never use it in production).
  3. Cassandra's storage engine is optimized for reading contiguous data from a partition in sorted order. Any query that breaks this pattern becomes a scatter-gather query (see §5 below).

This means: before writing a single line of CQL, you must know your complete set of read queries. Denormalization is not a dirty word here — it is the correct tool.

  • Guarantees: A query that matches a table's primary key is answered from one partition on RF replicas — its cost is independent of cluster size and table size.
  • Does not guarantee: That a new query can be served by an existing table. A new read pattern usually means a new table, written alongside the old ones by the application — Cassandra will not keep the copies consistent for you.

Primary Key Anatomy

CREATE TABLE events (
    device_id   UUID,
    event_time  TIMESTAMP,
    sensor_type TEXT,
    value       DOUBLE,
    PRIMARY KEY ((device_id), event_time, sensor_type)
);
The primary key ((device_id), event_time, sensor_type) does two jobs. The partition key device_id is hashed with Murmur3 to a token, a position on the ring, which picks the replica nodes; all rows for device d1 live together there, and a query without the full partition key has no token and must be broadcast to every node. The clustering columns event_time then sensor_type set the physical sort order inside d1’s partition: a range on event_time, such as 09:00:00 to 09:00:01, is one contiguous slice, but filtering on sensor_type alone matches every other row and is no slice.
One key, two jobs — the partition key places, the clustering key orders

Partition Key: (device_id)

The partition key determines which node(s) store this row. Cassandra hashes the partition key to find the token, which determines placement on the ring (the ring and token ownership are Part 2 §1).

All rows with the same partition key are stored contiguously on disk on the same node. This makes queries within a single partition extremely fast — one disk seek, sequential read.

Clustering Key: (event_time, sensor_type)

The clustering key determines the sort order within a partition. Rows within the same partition are stored sorted by clustering key. This makes range queries efficient: WHERE device_id = X AND event_time >= Y AND event_time <= Z reads a contiguous slice of sorted data.

Query against eventsServed?Why
WHERE device_id = XYesOne whole partition, in clustering order.
WHERE device_id = X AND event_time >= Y AND event_time <= ZYesRange on the leading clustering column — one contiguous slice.
WHERE device_id = X AND event_time = T AND sensor_type = SYesEquality on every clustering column in order — a single row.
WHERE device_id = X AND sensor_type = SNoSkips the leading clustering column; matching rows are not adjacent. Rejected unless you add ALLOW FILTERING.
WHERE event_time >= YNoNo partition key — nothing to route on. Scatter-gather.
  • Guarantees: Within a partition, rows come back in clustering order for free — ORDER BY, LIMIT and range slices on the clustering prefix are sequential reads.
  • Does not guarantee: Any ordering across partitions. Partition keys are placed by hash, so you cannot range-scan from one partition key to the next.

What Is a Partition?

What it isA partition is the fundamental unit of data locality in Cassandra. It is all the rows that share the same partition key, stored together on the same node.
Ideal sizeUnder 100MB of data, under ~100,000 rows. The exact numbers vary by workload but these are widely-used operational guidelines.
Why size mattersThe entire partition must be read for certain operations. Compaction, repairs, and some read patterns operate at partition granularity. A 5GB partition will cause read latency spikes, compaction slowdowns, and heap pressure when it is accessed or compacted.
  • Guarantees: All rows of a partition live on the same replica set — a single-partition query never needs another node's data.
  • Does not guarantee: Any limit on partition size. Cassandra will happily accept writes into a 5GB partition; the bound has to come from your key design.

The Wide Partition Problem

A partition grows without bound when you keep adding rows with new clustering key values but never expire or delete old rows.

✗ DON'T — example of a dangerous model

-- DON'T: all events for a user in one partition
PRIMARY KEY (user_id, event_time)
-- A user with 5 years of activity = one enormous partition

DO — bucket by time to cap partition size

-- DO: bucket by (user_id, year_month) to bound partition size
PRIMARY KEY ((user_id, year_month), event_time)
-- Query: WHERE user_id = X AND year_month = '2026-06'
The same user’s history partitioned two ways. With PRIMARY KEY (user_id, event_time) there is one partition per user forever, and it keeps growing year after year. With PRIMARY KEY ((user_id, year_month), event_time) each month is its own partition with its own token, bounded by one month of activity and possibly on a different node. A query for April to June reads three partitions, 2026-04, 2026-05 and 2026-06, and the application merges them.
Unbounded vs. bucketed — put time in the key and every partition gets an end

The downside: a query spanning multiple months must now read from multiple partitions and merge results in the application layer. This is an intentional trade-off — multiple small reads beat one giant read.

  • Guarantees: Each partition's size is bounded by the activity that fits in one bucket — regardless of how long the entity lives.
  • Does not guarantee: Ordering or pagination across buckets. Merging, sorting and limiting across partitions is the application's job.

Scatter-Gather: What It Is and Why It Is Catastrophic

A scatter-gather query is one where Cassandra must contact many nodes to collect and aggregate results.

This Happens When

TriggerWhat Cassandra does
You query without the partition keyCassandra broadcasts to all nodes.
You use ALLOW FILTERINGExplicitly tells Cassandra to scan every partition.
You use a secondary indexInternally broadcasts to all nodes.
You run a SELECT * without a WHERE clauseA full table scan across every token range.
Two copies of the same eight-node ring. Left, a query with WHERE partition_key = X: the coordinator computes the token and contacts only the three RF owners, while five nodes stay idle, so the cost does not change as the cluster grows. Right, a query with no partition key or with ALLOW FILTERING: the coordinator contacts all eight nodes, every node scans and the coordinator merges everything, so the slowest node sets the latency and the cost grows with every node added.
Single-partition read vs. scatter-gather, on the same eight-node ring

What Makes It Catastrophic in Cassandra Specifically

  1. Every node in the cluster must handle the query simultaneously.
  2. Each node scans its local SSTables for matching rows.
  3. The coordinator collects and merges all responses.
  4. Tail latency is determined by the slowest node in the cluster.
  5. This pattern degrades with cluster size — the larger the cluster, the worse it gets.
  6. Under high traffic, this can bring down the entire cluster by exhausting thread pools.
  • Guarantees: A scatter-gather query returns a correct result if every token range answers in time.
  • Does not guarantee: Bounded latency or isolation. One slow node slows the whole query, and enough concurrent scatter-gathers degrade every other query on the cluster with them.

Design Example: IoT Sensor Data

Access Patterns

Before modeling, define every query the application will need:

  1. Query 1 — Get the last N readings for a specific device.
  2. Query 2 — Get all readings for a specific device within a time range.
  3. Query 3 — Get readings for a specific device and sensor type within a time range.

Primary Key Decision

CREATE TABLE sensor_readings (
    device_id    TEXT,
    sensor_type  TEXT,
    event_time   TIMESTAMP,
    value        DOUBLE,
    unit         TEXT,
    PRIMARY KEY ((device_id, sensor_type), event_time)
) WITH CLUSTERING ORDER BY (event_time DESC)
  AND COMPACTION = {'class': 'TimeWindowCompactionStrategy',
                    'compaction_window_unit': 'HOURS',
                    'compaction_window_size': 1}
  AND default_time_to_live = 2592000;  -- 30 days

Partition key: (device_id, sensor_type)

Why compound? Consider the access patterns: every query specifies both device and sensor type. Using both as the partition key:

  1. Keeps partitions bounded (one device's temperature readings, not all readings for all sensors).
  2. Makes Query 3 a direct partition lookup with no filtering.
  3. Distributes load across the cluster (different device+sensor combos go to different nodes).

If we used only device_id, a device with 10 sensor types all writing at high frequency would create a wide partition that grows indefinitely.

Clustering key: event_time DESC

Why descending?Query 1 asks for the last N readings. With DESC order, the most recent rows are physically first in the partition — reading the first N rows without reading the whole partition satisfies the query.
Why event_time?It enables Query 2: WHERE device_id = X AND sensor_type = Y AND event_time >= start AND event_time <= end reads a contiguous sorted slice. Cassandra can seek to start and read forward to end with no wasted I/O.

TWCS compaction

Sensor data is time-series, written once, read within recent windows, and expires after 30 days. TWCS groups data by 1-hour windows, drops old windows entirely, and produces zero tombstone accumulation. TTL-based expiry on TWCS means old data simply disappears when the whole SSTable file ages out (strategy details in Part 6).

Partition Size Check

If a device writes one reading per second per sensor type, that is 3,600 rows per hour per device+sensor combo. With a 30-day TTL, the maximum live rows in a partition at any time is 30 × 24 × 3,600 = 2,592,000 rows — potentially large.

Unbucketed  30 days × 24 h × 3,600 rows2,592,000
~100,000  the operational guideline from §3—
86,400  with a daily date_bucket: 24 h × 3,600 rows—
Bar widths are to scale — the unbucketed partition is 30× the bucketed one and ~26× the guideline.

If this exceeds your comfort zone, add a time bucket to the partition key:

PRIMARY KEY ((device_id, sensor_type, date_bucket), event_time)
-- date_bucket = '2026-06-07'
-- Each partition holds at most 24 × 3600 = 86,400 rows

Query 2 now requires fetching one partition per day in the range and merging in the application. That is an acceptable trade-off to keep partitions manageable.

  • Guarantees: With (device_id, sensor_type, date_bucket), every partition is capped at 86,400 rows at one reading per second, and every query in the design resolves to a set of partitions whose keys the client can compute.
  • Does not guarantee: That the cap survives a change in write rate. A sensor that moves to 10 readings per second puts 864,000 rows in each daily partition — the bucket width has to be re-derived whenever the busiest producer's rate changes.