Scrivio Interview library
DesignIntermediate7 min read · updated 12 November 2026

Model a Cassandra table for 'latest 50 messages per conversation' with Spring Data Cassandra. Explain partition and clustering keys and the pitfalls.

We design the table for the one query it serves: the partition key is the conversation id plus a time bucket such as the month, the clustering columns are the message time in descending order plus the message id for uniqueness, so SELECT ... LIMIT 50 reads the newest 50 rows straight from the top of one partition. In Spring Data Cassandra that is @PrimaryKeyColumn with type PARTITIONED for the key columns and CLUSTERED with Ordering.DESCENDING. The pitfalls are partitions that grow without bound, which the bucket prevents, tombstones from frequent deletes, and any query that needs ALLOW FILTERING, which signals a missing table.

Why this question is asked

Chat history is one of the workloads Cassandra handles best: a huge volume of small writes, and reads that almost always ask for the latest messages of one conversation. But it is also a classic place to get the model subtly wrong, with a design that is fast in testing and becomes slow for the busiest conversations a year later. Interviewers ask this design question to see whether we think in query-first tables, choose keys deliberately, and know Cassandra's operational traps. In this answer, we will recap the query-first principle, design the table, map it in Spring Data Cassandra, add time buckets against unbounded partitions, deal with tombstones, and see what to do when a new query appears.

1A Quick Recap: Design Tables per Query

In Cassandra, the partition key decides which nodes store a row, and clustering columns decide the order of rows within a partition. An efficient query names the partition key and reads a contiguous slice of sorted rows. So instead of designing a normalised schema and writing queries against it, we start from each query and design a table that answers it with one partition read. If the application has three different queries, it may well have three tables holding the same messages, written together.

Our query is: give me the latest 50 messages of conversation c-123. That tells us almost the whole design.

2Designing the Table

The conversation id must be in the partition key, since the query always names it. The rows inside must be sorted newest first, so message time is a clustering column in descending order. Two messages can share a timestamp to the millisecond, so we add the message id as a second clustering column; otherwise the second message would silently overwrite the first, because a row with the same primary key is an update in Cassandra. Using a timeuuid, a UUID that embeds a timestamp, for the message id is a common alternative that gives both order and uniqueness in one column.

SQL
CREATE TABLE messages_by_conversation (
conversation_id text,
bucket text, -- '2026-11': one partition per conversation per month
sent_at timestamp,
message_id uuid,
sender_id text,
body text,
PRIMARY KEY ((conversation_id, bucket), sent_at, message_id)
) WITH CLUSTERING ORDER BY (sent_at DESC, message_id DESC);
SELECT sender_id, body, sent_at FROM messages_by_conversation
WHERE conversation_id = 'c-123' AND bucket = '2026-11'
LIMIT 50; -- newest 50, read from the top of one partition
One partition, rows in clustering order
sent_at (DESC)message_idsenderbody
2026-11-05 10:42:07.3119f1c...u-7See you then
2026-11-05 10:42:07.3114a02...u-3Great
2026-11-05 10:41:55.02077be...u-7Lunch at 12?
... older rows ...LIMIT 50 stops here
Partition (c-123, 2026-11). Two messages share a millisecond; message_id keeps both.

Because the rows are stored newest first, the replicas read the first 50 rows of the partition and stop. No sorting happens at query time, and the cost does not depend on how many older messages the conversation has. If the current month has fewer than 50 messages, the application queries the previous bucket for the rest, which is a second cheap partition read.

3Mapping It in Spring Data Cassandra

For a composite key, a separate key class keeps the entity readable. @PrimaryKeyClass marks the class, and each column carries its role and order.

Java
@PrimaryKeyClass
public record MessageKey(
@PrimaryKeyColumn(name = "conversation_id", ordinal = 0, type = PrimaryKeyType.PARTITIONED) String conversationId,
@PrimaryKeyColumn(name = "bucket", ordinal = 1, type = PrimaryKeyType.PARTITIONED) String bucket,
@PrimaryKeyColumn(name = "sent_at", ordinal = 2, type = PrimaryKeyType.CLUSTERED,
ordering = Ordering.DESCENDING) Instant sentAt,
@PrimaryKeyColumn(name = "message_id", ordinal = 3, type = PrimaryKeyType.CLUSTERED,
ordering = Ordering.DESCENDING) UUID messageId) {}
@Table("messages_by_conversation")
public record Message(@PrimaryKey MessageKey key, String senderId, String body) {}
public interface MessageRepository extends CassandraRepository<Message, MessageKey> {
@Query("SELECT * FROM messages_by_conversation WHERE conversation_id = ?0 AND bucket = ?1 LIMIT 50")
List<Message> latest(String conversationId, String bucket);
}

