AI Hints
Home›System Design Tutorial›Case Study: Chat and Feeds
System Design · Lesson 98 of 120

Chat App: Storage and Groups

History at scale.

⏱ 2 min read▶ Video at 1:58:40🎓 Free
Watch this lesson in the System Design courseWatch on YouTube ↗Full System Design course

Two hundred gigabytes of messages arrive every day, and users scroll back through years of history. And a group message must reach up to a hundred people at once.

Chat App: Storage and Groups
From the video: Chat App: Storage and Groups
  • 200 GB a day
  • Years of history
  • Groups of 100

Storing messages

Messages are written constantly, and read mostly by chat, newest first. A wide column store, like Cassandra, fits well. The partition key is the chat ID, so one chat's messages live together. Within a chat, messages are sorted by a time based ID. Fetching the latest fifty is one fast read.

keyvalue
Storewide-column (Cassandra)
Partition keychat ID
Sort bytime-based message ID
Readlatest 50, one query

Ordering within a chat

Order matters within a chat. Here, each chat keeps a sequence counter, and every message gets the next number. Even if messages arrive at the server out of order, sorting by sequence shows them correctly. Run it. The chat reads in the right order, whatever order the messages arrived in.

chatorder.pypython
arrived = [
    {"chat": "sam-priya", "seq": 2, "text": "How are you?"},
    {"chat": "sam-priya", "seq": 1, "text": "Hi Priya!"},
    {"chat": "sam-priya", "seq": 3, "text": "Free for lunch?"},
]

history = sorted(arrived, key=lambda m: m["seq"])
for m in history:
    print(m["seq"], m["text"])
Output
1 Hi Priya!
2 How are you?
3 Free for lunch?

Group messages

For a group, the message is stored once, under the group's chat ID. Then the server fans it out, looking up each member's connection, and pushing a copy to everyone online. For very large groups, the fan out goes through a queue, so one busy group can't slow down everything else.

keyvalue
Store onceunder the group ID
Fan outpush to each member
Big groupsfan out via a queue
Offline memberssync later

Summary

Messages live in a wide column store, partitioned by chat, sorted by sequence. Groups store once, and fan out to members. Next, a news feed.

Key takeaways
  • Partition by chat
  • Sequence per chat
  • Fan out to groups
Next up: News Feed: Requirements — posts from friends