The Ring, CQL, Keyspaces and Key Design

Article · 9:00

Masterless architecture, token ranges and virtual nodes, the coordinator, keyspaces and replication, partition and clustering keys, and where CQL is not SQL.

Every node is identical. There is no primary, no configuration node and no special role. A client connects to any node, which becomes the coordinator for that request: it works out which nodes own the data, contacts them, applies the consistency level and returns the result. Losing a node removes capacity and nothing else - no election, no promotion, no reconfiguration.

Data is placed by token. The partition key is hashed (Murmur3 by default) to a token, and the token space is divided among nodes. Virtual nodes (num_tokens, 16 in recent versions) give each node many small ranges rather than one large one, which makes the ring balance better and makes adding and removing nodes smoother.

The partition is the unit of everything. All rows sharing a partition key live on the same nodes, sorted by the clustering columns, and are read together. A query that reads one partition is fast at any cluster size; a query that must visit many partitions is a multi-node scatter-gather and is slow in a way that gets worse as you grow. This is why "one table per query" is the rule - you shape the partition so that each query reads exactly one.

Partition size must be bounded deliberately. The practical guidance: aim under 100 MB and under 100,000 rows per partition. Larger partitions cause long compaction pauses, heap pressure, slow reads and wide variance in latency. The usual technique is a bucket in the partition key - (user_id, day) rather than (user_id) - which bounds growth by time and is the single most common Cassandra modelling pattern.

Where CQL is not SQL, and this list is the most useful thing in Module 1:

  • No joins, and no plan to add them.
  • WHERE must constrain the partition key, or the query is rejected - unless you add ALLOW FILTERING, which permits a full cluster scan. ALLOW FILTERING is not a hint, it is a warning, and it should essentially never appear in application code.
  • ORDER BY only works on clustering columns, in the order they are defined, and only ascending or descending relative to the defined order.
  • Aggregations exist (COUNT, SUM, AVG) and are computed by the coordinator, so SELECT COUNT(*) FROM table on a large table is a cluster-wide scan that may simply time out.
  • No OFFSET. Paging is by the driver's paging state, or by a clustering-column cursor.
  • An UPDATE on a non-existent row creates it - there is no distinction between insert and update, because both are just writes. This is called an upsert and it means a typo in a primary key silently creates a row.
  • A SELECT of a row that does not exist returns no error and no rows, and you cannot tell "never existed" from "deleted" without looking at tombstones.

Laboratory exercise 1 - provision and verify.

Stand up a three-node cluster. Confirm it with nodetool status, and record the token ranges, the ownership percentages and the num_tokens setting.

Create a keyspace with NetworkTopologyStrategy and RF=3, and explain each part of the replication setting in your README.

Load at least two million rows modelling the capstone's event feed, with a partition key that includes a time bucket. Record the resulting partition size distribution with nodetool tablehistograms.

Then demonstrate the CQL boundaries, each with its exact error: a WHERE on a non-key column; the same with ALLOW FILTERING and its timing against the partition-key version; ORDER BY on a non-clustering column; SELECT COUNT(*) on the whole table; and an UPDATE on a key that does not exist, showing the row created.

Finally, demonstrate the unbounded partition: write a table keyed only on user_id, load 500,000 rows for one user, and record what nodetool tablehistograms says and how the read latency compares with the bucketed version.

Deliverable: an idempotent schema script, a README explaining the replication settings, nodetool status and ring output with the ownership explained, the partition size distribution, the five CQL boundary demonstrations with their errors and timings, and the unbounded partition comparison.

