Message storage, presence and multi-device sync
Design message storage partitioned by conversation and time bucket, measure what the bucket width costs, keep presence as soft state with heartbeats and a TTL, sync several devices with cursors, and set limits on group fan-out.
Contentsand lesson path
On this page
- Why it matters
- Storing messages by conversation
- Presence as soft state
- Several devices, one history
- Group fan-out and its limits
- Check your understanding
- Apply it
- Review prompt
Lessons of Chat System Design
- Scoping chat and estimating connections Worked example · 20 min
- Real-time transports and connection gateways Concept · 20 min
- Ordering, receipts and retries Worked example · 25 min
- Message storage, presence and multi-device sync Concept · 25 min
- Chat design check Knowledge check · 6 questions
What you will learn
- Design message storage, presence and multi-device sync, including fan-out for group chats.
Prerequisites: Messaging & Event Streaming
01. Why it matters
Lesson 1 put Relay's history at about 720 GB a day, copies included, or roughly 263 TB a year. Lesson 3 gave every message a number and every device a cursor. Two reads dominate: show the latest page of this conversation when a user opens it, and give this device everything after its cursor when it reconnects.
Every chat screen also asks: is this person online, and does my laptop show what my phone sent? This lesson designs storage around the two reads, presence that stays right when a phone loses signal, sync for several devices, and limits for large groups.
02. Storing messages by conversation
Start with the plain design: one relational table, messages(conversation_id, seq, sender_id, body, sent_at), with the primary key (conversation_id, seq). Both reads are an index range scan, and a single well-run database serves this for a long time; many products never outgrow it. The limit is volume: at lesson 1's rate, about 240 GB a day before copies, one primary fills its disk within weeks and may reach its write ceiling, which only a load test can tell. Splitting the table by conversation keeps each read on one machine, as the sharding lesson explains.
Wide-column stores such as Cassandra and ScyllaDB make this layout explicit. The partition key picks the machines that hold a row and the clustering key orders rows inside the partition, as in the wide-column lesson. With the conversation as partition key and the sequence number, newest first, as clustering key, latest 50 messages is one sequential read. Discord described this layout in 2023: messages are partitioned by channel and a bucket, a fixed time window, and every ID is a Snowflake ID, so IDs sort by time. The bucket stops a busy channel's partition from growing for ever. Its width is a trade-off, which bucket_read.py measures on 90 days of simulated traffic for three conversations of very different activity (Python 3.12, standard library only):
"""Partition key = (conversation, time bucket): what the width costs (Python 3.12)."""
import random
DAYS = 90 # history we simulate; real histories run for years
RATES = {"team-room": 1500, "two-friends": 25, "old-friend": 0.3} # messages per day
def history(rate: float, rng: random.Random) -> list[float]:
"""Message times in days, oldest first, with random gaps at the given rate."""
t, times = 0.0, []
while True:
t += rng.expovariate(rate)
if t >= DAYS:
return times
times.append(t)
rng = random.Random(7)
convs = {name: history(rate, rng) for name, rate in RATES.items()}
for name, times in convs.items():
print(f"{name:<12}{len(times):>9,} messages in {DAYS} days")
print(f"\n{'bucket':<9}{'largest':>13} partitions read to show the latest 50")
print(f"{'width':<9}{'partition':>13}" + "".join(f"{name:>13}" for name in convs))
for width in (1, 7, 30):
buckets: dict[tuple[str, int], int] = {}
for name, times in convs.items():
for t in times:
key = (name, int(t // width)) # the partition key
buckets[key] = buckets.get(key, 0) + 1
largest = max(buckets.values())
reads = []
for name in convs:
b, found, read = int((DAYS - 1) // width), 0, 0
while found < 50 and b >= 0: # newest bucket first, walking back in time
found += buckets.get((name, b), 0) # an empty bucket still costs a read
read += 1
b -= 1
reads.append(read)
cells = "".join(f"{r:>13}" for r in reads)
print(f"{width:>2} day(s){largest:>8,} rows{cells}")python3.12 bucket_read.pyteam-room 135,392 messages in 90 days
two-friends 2,345 messages in 90 days
old-friend 16 messages in 90 days
bucket largest partitions read to show the latest 50
width partition team-room two-friends old-friend
1 day(s) 1,615 rows 1 2 90
7 day(s) 10,658 rows 1 1 13
30 day(s) 45,216 rows 1 1 3A 30-day bucket lets the busy room's partition reach 45,216 rows, and without buckets it would keep growing. A one-day bucket keeps partitions small, but the quiet conversation, with 16 messages in 90 days, needs 90 reads, mostly of empty buckets, to fill a screen; over years, hundreds. Two common answers are a width chosen per conversation from its activity, or a pointer to the last non-empty bucket kept with the conversation. Discord also reported hot partitions, bursts of reads on one big channel; its data services merge identical concurrent requests and route each channel's requests to one instance.
Which key orders messages inside a partition? The per-conversation sequence of lesson 3 is dense, so devices can see gaps, but it needs a sequencer. A Snowflake-style ID, as built in the Snowflake lab, is unique without coordination but not consecutive, and it carries its generator's clock, so close messages from different servers are ordered only as well as clocks agree. Many designs keep both: the global ID for references from replies or reactions, the sequence for order and sync. Attachments go to object storage, with only a reference in the row.
03. Presence as soft state
The simple presence design writes online when a device connects and offline when it disconnects. It is right whenever disconnects are clean. But a phone that loses signal sends no close frame, and a gateway that crashes cleans nothing up, so the user stays online for good. Presence works better as soft state, a record that disappears unless it is renewed. Each heartbeat renews a key with a time to live (TTL), a clean close deletes the key at once, and silence lets it expire. An in-memory store with key expiry, such as Redis, fits; losing it costs a heartbeat interval of wrong dots but no messages. The script presence_fanout.py (Python 3.12, standard library only) simulates the keys and prices the fan-out:
"""Presence by heartbeat and TTL, and what fan-out costs (Python 3.12)."""
HEARTBEAT_S, TTL_S = 30, 90 # a key survives up to two missed heartbeats
print("1. Presence keys with a TTL; both users stop at t=100 s")
expires = {} # user -> time their presence key expires
for t in range(0, 200, 10):
for user in ("ana", "ben"):
if t <= 100 and t % HEARTBEAT_S == 0: # heartbeats until t=100
expires[user] = t + TTL_S
if t == 100: # ana closes the app: the gateway sees a close frame
del expires["ana"]
print(f" t={t:>3} s ana: close frame, key deleted -> offline now")
print(f" t={t:>3} s ben: phone loses signal, nothing reaches the server")
for user, when in list(expires.items()):
if t >= when:
del expires[user]
last = when - TTL_S
print(f" t={t:>3} s {user}: key expired, last heartbeat t={last} s"
" -> offline")
print("\n2. Presence updates per second at peak (inputs from lesson 1)")
online, dau = 6_250_000, 20_000_000 # connected users at peak, daily users
changes_per_hour = 4 # each online user goes online/offline/away this often
contacts, visible = 150, 8 # contacts per user; presence dots on screen at once
changes = online * changes_per_hour / 3600
to_all = changes * contacts * online / dau # every online contact gets each change
watchers = online * visible / dau # average viewers who have this user on screen
print(f" presence changes {changes:>10,.0f} per s")
print(f" push to every online contact {to_all:>10,.0f} per s")
print(f" push only to on-screen watchers {changes * watchers:>10,.0f} per s")
print("\n3. Cost of one group message (40% of members online, 1.3 devices each)")
print(" members log rows inbox rows live deliveries receipt events")
for n in (2, 12, 256, 5000):
others = n - 1 # everyone except the sender
print(f" {n:>7,}{1:>10}{n:>12,}{others * 0.4 * 1.3:>17,.1f}{others * 2:>16,}")python3.12 presence_fanout.py1. Presence keys with a TTL; both users stop at t=100 s
t=100 s ana: close frame, key deleted -> offline now
t=100 s ben: phone loses signal, nothing reaches the server
t=180 s ben: key expired, last heartbeat t=90 s -> offlineAna's clean close shows at once. Ben's last heartbeat was at 90 s, so his key lives until 180 s: a silent drop can take up to one TTL after the last heartbeat to show. A shorter TTL shows it sooner but turns a brief signal loss into an offline flicker, and shorter heartbeat intervals cost frames (lesson 1). This model simplifies: a gateway that notices a dead connection through its own pings can delete the key earlier.
Each change of presence must also reach the people who can see it, and the obvious design pushes it to every online contact. Part 2 prices that with lesson 1's peak, 6.25 million of 20 million users online, and assumed inputs: 4 changes per online user per hour, 150 contacts, and 8 presence dots on screen at a time.
2. Presence updates per second at peak (inputs from lesson 1)
presence changes 6,944 per s
push to every online contact 325,521 per s
push only to on-screen watchers 17,361 per sPushing to every online contact costs about 325,000 events a second; pushing only to people who have that user on screen costs about 17,000, roughly 19 times fewer. Slack's 2023 write-up describes this choice: a client receives presence notifications only for users visible on its screen. The trade-off: a dot scrolling into view must be fetched first. A product with no presence, or only a coarse last seen, skips most of this.
04. Several devices, one history
Each device is a separate connection in the registry and keeps its own cursor in each conversation. On reconnect it sends its cursors and receives only newer messages; repeating the request is harmless, as the device drops numbers it holds. Three details make several devices feel like one:
- The sender's other devices are recipients too. When Ana sends from her phone, her laptop must get the message as well: the echo that lesson 1 counted.
- The read mark belongs to the user, not the device. When the laptop sends read up to 41, the server forwards it to the phone, which clears its badge.
- A new device starts from recent pages of recent conversations and fetches older ones when the user scrolls, instead of replaying years of history.
A user in 2,000 conversations would send 2,000 cursors on every reconnect. One design option avoids that: a per-user change log with its own sequence, recording conversation X advanced to seq N. A device then sends one cursor and learns which conversations changed. The cost is one small write per member for every message, which leads to groups.
05. Group fan-out and its limits
Part 3 of the script prices one group message under two designs: a single log row in the group's conversation, or a copy in every member's inbox (fan-out on write), with lesson 1's 40% of members online and 1.3 devices each.
3. Cost of one group message (40% of members online, 1.3 devices each)
members log rows inbox rows live deliveries receipt events
2 1 2 0.5 2
12 1 12 5.7 22
256 1 256 132.6 510
5,000 1 5,000 2,599.5 9,998With one log row, the storage cost of a message stays constant whatever the group size, while live deliveries and receipts grow with the members. Inbox copies make storage writes grow too: one message to 5,000 members becomes 5,000 rows. For one-to-one chats and small groups, inbox copies are cheap and keep per-user sync simple. For large groups, store the message once, push it to members who are online, and let offline members read the log from their cursor when they return, with one push notification rather than one per message. It is the same trade-off as fan-out on write in a news feed.
A size limit keeps the cost of one message predictable. Relay caps groups at 256, so its worst message costs about 133 live deliveries and up to 510 receipt events. Products with much larger groups tend to change features as size grows: receipts become counts, presence shows for a few members, and posting is rate-limited. If every group is small, though, the inbox design is simpler and its extra writes stay bounded.
06. Check your understanding
07. Apply it
Finish the design doc of this skill's practice, a chat service with 50 million daily users and groups of up to 500 members, with one sentence of justification for each choice:
- the message table: partition key, clustering key, bucket width, and how quiet chats avoid empty-bucket reads;
- presence: heartbeat interval, TTL, where keys live and who gets updates, priced with your copy of
presence_fanout.py; - sync: what a reconnecting device sends, how a new device starts and how read marks reach other devices;
- group fan-out: inbox copies or one log row at 500 members, and what changes for the largest groups.
08. Review prompt
Without looking back, answer in your own words:
- Why does the message table use the conversation plus a time bucket as its partition key, and what does the bucket width trade?
- Why is presence soft state, and how long can a silent drop take to show?
- What does a reconnecting device send, and how do a sender's other devices get her messages?
- For a 500-member group, compare one log row with inbox copies on writes, deliveries and receipts.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.