Sub topic 5
Modeling users, conversations, and messages
Prerequisites and scope
This chapter assumes you know basic relational and key-value storage ideas, and can read short Python and JavaScript. The previous chapters set the requirements and the architecture. Here we define the data the system stores. Later chapters cover the message flow, ID generation, and the choice of database.
A chat data model has to serve a few access patterns well. Each one drives a design decision below.
- Append a new message to a conversation.
- Read the latest N messages of a conversation, then page backward.
- List a user's conversations, ordered by recent activity.
- Count or find unread messages per conversation.
- Look up the members of a conversation, to fan messages out to them.
The core entities
Three entities carry most of the model: users, conversations, and messages. Two more tables link them: memberships and per-user read state.
| Entity | Purpose | Key fields |
|---|---|---|
| User | An account that can send and receive | `user_id`, `display_name`, `created_at` |
| Conversation | A container for messages, either a direct chat or a group | `chat_id`, `type`, `created_at`, `last_seq` |
| Membership | Links a user to a conversation | `chat_id`, `user_id`, `role`, `joined_at`, `last_read_seq` |
| Message | One entry in a conversation's log | `chat_id`, `seq`, `message_id`, `sender_id`, `client_msg_id`, `body`, `created_at` |
| Device | A client that receives messages for a user | `device_id`, `user_id`, `push_token`, `last_ack_seq` |
One model for direct and group chats
A common mistake is to build separate tables for one-to-one chats and groups. This doubles the code for sending, storing, and syncing. A better approach treats a direct chat as a conversation with exactly two members and type = "direct".
With this choice, the send path, the history query, and the sync logic are the same for both types. Group chat then differs only in how many members receive a message, which a later chapter covers under fan-out.
Direct chats need one extra rule: two users must not end up with two different direct conversations. A simple way is to derive a deterministic key from the pair.
def direct_chat_key(user_a: str, user_b: str) -> str:
low, high = sorted([user_a, user_b])
return f"direct:{low}:{high}"
assert direct_chat_key("alice", "bob") == direct_chat_key("bob", "alice")Store this key under a unique constraint. If both users try to start a chat at the same moment, one insert wins and the other reads the existing row.
Messages as an append-only log
Treat each conversation as an append-only log. Every message gets a sequence number seq that increases by one within that conversation. The pair (chat_id, seq) identifies a message and gives it a position.
This shape has useful properties:
- Reading recent history is a range scan:
chat_id = X AND seq <= N, newest first. - A client that knows its last seen
seqcan ask for everything after it. This is the basis of sync. - Gaps are detectable. If a client has
seq10 and then receives 12, it knows 11 is missing. - Unread counts become arithmetic:
last_seq - last_read_seq.
The sequence is per conversation, not global. A global counter becomes a bottleneck and gives no benefit, because users only need ordering inside one conversation. How the server assigns seq safely under concurrent writers is covered in the chapter on ordering.
Two identifiers per message
A message carries two IDs for different jobs.
| ID | Created by | Job |
|---|---|---|
| `client_msg_id` | The sending client | Lets the server recognize a retry of the same send |
| `message_id` or `(chat_id, seq)` | The server | Stable reference for storage, replies, and edits |
The client ID must stay unique per sender, because the server deduplicates on (chat_id, sender_id, client_msg_id). The server ID is authoritative. Never trust a client to choose ordering or the final ID.
A concrete message record
A stored message in JSON form looks like this.
{
"chat_id": "c1",
"seq": 42,
"message_id": "01HZX3K8M2",
"sender_id": "alice",
"client_msg_id": "5f0c1e8a-3d2b-4c7e-9a41-0b6d8e2f7a13",
"type": "text",
"body": "See you at 6?",
"reply_to_seq": 40,
"created_at": "2026-11-26T10:29:50Z",
"edited_at": null,
"deleted": false
}Some design notes on these fields:
typeallows values such astext,image,system. System messages record events like "Bob joined the group", and they travel through the same log so every client sees them in order.- For media,
bodyholds a reference (a URL or an object key) and metadata, not the bytes. The media chapter covers this. reply_to_seqpoints at another message in the same conversation. Referencing byseqkeeps the link inside one partition.deletedis a flag. Hard deletion would leave a hole in the sequence and confuse gap detection, so most systems keep the row and clear the body.created_atis the server time at acceptance. Do not sort by it. Clocks differ between servers, andseqis the source of truth.
Memberships and read state
The membership record answers two questions: who is in this conversation, and how far has each member read.
from dataclasses import dataclass
@dataclass
class Membership:
chat_id: str
user_id: str
role: str = "member"
last_read_seq: int = 0
def unread_count(last_seq: int, m: Membership) -> int:
return max(0, last_seq - m.last_read_seq)
m = Membership("c1", "bob", last_read_seq=40)
assert unread_count(42, m) == 2Storing a single last_read_seq per member is cheap. It avoids a read-receipt row per message per user. In a group of 500 people, per-message receipts would multiply writes by 500. A high-water mark scales with the number of members instead.
Because one user is indexed by chat_id here, you also need the reverse lookup: all conversations for a user. Keep the membership data in two views, one keyed by chat_id (for fan-out) and one keyed by user_id (for the conversation list). In a relational database this is two indexes. In a key-value or wide-column store it often means writing the data twice.
The conversation list
The inbox screen shows each conversation with its latest message and an unread badge. Computing that by joining memberships and messages on every load is slow. Instead, keep a small denormalized summary per user and conversation.
inbox = {} # (user_id, chat_id) -> summary
def update_inbox(user_id, chat_id, seq, preview, ts):
inbox[(user_id, chat_id)] = {
"last_seq": seq,
"preview": preview[:80],
"updated_at": ts,
}
update_inbox("bob", "c1", 42, "See you at 6?", "2026-11-26T10:29:50Z")
assert inbox[("bob", "c1")]["last_seq"] == 42This trades extra writes for fast reads. A chat app reads the inbox far more often than it sends messages, so the trade is usually worth it. The cost is that each message updates one summary row per member, so keep the summary small.
Design decisions and edge cases
Partitioning key
Choose chat_id as the partition key for messages. All messages of one conversation then sit together, which makes history reads fast and seq assignment local to one partition. The risk is a very busy conversation becoming a hot partition. For most chats this is acceptable. For very large groups, you can bucket by time, such as (chat_id, month), so no partition grows without bound.
Edits and deletions
Model an edit as an update to the existing message plus an edited_at timestamp. Clients that are online need to learn about it, so also emit an event in the conversation's log. Without that, a client that synced earlier never sees the change. One approach is a system-type log entry that references the target seq. A deletion works the same way.
Group membership changes
A user who joins later should usually not see earlier history. Record joined_at or a first_visible_seq on the membership and enforce it in history queries. A user who leaves keeps their old messages in the log, but is removed from the membership list so they receive nothing new.
Blocked and deleted users
Messages reference sender_id. If an account is deleted, keep the ID and render a placeholder name, instead of cascading deletes through every conversation.
Message size
Set a maximum body length, such as a few thousand characters. This bounds row size, protects clients, and keeps storage estimates reliable.
Common errors
- Separate tables for direct and group chat, which duplicates every code path.
- Sorting by timestamp instead of
seq, which produces unstable order when clocks drift. - One global sequence counter, which becomes a write bottleneck.
- Per-message read receipts for every member, which multiplies writes in large groups.
- Hard-deleting messages, which breaks gap detection.
- Missing a reverse index from user to conversations, so the inbox needs a full scan.
Exercise
A client holds messages up to seq 17 for chat "c9" and receives a message with seq 20. What does this tell the client, and what should it do? Also explain why the server stores a per-member lastreadseq instead of a read receipt per message.
Show answer
Seq 18 and 19 are missing. The client should request messages after seq 17 for chat "c9" (or specifically 18 and 19) and apply them in order before showing seq 20 as caught up. The server stores lastreadseq because it is a single high-water mark per member. A read receipt per message per member would multiply writes by the group size, while the high-water mark needs one small update and still yields unread counts as lastseq minus lastread_seq.
Exercise
Why is a direct chat modeled as a conversation with two members instead of a separate table, and how do you stop two users from creating two direct chats with each other?
Show answer
Using one conversation model means sending, storage, history, and sync code works for both direct and group chats. To prevent duplicates, derive a deterministic key from the sorted pair of user IDs, such as "direct:alice:bob", and store it under a unique constraint. If two inserts race, one fails and the caller reads the existing conversation.