knaxuslearn · build · ship

Projects / Chat store / Phase 2

Phase 2 of 4 · about 2.5 hours

One table per question

You end with two tables that hold the same messages, written together, plus a unique username, expiring data and a counter.

Step 2.1: A table for the second question (about 20 minutes)

"Show me everything Ben has written" is a different question, so it needs a different table. The author is the partition key, and the messages are sorted newest first, as before:

CREATE TABLE IF NOT EXISTS chat.messages_by_user (
  author  text,
  msg_id  timeuuid,
  room_id text,
  body    text,
  PRIMARY KEY ((author), msg_id)
) WITH CLUSTERING ORDER BY (msg_id DESC);
DESCRIBE TABLE chat.messages_by_user;

This feels wrong at first if you come from relational databases. We are storing the same message twice. In Cassandra that is the normal way. Storage is cheap, and a read that touches a single partition is the thing worth paying for.

One message, two tables, one batch.

Step 2.2: Write both together (about 35 minutes)

To keep the two tables in step we write each message to both inside a batch. A logged batch makes sure that either both writes eventually happen or neither does. This statement rewrites the five messages from Phase 1 into both tables, and adds three new ones:

BEGIN BATCH
  INSERT INTO chat.messages_by_room (room_id, msg_id, author, body) VALUES ('general', minTimeuuid('2026-11-01 09:00:00+0000'), 'asha', 'Good morning');
  INSERT INTO chat.messages_by_user (author, msg_id, room_id, body) VALUES ('asha', minTimeuuid('2026-11-01 09:00:00+0000'), 'general', 'Good morning');
APPLY BATCH;
BEGIN BATCH
  INSERT INTO chat.messages_by_room (room_id, msg_id, author, body) VALUES ('general', minTimeuuid('2026-11-01 09:05:00+0000'), 'ben', 'Morning! Standup at 09:10?');
  INSERT INTO chat.messages_by_user (author, msg_id, room_id, body) VALUES ('ben', minTimeuuid('2026-11-01 09:05:00+0000'), 'general', 'Morning! Standup at 09:10?');
APPLY BATCH;
BEGIN BATCH
  INSERT INTO chat.messages_by_room (room_id, msg_id, author, body) VALUES ('general', minTimeuuid('2026-11-01 09:30:00+0000'), 'asha', 'Notes are in the doc');
  INSERT INTO chat.messages_by_user (author, msg_id, room_id, body) VALUES ('asha', minTimeuuid('2026-11-01 09:30:00+0000'), 'general', 'Notes are in the doc');
APPLY BATCH;
BEGIN BATCH
  INSERT INTO chat.messages_by_room (room_id, msg_id, author, body) VALUES ('general', minTimeuuid('2026-11-01 10:00:00+0000'), 'chitra', 'Lunch at one?');
  INSERT INTO chat.messages_by_user (author, msg_id, room_id, body) VALUES ('chitra', minTimeuuid('2026-11-01 10:00:00+0000'), 'general', 'Lunch at one?');
APPLY BATCH;
BEGIN BATCH
  INSERT INTO chat.messages_by_room (room_id, msg_id, author, body) VALUES ('random', minTimeuuid('2026-11-01 09:15:00+0000'), 'ben', 'Anyone seen the match?');
  INSERT INTO chat.messages_by_user (author, msg_id, room_id, body) VALUES ('ben', minTimeuuid('2026-11-01 09:15:00+0000'), 'random', 'Anyone seen the match?');
APPLY BATCH;
BEGIN BATCH
  INSERT INTO chat.messages_by_room (room_id, msg_id, author, body) VALUES ('general', minTimeuuid('2026-11-01 10:30:00+0000'), 'ben', 'Yes, one works');
  INSERT INTO chat.messages_by_user (author, msg_id, room_id, body) VALUES ('ben', minTimeuuid('2026-11-01 10:30:00+0000'), 'general', 'Yes, one works');