The ordering attribute only matters when Spring Data creates the schema; in production the CQL migration defines CLUSTERING ORDER BY, and the two must agree. For paging further back in history, Cassandra paging state, exposed through Slice and CassandraPageRequest, continues from where the last page stopped instead of using offsets, which Cassandra does not support efficiently.

4Pitfall 1: Unbounded Partitions

Without the bucket, the partition key would be conversation_id alone, and a busy group chat would put every message it ever received into one partition on the same three nodes. Large partitions make compaction, repair and reads of that partition slow and can create hot spots; common guidance is to keep partitions well under about 100 MB, check the guidance for your version. Bucketing by month bounds each partition to one month of one conversation. The bucket size is a trade-off: smaller buckets keep partitions small but mean more reads to fill 50 messages for quiet conversations. Month suits most chat traffic; a support system with very busy channels might bucket by day.

5Pitfall 2: Tombstones From Deletes

Cassandra does not delete data in place. A delete writes a tombstone, a marker saying this row is gone, and the real removal happens only during compaction after gc_grace_seconds, ten days by default, so that replicas that missed the delete still learn about it. Reads must skip over tombstones, so a partition with thousands of deleted messages at its top makes reading the newest 50 slow, and past a threshold (100,000 by default, configurable) Cassandra aborts the query.

So we avoid frequent deletes. If messages must disappear after 90 days, we write them with a TTL, USING TTL 7776000, and pair it with TimeWindowCompactionStrategy, which groups data by write time so whole files of expired rows can be dropped at once. Expired TTL data still becomes tombstones, so TTLs are not free, but with time-window compaction their cost is far lower than scattered deletes. For a user who edits or unsends a message, an update that marks it as deleted is often cheaper than a real delete.

6When a New Query Appears

Product will ask for more: all messages a user sent, or unread messages per user. These do not name a conversation, so they cannot use our table, and the temptation is a derived method or ALLOW FILTERING. Needing ALLOW FILTERING is the signal of a missing table. We add messages_by_sender keyed by (sender_id, bucket) and write each message to both tables, typically in a logged batch when they must stay consistent, accepting the extra write in exchange for cheap reads.

7Follow-up questions

Why not use the message id alone as the clustering column?

A random UUID gives no time order, so the newest 50 would not be at the top. A timeuuid works on its own because it sorts by its embedded time; a separate timestamp plus a random UUID is easier to read and query by time range.

How do you find the previous bucket efficiently?

The bucket is derived from time, so the application computes the previous month. For conversations with long gaps, a small table conversation_buckets listing the non-empty buckets per conversation avoids probing many empty months.

What consistency level would you use?

LOCAL_QUORUM for writes and reads is a common choice: a read after a write in the same data centre then sees the message, because a majority of replicas acknowledged both.

8Conclusion

In this answer, we designed messages_by_conversation for its one query: a partition key of conversation id plus a month bucket, and clustering columns sent_at descending plus message_id, so the newest 50 messages come from the top of one partition with LIMIT 50. We mapped it with @PrimaryKeyClass and @PrimaryKeyColumn using PARTITIONED and CLUSTERED with descending order. We bounded partitions with buckets, avoided tombstone-heavy deletes in favour of TTLs with time-window compaction, and treated any need for ALLOW FILTERING as a sign that a new table is missing.

What to say in the interviewAbout 90 seconds aloud

Open with

In Cassandra I design the table for the query, so I start from latest 50 messages of a conversation. The conversation id must be in the partition key, and I add a time bucket, say the month, so the partition key is conversation id plus bucket.

Then, if they want more

The clustering columns are sent_at descending and then message_id, also descending. The message id matters because two messages can share a millisecond, and in Cassandra the same primary key means an update, so without it one message would overwrite the other.

With that, SELECT with LIMIT 50 reads the top of one partition, already sorted, and stops; if the month has fewer than 50, I read the previous bucket.

In Spring Data Cassandra I would use a @PrimaryKeyClass with @PrimaryKeyColumn entries, type PARTITIONED with ordinals for conversation id and bucket, and CLUSTERED with Ordering.DESCENDING for the time and id, plus a @Query with the limit. The pitfalls: without the bucket, a busy group chat becomes one huge, ever-growing partition on three nodes, which hurts compaction, repair and reads.

Deletes write tombstones that reads must skip, and enough of them make the latest-50 query slow or fail, so I avoid frequent deletes and use TTLs with time-window compaction for retention. And if a new requirement needs ALLOW FILTERING, like messages by sender, that tells me I am missing a table, so I add messages_by_sender and write to both.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
Spring Data reference
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Model a Cassandra table for 'latest 50 messages per conversation' with Spring Data...": https://scrivio-interview-library.netlify.app/databases/spring-data-nosql/3dfc2a7598/