Sub topic 9
Choosing storage for chat history
This chapter assumes you know the message model from earlier chapters (a chat_id, a per-chat seq, a sender_id) and the basics of relational and key-value stores. It explains how to pick a database for messages by starting from how the system reads and writes them.
Start with the access patterns
Chat history behaves differently from most application data:
- Writes dominate. Every message is an insert, and messages are almost never edited.
- Most reads fetch the newest messages of one chat, such as the last 50 when a user opens it.
- Scrolling up reads older pages of the same chat.
- Sync after reconnecting reads everything after the last
seqthe client has. - Reads rarely span chats, and joins are rare.
- Data grows without limit, and old messages are read much less often than new ones.
All of these reads are range scans inside one chat. That points to a store that keeps one chat's messages together and sorted.
Split the data by shape
| Data | Shape | Good fit |
|---|---|---|
| Users, groups, membership | Small, relational, needs joins and constraints | Relational database |
| Messages | Huge, append-only, keyed by chat | Wide-column or key-value store (Cassandra, HBase, DynamoDB) |
| Sessions, presence | Short-lived, frequently overwritten | In-memory store with expiry |
A single relational database can hold everything at small scale. The messages table is what outgrows it first, because its size and write rate grow far faster than the rest.
Key design: partition by chat, sort by seq
Use chat_id as the partition key and seq as the clustering (sort) key. Messages of one chat then sit together in order, and every pattern above becomes one sequential read. The example below uses SQLite to show the same query shapes that a wide-column store serves.
import sqlite3
db = sqlite3.connect(":memory:")
db.execute("""
CREATE TABLE messages (
chat_id TEXT NOT NULL,
seq INTEGER NOT NULL,
sender_id TEXT NOT NULL,
text TEXT NOT NULL,
PRIMARY KEY (chat_id, seq)
) WITHOUT ROWID
""")
for seq in range(1, 101):
db.execute("INSERT INTO messages VALUES (?, ?, ?, ?)",
("c1", seq, "alice", f"message {seq}"))
latest = db.execute(
"SELECT seq FROM messages WHERE chat_id = ? ORDER BY seq DESC LIMIT 3",
("c1",)).fetchall()
older = db.execute(
"SELECT seq FROM messages WHERE chat_id = ? AND seq < ? "
"ORDER BY seq DESC LIMIT 3", ("c1", 98)).fetchall()
missed = db.execute(
"SELECT seq FROM messages WHERE chat_id = ? AND seq > ? ORDER BY seq",
("c1", 98)).fetchall()
assert latest == [(100,), (99,), (98,)]
assert older == [(97,), (96,), (95,)]
assert missed == [(99,), (100,)]Common mistakes
- Sorting by timestamp. Clocks differ between servers and two messages can share a millisecond. Sort by the per-chat
seqinstead. - Unbounded partitions. A busy group chat can grow one partition until it becomes slow and uneven. Add a bucket to the key, such as
(chat_id, seq // 10000). A scan then crosses at most a few buckets. - Searching with the main store. Full-text search over messages needs a separate search index fed from the message stream. Do not add secondary indexes to the history table.
- Keeping everything on fast storage. Move old buckets to cheaper storage once reads of them become rare.
Exercise
A group chat has produced 40 million messages in one partition keyed by chat_id, and reads of the latest messages are slowing down. What change to the key fixes this, and what stays fast?
Show answer
Add a bucket to the partition key, for example (chat_id, seq // 10000). Each partition then holds a bounded number of messages. Reading the latest messages still hits one or two buckets, and sync by seq range stays sequential within each bucket.