Design a Group Chat App (Slack/Discord)
hard 45 minDesign team chat: channels, threads, unread badges, presence and search.
See it run
Send, deliver, thread, search, presence and reconnect, one hop at a time.
Operations
Send a message
Check, number, commit, answer. Live delivery starts after the commit.
Step 1 of 13
Client sends
text
Hello team!
A POST with the channel, the text and a client_msg_id. Why: HTTP gives a status and a safe retry.
Step 1: Client sends
def send(session, channel, client_id, text): user = check_session(session) check_member(user, channel) check_limits(user, channel) with shard(channel).transaction() as tx: seq = tx.lock_and_next(channel) row = tx.insert(channel, seq, user, client_id, text) tx.outbox(channel, seq) channel_server(channel).hint(row) # best effort return 201, row- Latency
- about 40 ms
- Load
- 5,800/s
- Peak (3x)
- 17,400/s
A repeat of the same client id fails on the unique key. Return the first row, not an error.
In the real world
The same group chat doing real jobs. Pick one and step through it.
The push for 412 never arrives and the room is quiet.
Step 1 of 4
Push lost
The channel server restarts while sending 412.
Step 1: Push lost
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Pushing before saving
criticalIf the commit fails, people saw a message that does not exist.
Wrongpush(message)db.insert(message)Rightdb.insert(message) # commitpush(message)Ordering by clock
majorClocks differ and can step back. NTP reduces the error but does not remove it.
Wrongmessages.sort(key=lambda m: m.time)Rightmessages.sort(key=lambda m: m.event_seq)A counter for every member
majorOne message in a 10,000 member room becomes 10,000 writes.
Wrongfor m in members: incr(f"unread:{m}")Rightunread = channel.last_msg - position[user]Reading, then subscribing
criticalAn event between the two steps is never seen.
Wronggap = read(after=last)subscribe(channel)Rightsubscribe(channel)gap = read(after=last) # drop repeatsFiltering search afterwards
criticalCounts and empty pages reveal what is hidden.
Wronghits = index.query(words)return [h for h in hits if allowed(h)]Rightindex.query(words, filter=allowed_channels)
Interview tips
Lead with numbers
- 5,800 messages a second, 290,000 deliveries.
- 3M sockets, 100 gateways.
- 91 TB a year splits the store.
Say the promises
- Never lost: committed messages.
- May be late: search and notices.
- May vanish: typing and dots.
Follow the absent
- Draw the offline member early.
- Subscribe, then read.
- Heartbeats carry the newest number.
Plan the bad day
- Spread reconnects.
- Drain gateways slowly.
- Watch the age of the outbox.