-- ------------------------------------------------------------------
-- A THREE-NODE cluster. Not one. Consistency levels, replication and
-- repair do not exist on a single node.
-- ------------------------------------------------------------------
--   docker compose up -d   (cassandra:5 x3, seeds configured)
--   docker exec -it cass1 cqlsh
--
--   nodetool status
--   Datacenter: dc1
--   ==============
--   --  Address     Load      Tokens  Owns(effective)  Host ID  Rack
--   UN  172.18.0.2  1.21 GiB  16      100.0%           ...      rack1
--   UN  172.18.0.3  1.19 GiB  16      100.0%           ...      rack1
--   UN  172.18.0.4  1.22 GiB  16      100.0%           ...      rack1
--
--   UN = Up/Normal. Owns 100% each because RF=3 on a 3-node cluster:
--   every node holds every partition. Tokens 16 = VIRTUAL NODES, so
--   each node owns 16 small ranges rather than one large one, which
--   balances better and makes adding nodes smoother.
--
--   nodetool ring
--   nodetool describecluster
--   nodetool gossipinfo

SELECT cluster_name, release_version, partitioner FROM system.local;
--   org.apache.cassandra.dht.Murmur3Partitioner

-- ------------------------------------------------------------------
-- Keyspace and replication. Every part of this matters.
-- ------------------------------------------------------------------
CREATE KEYSPACE IF NOT EXISTS feed
WITH replication = {
  'class': 'NetworkTopologyStrategy',   -- ALWAYS this, even with one
                                        -- DC. SimpleStrategy ignores
                                        -- racks and datacentres and
                                        -- cannot be migrated cleanly.
  'dc1': 3                              -- RF per DATACENTRE
} AND durable_writes = true;            -- keep the commit log on

USE feed;

-- ------------------------------------------------------------------
-- THE PARTITION IS THE UNIT OF EVERYTHING.
-- ------------------------------------------------------------------
CREATE TABLE events_by_user_day (
    user_id    uuid,
    day        date,            -- THE BUCKET. See below.
    event_at   timestamp,
    event_id   timeuuid,
    kind       text,
    payload    text,
    PRIMARY KEY ((user_id, day), event_at, event_id)
    --           ^^^^^^^^^^^^^^^  ^^^^^^^^^^^^^^^^^^
    --           PARTITION key    CLUSTERING columns
) WITH CLUSTERING ORDER BY (event_at DESC, event_id DESC)
  AND comment = 'One partition per user per day. Bounded by design.';

--   PARTITION KEY  -> hashed to a token -> decides WHICH NODES hold it
--   CLUSTERING     -> the SORT ORDER WITHIN the partition, on disk
--
-- A query that reads ONE partition is fast at ANY cluster size.
-- A query that must visit MANY partitions is a scatter-gather and
-- gets WORSE as you grow. That is why "one table per query" is the
-- rule: you shape the partition so each query reads exactly one.

-- ------------------------------------------------------------------
-- BOUND THE PARTITION. Aim < 100 MB and < 100,000 rows.
-- ------------------------------------------------------------------
-- BAD - unbounded. A heavy user's partition grows forever:
CREATE TABLE events_by_user_bad (
    user_id  uuid,
    event_at timestamp,
    event_id timeuuid,
    payload  text,
    PRIMARY KEY (user_id, event_at, event_id)
);
-- 500,000 rows for one user -> long compaction pauses, heap
-- pressure, slow reads, wide latency variance. Demonstrate it:
--   nodetool tablehistograms feed.events_by_user_bad
--   Partition Size (bytes)  max: 412,000,000     <- 412 MB. Too big.
--   Cell Count              max:   4,100,000

-- GOOD - the day bucket bounds growth by TIME. The single most
-- common Cassandra modelling pattern:
--   PRIMARY KEY ((user_id, day), event_at, event_id)
--   a very heavy user: ~20,000 rows/day -> ~8 MB. Fine, forever.
--
-- Choose the bucket from the WRITE RATE: hour for high-volume,
-- month for low. The query then reads one bucket, or a few:
SELECT * FROM events_by_user_day
WHERE user_id = 7f3c... AND day = '2026-11-30' LIMIT 50;

