Sub topic 9
Choosing storage for chat history
This chapter assumes you know the message and conversation model from the earlier chapters, the difference between relational and key-value stores, and the basics of indexing. You should also be comfortable with the per-chat sequence numbers introduced in the ordering chapter.
What chat storage has to do
Chat history is a write-heavy, append-mostly log. Before picking a database, list the access patterns the rest of the system needs.
- Append a message to a chat. This is the hot path. It happens on every send and must be fast and durable.
- Read the latest N messages of a chat. This runs every time a user opens a conversation.
- Page backwards through older messages. Users scroll up through history.
- Fetch messages after a known sequence number. Reconnecting clients and extra devices use this to catch up.
- Look up a message by ID. Replies, edits, deletes, and receipts all need this.
- Fetch a user's conversation list with unread counts. This is a different shape of data from the message log.
Almost every read is "messages of one chat, ordered by time or sequence." Almost none are "all messages across chats that match a condition." That narrow pattern drives the whole decision.
Two kinds of data, two kinds of store
Chat systems usually store two very different kinds of data.
| Data | Examples | Shape | Typical volume |
|---|---|---|---|
| Relational-style data | Users, profiles, group membership, settings, contacts | Small, updated in place, joined and filtered in many ways | Millions to billions of rows, low write rate |
| Message history | Messages, per-chat logs | Huge, append-only, read by chat and position | Billions of rows per day, very high write rate |
A relational database such as PostgreSQL or MySQL suits the first kind well. It gives transactions, secondary indexes, and flexible queries, and the data is small enough that replication and read replicas cope with the load.
The second kind is where a relational database becomes difficult. The next sections explain why and what to use instead.
Why a single relational database struggles with messages
A relational table with an index on (chat_id, seq) works well at small scale. At large scale the problems appear:
- Write volume. A system handling 100,000 messages per second needs far more write throughput than one primary can offer. You must shard.
- Sharding cost. Once you shard by
chat_id, you lose cross-shard joins and transactions. Much of the relational advantage disappears, but you still carry the operational weight. - Index growth. The index on a table with trillions of rows no longer fits in memory. Random reads then hit disk.
- Long tail of cold data. Most messages are never read again after a few days. A general-purpose database pays the same cost to store old rows as hot ones.
None of these makes a relational database impossible. Many successful systems ran on sharded MySQL for years. The point is that you are building a key-value store on top of it, so a store designed for that pattern is often a better fit.
Wide-column and key-value stores
Stores such as Cassandra, ScyllaDB, HBase, and DynamoDB organize data by a partition key and a sort key. All rows with the same partition key live together, and within a partition they are ordered by the sort key. This matches the chat access pattern directly.
- Partition key:
chat_id - Sort key:
seq(the per-chat sequence number)
Appending a message writes one row to one partition. Reading the latest 50 messages is a single range scan on one partition, in reverse order. Paging backwards means continuing the scan from the last sequence number you returned.
CREATE TABLE messages (
chat_id text,
seq bigint,
message_id bigint,
sender_id text,
client_msg_id text,
body text,
created_at timestamp,
PRIMARY KEY ((chat_id), seq)
) WITH CLUSTERING ORDER BY (seq DESC);
-- Latest 50 messages
SELECT * FROM messages WHERE chat_id = 'c1' LIMIT 50;
-- Page back: messages older than seq 9000
SELECT * FROM messages WHERE chat_id = 'c1' AND seq < 9000 LIMIT 50;
-- Catch up: messages after seq 9040, oldest first
SELECT * FROM messages WHERE chat_id = 'c1' AND seq > 9040
ORDER BY seq ASC LIMIT 100;This is CQL, the Cassandra query language. The PRIMARY KEY ((chat_id), seq) declaration puts chat_id in the partition key and seq as the clustering column. Because CLUSTERING ORDER BY (seq DESC) stores newest rows first, the "latest 50" query reads from the start of the partition.
Writes in these stores are cheap. They go to a commit log and an in-memory table, then flush to sorted files on disk (an LSM tree design). This favors append-heavy workloads. Replication across nodes is built in, and you add capacity by adding nodes.
The cost of this model
- Limited queries. You query by partition key. Searching message text, or "all messages from Alice across chats," needs a separate index, such as a search engine fed from the message stream.
- Eventual consistency by default. With quorum reads and writes you can get stronger guarantees, but at a latency cost. Because the server assigns
seqbefore writing, per-chat order does not depend on the database's clock. - Tombstones. Deleting messages writes markers that slow reads until compaction removes them. Heavy delete workloads need care.
- Operations. Running a large Cassandra cluster is real work: compaction tuning, repair, and capacity planning.
Partition size and hot partitions
Partitioning by chat_id alone has a trap. A very active group chat can grow a single partition without bound. Large partitions slow reads, compaction, and repair, and one chat can overload the nodes holding its replicas.
The standard fix is a bucket in the partition key. The bucket groups a time range or a sequence range.
PRIMARY KEY ((chat_id, bucket), seq)Here bucket could be seq / 10000 or a month number. A chat's data splits into bounded partitions. The cost is that reads which cross a bucket boundary need a second query. The client or service reads the newest bucket, and if it returns fewer rows than requested, it reads the one before.
Keep the bucket calculation in one place in the service. If different services compute it differently, they will not find each other's data.
Handling duplicates at the storage layer
The delivery guarantees chapter made sends idempotent using the key (chat_id, sender_id, client_msg_id). Storage has to enforce this, not only application memory. Two common approaches:
- Unique lookup table. Keep a second table keyed by the dedup key. Insert it with a conditional write (
IF NOT EXISTSin Cassandra). If the insert fails, a message with that key already exists, so return the stored one. - Deterministic row identity. Make the dedup key part of the primary key, so a retry overwrites the same row with identical data.
The first approach costs an extra conditional write, which is slower in Cassandra because it uses a consensus protocol. The second is cheap, but you must have the seq before you write, so the sequence assignment still needs to be consistent for a given retry.
Hot, warm, and cold data
Message access drops off sharply with age. You can use that to control cost.
Instead of a diagram you cannot verify, here is the tiering as a table.
| Tier | Age | Storage | Access |
|---|---|---|---|
| Hot | Last days | In-memory cache plus SSD-backed nodes | Every conversation open |
| Warm | Weeks to months | SSD or HDD in the main cluster | Scrolling back |
| Cold | Older | Compressed objects in blob storage | Rare, higher latency acceptable |
A cache of the most recent messages per active chat, for example in Redis, absorbs most reads. A background job moves old partitions to cheaper storage. Clients then see a slower load when they scroll very far back, which is usually acceptable.
Choosing: decision criteria
Use these questions to decide.
- What is the write rate? Under a few thousand writes per second, a single well-indexed relational database with replicas is simpler and usually enough.
- Does your team already operate it? A familiar database that you can run reliably often beats a better-suited one you cannot.
- Do you need transactions across entities? If messages must be written together with other records atomically, a relational store makes that easy.
- How long do you keep history? Long retention favors tiering and cheap storage.
- Do you need search? No primary message store handles full-text search well. Plan a separate index.
Common errors
- Using
created_atas the sort key. Clocks on different servers disagree, so two messages can sort wrongly. Sort by the server-assignedseq. - Letting partitions grow without a bucket.
- Storing the conversation list in the message table. Unread counts and last-message previews belong in a per-user table keyed by
user_id. - Treating a cache as the source of truth. The cache holds copies, and the message store holds the record.
Exercise
A group chat produces about 50 messages per second during a live event, and your wide-column table is partitioned by chat_id alone with seq as the sort key. What problem do you expect, and how do you fix it?
Show answer
The partition for that chat grows very large and becomes a hot partition, which slows reads, compaction, and repair on the nodes that hold it. Add a bucket (for example seq / 10000 or a month number) to the partition key so the chat's data splits into bounded partitions. Reads that cross a bucket boundary then need a second query for the previous bucket.
Exercise
Why should the sort key for messages be the server-assigned seq and not created_at?
Show answer
created_at comes from clocks that can differ between servers, so messages can be ordered incorrectly or tie. The per-chat seq is assigned in one place and increases strictly, so it gives a stable order that also supports "fetch everything after seq N" for catch-up.