Build a Chat Platform with Channels, DMs, and Presence
System DesignModel answerLast updated
Design a real-time workspace chat backend with channels, DMs, paginated history, unread tracking, and presence, supporting 5M concurrent connections and channels of up to 50,000+ members.
Problem
You are asked to design the backend for a workplace chat product. People belong to a workspace and talk in public channels, private channels, and one-to-one direct messages. Delivery must feel instant, and nothing that has been confirmed to a sender may ever disappear.
What the product must do
- Send and receive: Users exchange text in DMs and in channels, with live delivery to anyone who is online.
- Browse history: Users scroll backward through older messages in a conversation, loaded in pages.
- Presence: Users can tell whether other workspace members are online or offline.
- Unread state: The system tracks how far each user has read in each channel so it can show unread counts.
Quality targets
- Latency: Under 100 ms end-to-end delivery for users in the same region.
- Ordering: Every participant sees the messages of a channel in the same strict order.
- Durability: After the server confirms a message, it must not be lost, even through failures.
- Scale range: The same design must serve tiny group chats and company-wide announcement channels without degrading.
Load assumptions
- 20 million daily active users
- 5 million simultaneous persistent connections at peak
- 500 million messages per day, about 6,000/s on average and 25,000/s at peak
- Channel sizes from 2 up to 50,000+ members
- About 500 bytes per message including metadata
What your answer should cover
- APIs: The main client-facing operations: sending, fetching history, joining or managing channels, updating read position.
- Real-time connection layer: Protocol choice (persistent sockets vs. polling), how traffic is routed, and how the system knows which server holds which user's connection.
- Fan-out: How a single message reaches every online member, and how your approach differs between small and very large channels.
- Storage and schema: Which databases you would choose and how you would model users, channels, messages, and read positions.
- Presence: How online/offline status is collected and distributed efficiently at this scale.
Include back-of-the-envelope capacity numbers and call out the trade-offs you are making.
Hints
Hint 1
Convert the numbers into load before designing. Writes are only about 25K/s at peak, but each message is delivered to many online recipients, so delivery volume (hundreds of thousands per second) is the real driver.
Hint 2
For ordering, avoid distributed locks: route all messages of a channel through a single partition or single writer, and have that writer assign a dense per-channel sequence number. Use the same number for pagination and for gap detection on clients.
Hint 3
Treat a 2-person DM and a 50,000-member channel differently: per-recipient routing for small channels, but for huge ones deliver once per gateway server that has at least one member connected and let that server fan out locally.
Hint 4
For presence and read state, avoid per-event broadcast and per-message storage: use heartbeats with expiring keys, only publish on state changes, and compute unread counts as the difference between a channel's latest sequence and the user's read cursor.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Scope and capacity estimates
In scope: channels, DMs, history, presence, read state. Out of scope unless asked: file uploads, calls, threads, search.
| Quantity | Estimate |
|---|---|
| Message writes | ~6K/s average, 25K/s peak |
| Storage | 500M x 500 B = ~250 GB/day, ~90 TB/year raw, ~270 TB with 3x replication |
| Connections | 5M; at ~50K sockets per host that is ~100 gateways, ~150 with headroom |
| Deliveries | If a peak message reaches ~20 online users on average, ~500K deliveries/s |
Delivery fan-out, not ingestion, dominates. One post in a 50K-member channel with 20K members online is 20K deliveries by itself.
2. APIs
Real-time traffic uses a persistent WebSocket, everything else is REST.
WS -> send {client_msg_id, channel_id, text}
WS <- ack {client_msg_id, message_id, seq, ts}
WS <- message {channel_id, seq, message_id, sender_id, text, ts}
WS -> heartbeat / subscribe_presence {user_ids}
WS <- presence {user_id, status}
POST /channels create channel or open DM
POST /channels/{id}/members join / invite
GET /channels/{id}/messages?before_seq=&limit=50
POST /channels/{id}/read {last_read_seq}
GET /sync?cursors=... catch up after reconnect
client_msg_idmakes retries idempotent, so a flaky network never produces duplicates.- History pages by
seq, not offset, so pages stay stable while new messages arrive.
3. Connection layer
WebSockets give full-duplex, low-overhead delivery, which is what a sub-100 ms target needs. Keep long-polling as a fallback for restrictive proxies.
- Gateways are stateful but thin: terminate sockets, authenticate, forward frames. Business logic lives in stateless services, so gateways deploy rarely and drain gracefully.
- Session registry: on connect, the gateway writes
user_id -> {gateway_id, conn_id}to Redis with a TTL, refreshed by heartbeats. - A Layer-4 load balancer spreads new connections. Clients reconnect with backoff and jitter to avoid thundering herds after a gateway failure.
4. Write path: ordering and durability
- The message service validates membership (cached) and produces to Kafka keyed by
channel_idwithacks=all, min ISR 2. - One partition means one total order per channel. A per-partition consumer (the sequencer) is the sole writer for its channels, so it assigns
seq = last_seq + 1without locks. - It persists to the message store at quorum, then passes the message to fan-out.
- The sender gets an ack once the message is durably in Kafka (a few ms). Later stages can be replayed from the log, so failures downstream do not lose data.
A dense per-channel seq beats time-based IDs alone: clients detect a gap (got 105 after 103) and refetch. A Snowflake-style ID can still be attached for global uniqueness.
Trade-off: a hot channel is bounded by one partition's throughput. For announcement channels this is fine because posting is rate-limited.
5. Data model
Messages: Cassandra/ScyllaDB. Append-heavy, range-scanned, linearly scalable.
messages (
channel_id, bucket, -- bucket = month, caps partition size
seq BIGINT, message_id BIGINT, sender_id, text, edited_at, deleted,
PRIMARY KEY ((channel_id, bucket), seq)
) WITH CLUSTERING ORDER BY (seq DESC)
History is a single-partition range read: seq < ? LIMIT 50, moving to the previous bucket when exhausted.
Metadata: sharded Postgres/Vitess by workspace_id. Relational, transactional, small: users, channels(type, last_seq), memberships (with a reverse index by user).
Read state: read_state(user_id, channel_id, last_read_seq, mention_count) in a KV store.
- Unread count =
channel.last_seq - last_read_seq, computed on read, so a huge channel adds no per-message write cost. - Clients debounce cursor updates (e.g. every 2 s) and the server applies
max(old, new)so cursors never move backward.
6. Fan-out
Small channels (under ~1K members): push by user. Load the cached member list, batch-look up gateways in Redis, group recipients by gateway, and send one RPC per gateway with a recipient list. Offline members go to a push-notification queue filtered by their preferences.
Large channels: push by gateway. Per-user routing is too costly. Each gateway subscribes to a channel topic when at least one of its local users is a member. The fan-out service publishes once per subscribed gateway (at most ~150 sends instead of 50K) and each gateway delivers to its local sockets from memory. Cost drops from O(members) to O(gateways).
Extra protection for announcement channels: restrict who can post, send mobile push only for @mentions, and let gateways coalesce bursts into one frame per ~100 ms.
7. Presence
- Clients heartbeat every ~30 s over the existing socket. The gateway absorbs it and refreshes
presence:{user_id}in sharded Redis with a 60-90 s TTL. A missed heartbeat expires the key, which means offline, and this also handles crashed gateways. - Write to Redis only on state change or at a lower refresh cadence, not on every heartbeat, to cut write load (5M users / 30 s is ~170K heartbeats/s if done naively).
- Do not broadcast presence to everyone. Clients subscribe only to users currently visible (sidebar, current channel, DM list). Publish changes only to those subscribers, and apply a short debounce (5-10 s) so brief network blips do not cause flapping.
- In huge workspaces, show presence lazily, fetched on view, rather than pushed.
8. Failure handling and reconnects
- On reconnect, the client calls
/syncwith its lastseqper channel and fetches the gaps. This makes delivery effectively at-least-once with client-side dedupe by(channel_id, seq). - Replicate Kafka and Cassandra across zones. Losing a gateway only drops its sockets, and clients reconnect and sync.
Common mistakes
- Sizing around write QPS and ignoring delivery fan-out.
- Using offset pagination, or timestamps as the only ordering key.
- Per-user fan-out for 50K-member channels.
- Storing a per-user, per-message read flag instead of a cursor.
- Broadcasting every presence change to the whole workspace.
- Acking the sender before the message is durable.