SELECT * FROM events_by_user_day
WHERE user_id = 7f3c... AND day IN ('2026-11-28','2026-11-29','2026-11-30')
LIMIT 50;
--                        ^^ an IN on the partition key is a
--                        scatter-gather over that many partitions.
--                        A FEW is fine; dozens is not - the
--                        coordinator holds all the results.

-- ------------------------------------------------------------------
-- WHERE CQL IS NOT SQL. The most useful list in Module 1.
-- ------------------------------------------------------------------
-- 1. WHERE MUST CONSTRAIN THE PARTITION KEY.
SELECT * FROM events_by_user_day WHERE kind = 'login';
--   InvalidRequest: 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

SELECT * FROM events_by_user_day WHERE kind = 'login' ALLOW FILTERING;
--   This now reads EVERY PARTITION ON EVERY NODE.
--   ALLOW FILTERING IS NOT A HINT, IT IS A WARNING. It should
--   essentially never appear in application code. Time it against
--   the partition-key query and keep both numbers.

-- 2. ORDER BY only on CLUSTERING COLUMNS, in their defined order.
SELECT * FROM events_by_user_day
WHERE user_id = 7f3c... AND day = '2026-11-30' ORDER BY kind;
--   InvalidRequest: Order by is currently only supported on the
--   clustered columns of the PRIMARY KEY

-- 3. AGGREGATIONS are computed by the COORDINATOR.
SELECT COUNT(*) FROM events_by_user_day;
--   A CLUSTER-WIDE SCAN. On a large table it times out:
--   ReadTimeout: Error from server: code=1200
-- Within one partition it is fine:
SELECT COUNT(*) FROM events_by_user_day
WHERE user_id = 7f3c... AND day = '2026-11-30';

-- 4. NO OFFSET. Page with the driver's paging state, or a cursor on
--    the clustering column:
SELECT * FROM events_by_user_day
WHERE user_id = 7f3c... AND day = '2026-11-30'
  AND event_at < '2026-11-30 14:04:00+0000'   -- the cursor
LIMIT 50;

-- 5. UPSERT: an UPDATE on a non-existent row CREATES IT. There is no
--    insert/update distinction - both are just writes.
UPDATE events_by_user_day SET kind = 'typo'
WHERE user_id = 00000000-0000-0000-0000-000000000000
  AND day = '2026-11-30' AND event_at = '2026-11-30 00:00:00+0000'
  AND event_id = 11111111-1111-1111-1111-111111111111;
--   No error. THE ROW NOW EXISTS. A typo in a primary key silently
--   creates a row, and nothing will tell you.
--
--   Conversely, INSERT overwrites without complaint. The only way to
--   get "fail if it exists" is IF NOT EXISTS, which is a lightweight
--   transaction and has a real cost (Module 3).

-- 6. A SELECT for a missing row returns NO ERROR AND NO ROWS, and
--    you cannot tell "never existed" from "deleted" - the deleted
--    case leaves a TOMBSTONE, which Module 4 is largely about.

-- ------------------------------------------------------------------
-- TRACING: the most instructive diagnostic in Cassandra. Use it.
-- ------------------------------------------------------------------
TRACING ON;
SELECT * FROM events_by_user_day
WHERE user_id = 7f3c... AND day = '2026-11-30' LIMIT 50;
--   activity                                      | source     | elapsed
--   Execute CQL3 query                            | 172.18.0.2 |       0
--   Parsing SELECT ...                             | 172.18.0.2 |      74
--   reading data from /172.18.0.3                 | 172.18.0.2 |     311
--   Merged data from memtables and 2 sstables     | 172.18.0.3 |    1842
--   Read 50 live rows and 0 tombstone cells       | 172.18.0.3 |    1901
--                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ THE line to read.
--   It shows the coordinator, the replicas contacted, the SSTables
--   touched and the TOMBSTONES SCANNED. Module 4 lives here.
TRACING OFF;

Discussion

No questions on this topic yet. Sign in to ask the first one.