Home›Design›Chat and messaging
Course · Whole systemsLesson 31 of 330 read
Design doc · Chat and messaging

Chat and messaging

Where should chat messages go, when there are billions of them and every conversation is read newest first?

Applications like this: chat apps, support conversations, comments on a document. This page is written the way I write a database design doc: the workload first, then where each kind of data goes and why, then how it grows, what breaks, and what I rejected.

The short answerAt small and medium scale, PostgreSQL with messages partitioned by time and indexed by (conversation_id, sent_at). At large scale, a wide-column store such as Cassandra or ScyllaDB, partitioned by conversation and bucketed by time.
1 · The workload

What the application asks of the database

DimensionThis application
WritesHigh and steady. Every message is an insert.
ReadsThe latest page of one conversation, very often.
Read to writeRoughly balanced.
ConsistencyPer conversation, in order. Across conversations, loose.
LatencyDelivery feels instant: tens of milliseconds to store.
GrowthFast and forever, unless you set retention.
Connected

Real failures behind this design

These incidents are why the choices below matter. Each one is written up with its numbers and sources.

It happened
Check your own
2 · What goes where

Each kind of data, its store, and why

ApplicationMessagesPostgreSQL with time partitions, then Cassandra orScyllaDBSOURCE OF TRUTHConversations and membersThe relational databaseSOURCE OF TRUTHOnline status and typingRedis with a short TTLCAN BE LOSTAttachmentsObject storageSOURCE OF TRUTH

Solid arrows: the application writes there. Dashed arrows: a copy fed from the source of truth (change data capture, an outbox, or a cache fill), which can be rebuilt from it.

DataWhere it goesWhy
MessagesPostgreSQL with time partitions, then Cassandra or ScyllaDBOne conversation, newest first, is a range read on one partition. LSM stores take heavy insert rates well.
Conversations and membersThe relational databaseFew rows, many relationships, permissions.
Online status and typingRedis with a short TTLChanges every few seconds and does not need to survive a restart.
AttachmentsObject storageLarge and immutable.

How each family of store behaves under traffic: Database families.

3 · Data model

The core tables and the queries they serve

-- PostgreSQL
CREATE TABLE messages (
  conversation_id bigint NOT NULL,
  sent_at         timestamptz NOT NULL,
  id              bigint NOT NULL,
  sender_id       bigint NOT NULL,
  body            text,
  PRIMARY KEY (conversation_id, sent_at, id)
) PARTITION BY RANGE (sent_at);

-- Cassandra or ScyllaDB at scale
CREATE TABLE messages (
  conversation_id bigint, bucket int, sent_at timeuuid, sender_id bigint, body text,
  PRIMARY KEY ((conversation_id, bucket), sent_at)
) WITH CLUSTERING ORDER BY (sent_at DESC);
Step through it

One request, followed through the design

Step through one message from the sender to the recipient, and back when they scroll. Press Play, or use the arrows.

4 · How it grows

Start simple, change one thing at a time

  1. One relational databaseMessages table with the composite key above.
  2. Table too big to vacuum or back up comfortablyPartition by month and drop or archive old partitions.
  3. Insert rate beyond one primaryMove messages to a wide-column store. Keep conversations and members relational.

Scale it: watch this design grow

Pick a stage, then throw something at it. The numbers are a model to show the shape of each change, not a measurement; the measured numbers are in the lab notebooks.

5 · What breaks first

The failures to plan for

What happensWhat you seeWhat I do
One huge group chatA hot partition and slow readsBucket by time inside the conversation.
Deleting old messages with DELETEBloat and long-running deletesDrop whole partitions, or use TTLs in the wide-column store.
Unread counts computed on every readCOUNT(*) over a conversation on every app openKeep a per-member last-read marker and a counter.
6 · Alternatives

What I considered and did not pick

Cost. Storage grows forever. Set retention, or move old partitions to cheaper storage.

How this page was writtenFrom the engines' documentation and common practice. Measured on real servers: Cassandra message history read from one partition, in the notebooks. Before you build: check the anti-patterns, size it with the capacity calculator, and write your own version from the design doc template. Want a second opinion? Submit it for review.
7 · Where to run it

On-prem, managed, EC2 or Kubernetes

StageWhere it runs
Where I would startManaged relational with time partitions
When it growsManaged Cassandra-compatible service, or self-managed Cassandra or ScyllaDB on VMs

For a team without a dedicated database team. Who does which job in each option, and the full-cost comparison: Where to run the database.

8 · Estimate it

The numbers, worked live

The back-of-the-envelope numbers I would want before choosing anything. Move the assumptions to match your application. The link keeps your numbers, so a colleague sees the same ones.

Part 3 of 4 · Design · 24 pagesAll pages

Which database does my application need? What kind of application data goes in which database, and why, as design docs, plus the anti-patterns and the decisions behind them.