Cassandra Data Modeling: A Best Practices Guide

Updated

Apache Cassandra data modeling illustration

In Cassandra the primary key is not an index, it is an address. The partition key decides which node stores the row, the clustering columns decide the sort order inside that partition, and any query that does not start from a partition key is a scan. That single fact produces every rule below, starting with the error you will hit first:

cqlsh> SELECT * FROM hw_v2.events WHERE action='login';
InvalidRequest: Error from server: code=2200 [Invalid query] message="Cannot execute this query as it
might involve data filtering and thus may have unpredictable performance. If you want to execute this
query despite the performance unpredictability, use ALLOW FILTERING"

Cassandra is not asking you to add ALLOW FILTERING. It is telling you the table is wrong for the question.

What ALLOW FILTERING actually costs

Here is the same table (50,000 rows across 2,000 partitions, PRIMARY KEY (user_id, event_time)), read two ways, with TRACING ON. First, by partition key:

cqlsh> SELECT * FROM hw_v2.events WHERE user_id='user1234' LIMIT 5;

 Executing single-partition query on events
 Acquiring sstable references
 Skipped 0/1 non-slice-intersecting sstables, included 0 due to tombstones
 Partition index found for sstable 1, size = 0
 Merged data from memtables and 1 sstables
 Read 5 live rows and 0 tombstone cells

Five rows wanted, five rows read. Now the same five rows, found by a non-key column:

cqlsh> SELECT * FROM hw_v2.events WHERE action='login' LIMIT 5 ALLOW FILTERING;

 Computing ranges to query
 Submitting range requests on 17 ranges with a concurrency of 1 (3549.6 rows per range expected)
 Executing seq scan across 1 sstables for (min(-9223372036854775808), min(-9223372036854775808)]
 Read 21500 live rows and 0 tombstone cells

21,500 rows read to return 5. On one node with one SSTable that is merely wasteful. On a real cluster “17 ranges” becomes a fan-out to every replica set that owns any part of the ring, the coordinator waits for all of them, and the cost grows with the size of the table rather than the size of the answer. That is what “unpredictable performance” means in the error message: the query’s cost is unrelated to what you asked for. The 50,000-row load, the error above and both traced reads, along with most of the later examples, are re-run by data-model-guide.sh against a throwaway single-node Cassandra 5.x on ports 9153, 7112 and 7311 that leaves an existing installation alone.

The fix is a second table, not a flag

If you need events by action, store events by action. Duplicating the write is the price of a bounded read:

CREATE TABLE events_by_user (
    user_id     text,
    event_time  timestamp,
    action      text,
    PRIMARY KEY (user_id, event_time)
) WITH CLUSTERING ORDER BY (event_time DESC);

CREATE TABLE events_by_action (
    action      text,
    event_time  timestamp,
    user_id     text,
    PRIMARY KEY (action, event_time, user_id)
) WITH CLUSTERING ORDER BY (event_time DESC);

SELECT * FROM events_by_action WHERE action='login' LIMIT 5 runs against the second table with no filtering error, because action is now a partition key. But action has only a few distinct values, so each action’s events end up in one ever-growing partition; the usual fix is a time bucket in the partition key, which the Cassandra data-modeling documentation calls bucketing. Note also that declaring CLUSTERING ORDER BY (event_time DESC) is what makes newest-first free: you do not need an ORDER BY at query time, and you could not sort by anything else anyway:

cqlsh> SELECT * FROM hw_v2.events WHERE user_id='user1' ORDER BY action;
InvalidRequest: ... message="Order by is currently only supported on the clustered columns of the
PRIMARY KEY, got action"

CQL tables are not schemaless

Rows in a CQL table cannot have different columns; that has been true since thrift was removed. Try it:

cqlsh> INSERT INTO hw_v2.events (user_id, event_time, action, extra_field)
       VALUES ('u3', 1754800000000, 'x', 'y');
InvalidRequest: Error from server: code=2200 [Invalid query] message="Undefined column name extra_field
in table hw_v2.events"

Every column must be declared with ALTER TABLE first. Rows are sparse (a column you never write costs nothing on disk), but the set of legal column names is fixed by the schema, exactly as in PostgreSQL or MySQL. Sparse cuts one way only: omitting a column writes nothing, while writing null into it leaves a tombstone the next read has to walk past.

Partition size: measure it, because nothing stops you

The advice “don’t let partitions get too large” is useless without a measurement, so here is the measurement. 40,000 rows written to one partition key, flushed, then nodetool tablehistograms:

hw_v2/wide histograms
Percentile      Read Latency     Write Latency          SSTables    Partition Size        Cell Count
                    (micros)          (micros)                             (bytes)
50%                     0.00              2.00              0.00           4866323             42510
Min                     0.00              0.00              0.00           4055270             35426
Max                     0.00           2299.00              0.00           4866323             42510

A 4.8 MB partition with 42,510 cells, accepted silently. Cassandra 5.0 does have partition-size guardrails, and the default cassandra.yaml ships both thresholds switched off, as the 5.0 configuration reference also states. From the shipped file:

# Guardrail to warn or fail when writing partitions larger than threshold.
# ...
# The two thresholds default to null to disable.
# partition_size_warn_threshold:
# partition_size_fail_threshold:

So: turn them on deliberately, and watch the Partition Size column. The same reference says the check runs only when sstables are written (flush and compaction), per sstable, and that exceeding the fail threshold only logs an error without interrupting the operation, so they warn rather than prevent. The structural fix is to put a bound in the partition key itself. For time series that means a bucket:

CREATE TABLE sensor_readings (
    sensor_id    text,
    day          date,        -- part of the partition key, not a clustering column
    reading_time timestamp,
    value        double,
    PRIMARY KEY ((sensor_id, day), reading_time)
) WITH CLUSTERING ORDER BY (reading_time DESC);

The double parentheses are load-bearing: ((sensor_id, day), reading_time) makes sensor_id and day a composite partition key, so each sensor-day is its own bounded partition. Write (sensor_id, day, reading_time) by mistake and sensor_id alone is the partition key, day becomes a clustering column, and the partition grows forever: the exact failure the bucket was meant to prevent. A query that spans several days then reads several partitions, which is fine; a query that spans a thousand days is a scan wearing a disguise.

The order to work in

Write down the queries first, in the imperative: “given a user, the last 20 events, newest first”. Each such sentence becomes one table whose partition key is the “given” and whose clustering columns are the ordering. Then check two things per table: can the partition key be reached from what the caller has in hand, and is the partition bounded by something other than optimism. If both hold, no query in this article’s first section can happen to you.

Photo of author
Sudhir P. founded HeatWare.com in 1999 and has built and operated it full-stack ever since; it is now used by more than 88,000 people. He writes here about the PostgreSQL, MySQL, Linux and DevOps work that keeps it running. Articles are rewritten only after the commands in them have actually been run, and the verification scripts are published alongside them so anyone can check the claims. Reach him at blog@heatware.net.