TweakCode
Building Blocks lessons

Partitioning

Pick the key every read has

Before you start

  • Partitioning

    Keys are spread over nodes by hashing. That lesson covers the ring.

    Open lesson

Why it matters

Chat history is always opened for a known conversation, but its messages come from different senders. Splitting by sender scatters Ana’s and Bo’s lines even though readers need them together and in one order. A history request for conversation c1 must be one ordered range read on one partition, without scanning a global message table.

Example

Partition chat by conversation

Messages are stored in order per conversation. Readers always know the conversation id. You will not scan a global message table.

Mental model

The idea

Keep one example in view

Partition chat by conversation

Messages are stored in order per conversation. Readers always know the conversation id. You will not scan a global message table.

Keep this exact scenario and its constraint in view while you build the model.

Use conversation c1, not sender Ana or Bo, as the partition key, and seq 1, 2, 3 as the ordering key; both 1:1 chat and group g7 then read history from one ordered range.

Store each message under a composite key of (conversation_id, seq). The partitioner uses c1, placing Ana’s c1:1 and c1:3 beside Bo’s c1:2; the sequence orders them within that partition. A group id such as g7 uses the same shape.

To page or reconnect, ask the c1 partition for sequence numbers greater than the client’s last one. That is a contiguous range rather than a merge across senders. The tradeoff is a single very busy conversation: all of its ordered writes still meet at one partition.

Visual anchor

Partition chat by conversation

range readpartition 0c1: 1, 2, 3partition 1c2: 1, 2partition 2Read c1
Now history for c1 is one range read on one partition: messages 1 to 3, already in order. Newer pages are "seq greater than the last one I have".

Pro

The rest of this is on Pro

The idea above is free. The walkthrough, the cost, and the practice are on Pro.