APPLY BATCH;
BEGIN BATCH
  INSERT INTO chat.messages_by_room (room_id, msg_id, author, body) VALUES ('random', minTimeuuid('2026-11-01 10:45:00+0000'), 'chitra', 'What a finish');
  INSERT INTO chat.messages_by_user (author, msg_id, room_id, body) VALUES ('chitra', minTimeuuid('2026-11-01 10:45:00+0000'), 'random', 'What a finish');
APPLY BATCH;
BEGIN BATCH
  INSERT INTO chat.messages_by_room (room_id, msg_id, author, body) VALUES ('general', minTimeuuid('2026-11-01 11:00:00+0000'), 'asha', 'Back after lunch');
  INSERT INTO chat.messages_by_user (author, msg_id, room_id, body) VALUES ('asha', minTimeuuid('2026-11-01 11:00:00+0000'), 'general', 'Back after lunch');
APPLY BATCH;
SELECT count(*) AS in_room_table FROM chat.messages_by_room;
SELECT count(*) AS in_user_table FROM chat.messages_by_user;

Both counts should be 8. Because inserts are upserts, rewriting the five old messages did not duplicate them.

Pitfall: a batch in Cassandra is for keeping tables in step. It is not a way to make many writes fast. A batch that touches many partitions puts extra load on the node that coordinates it.

Step 2.3: Read by author (about 20 minutes)

Now the question that failed in Step 1.5 has a table:

SELECT toTimestamp(msg_id) AS sent_at, room_id, body
FROM chat.messages_by_user
WHERE author = 'ben';

Ben has three messages, newest first.

Step 2.4: A username can be taken once (about 30 minutes)

Nothing in a normal write stops two people from claiming the same name. IF NOT EXISTS makes the write conditional. It is a lightweight transaction, which uses extra rounds between machines to agree on the answer, so it is slower than a normal write and should be used rarely, for things like usernames:

CREATE TABLE IF NOT EXISTS chat.users (
  username     text PRIMARY KEY,
  display_name text,
  created_at   timestamp
);
INSERT INTO chat.users (username, display_name, created_at)
VALUES ('asha', 'Asha R', '2026-11-01 08:00:00+0000') IF NOT EXISTS;
INSERT INTO chat.users (username, display_name, created_at)
VALUES ('asha', 'Someone else', '2026-11-01 08:01:00+0000') IF NOT EXISTS;
SELECT username, display_name FROM chat.users;

Each conditional insert prints a result table with an [applied] column. The first should say True. The second should say False, and show the row that is already there, so asha keeps her name.

Step 2.5: Data that expires (about 25 minutes)

A "typing..." indicator should not live forever. USING TTL 60 gives the written data a time to live of 60 seconds, after which Cassandra deletes it by itself:

CREATE TABLE IF NOT EXISTS chat.typing (
  room_id  text,
  username text,
  status   text,
  PRIMARY KEY ((room_id), username)
);
INSERT INTO chat.typing (room_id, username, status) VALUES ('general', 'ben', 'typing') USING TTL 60;
SELECT room_id, username, status, TTL(status) AS seconds_left FROM chat.typing WHERE room_id = 'general';

TTL(status) shows the seconds left, a little under 60. Run the SELECT again after a minute and the row is gone.

Step 2.6: A counter (about 25 minutes)

Counting unread messages by reading and adding one would be a race, as the other database projects showed. Cassandra has a counter type that does the addition for you:

CREATE TABLE IF NOT EXISTS chat.unread (
  room_id  text,
  username text,
  unread   counter,
  PRIMARY KEY ((room_id), username)
);
UPDATE chat.unread SET unread = unread + 1 WHERE room_id = 'general' AND username = 'chitra';
UPDATE chat.unread SET unread = unread + 1 WHERE room_id = 'general' AND username = 'chitra';
UPDATE chat.unread SET unread = unread + 1 WHERE room_id = 'general' AND username = 'chitra';
UPDATE chat.unread SET unread = unread - 2 WHERE room_id = 'general' AND username = 'chitra';
SELECT room_id, username, unread FROM chat.unread;

Three plus ones and a minus two should leave 1. A counter table can contain only counters beside its key.

Phase 2 done

Each question has a table, the tables are written together, and you have a unique name, an expiry and a counter. Now we let the data grow.