Design a real-time group messaging platform
System DesignModel answerLast updated
Design a scalable chat platform with channels and DMs supporting millions of users, sub-200ms delivery, message ordering, presence, and cross-device history sync.
Problem Statement
Design a collaborative messaging platform that supports team-based communication through organized channels and direct messages. The system must handle millions of daily active users with fast message delivery, persistent conversation history accessible from any device, and real-time presence indicators showing who is online.
Functional Requirements
- Users can send and receive messages instantly within shared channels or through private direct messages.
- Conversation history must persist and remain consistent when a user switches between devices.
- Users can see which of their colleagues are currently online or away.
Non-Functional Requirements
- The platform must be highly available with message delivery latency under 200 milliseconds.
- Messages within a single conversation must arrive in a deterministic, ordered sequence.
- The system must scale to handle thousands of messages per second at peak load.
What You Should Cover
- API and Protocol Design: Define the REST endpoints and the real-time WebSocket event formats for sending, receiving, acknowledging, and syncing messages.
- Data Model: Propose a storage schema that supports fast appends for new messages and efficient retrieval of recent history. Discuss your choice of database technology.
- Architecture: Walk through how a message travels from sender to all recipients, including how you handle delivery to users in large channels with many online members.
- Trade-offs: Explain where you chose consistency over availability and vice versa, particularly around message persistence and presence updates.
- Resilience: Describe how the system handles dropped connections, client reconnections, and network partitions without losing or duplicating messages.
Hints
Hint 1
Think about what makes writes expensive: is it storing the message or delivering it to many recipients? Separate those concerns.
Hint 2
A per-channel monotonic sequence number solves both ordering and gap detection on reconnect. Who assigns it and how do you keep that assignment scalable?
Hint 3
Presence changes constantly and does not need to be perfectly accurate. What data structure and staleness tolerance lets you avoid flooding the system with presence updates?
Hint 4
Storing one copy of a message per recipient kills large channels. What if online users get a lightweight push notification and offline users simply fetch on demand?
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Scope and Scale
Start by stating assumptions and estimating load.
In scope: channels, DMs, real-time delivery, persistent cross-device history, presence. Out of scope: voice/video, file uploads, full-text search (follow-up topic).
Back-of-envelope numbers:
| Metric | Assumption | Result |
|---|---|---|
| Daily active users | 10M | ~5M peak concurrent connections (multiple devices per user) |
| Messages per user/day | 50 | 500M/day, roughly 6K msg/s average, ~30K/s at peak |
| Message size with metadata | ~1 KB | ~500 GB/day, ~180 TB/year before replication |
| Average online recipients per message | ~30 | 200K–1M socket pushes per second |
| WebSocket connections per gateway server | ~50–100K | ~100 gateway servers |
The key takeaway: writes are modest, but fan-out and connection management dominate the design.
2. API and Protocol Design
REST handles history retrieval and session management:
POST /channels {name, members}
GET /channels/{id}/messages?before_seq=&limit=50
GET /sync?cursors={channel_id: last_seq,...}
POST /channels/{id}/messages {client_msg_id, body} (fallback when WS is down)
The /sync endpoint lets a reconnecting device fetch all messages newer than its last-known sequence per channel.
WebSocket carries all real-time traffic bidirectionally:
C->S send {client_msg_id, channel_id, body}
S->C ack {client_msg_id, channel_id, seq, server_ts}
S->C message {channel_id, seq, msg_id, sender_id, body, ts}
C->S read {channel_id, seq}
C->S heartbeat {}
S->C presence {user_id, status}
C->S subscribe_presence {user_ids: [...]}
Two fields carry the correctness story:
client_msg_idis a UUID generated by the client, making sends idempotent. If a retry arrives, the server returns the originalackinstead of creating a duplicate.seqis a monotonic per-channel counter. Clients render byseq, not wall-clock time. If a client receives seq 41 then 43, it knows 42 is missing and fetches it via/sync.
3. Data Model
Messages are append-heavy and almost always read as "latest N in channel." That is a wide-column workload, so use Cassandra or ScyllaDB, which is what production chat systems like Discord use.
messages
PRIMARY KEY ((channel_id, bucket), seq) -- bucket = time window (~10 days)
columns: msg_id, client_msg_id, sender_id, body, created_at, edited_at, deleted
CLUSTERING ORDER BY (seq DESC)
Bucketing by time window keeps partitions bounded, which matters for very active channels.
Relational metadata lives in PostgreSQL, sharded by workspace. This data is small, needs transactions, and changes infrequently:
workspaces(id, ...)
channels(id, workspace_id, type, name, last_seq)
memberships(channel_id, user_id, role, last_read_seq)
users(id, ...)
Why shard messages by channel_id instead of user_id? Storing one copy per member would be write-amplification proportional to channel size, which is fatal for large channels. Instead, store each message once. Cross-device sync works through cursors: each device tracks {channel_id: last_seq} and calls /sync. Unread counts come from channel.last_seq - membership.last_read_seq.
4. Architecture
Clients ──WS──> L4 LB ──> Gateway (stateful sockets)
│ ▲
send │ │ deliver
▼ │
Chat Service ──> Sequencer (per-channel seq)
│
┌───────────┼──────────────┐
▼ ▼ ▼
Cassandra Pub/Sub bus Push Notif Svc
(messages) (Redis/NATS/Kafka) (APNs/FCM)
│
Gateways subscribed to channel topics
Presence Service (Redis TTL keys) <── heartbeats from gateways
Message flow:
- Client sends over its WebSocket to its gateway.
- Gateway forwards to the Chat Service.
- Chat Service verifies membership and dedupes on
(channel_id, client_msg_id). - It obtains the next
seqfor that channel from the sequencer. - It writes to Cassandra with quorum consistency, then acks the sender.
- It publishes the message to a pub/sub topic keyed by
channel_id. - Each gateway that has users subscribed to that channel receives the message and pushes it to the relevant local sockets.
- Members with no active connection get a mobile push notification.
Routing optimization: gateways register user_id → gateway_id in a Redis session store and subscribe to pub/sub topics for channels their connected users belong to. A message crosses the bus once per interested gateway, not once per user.
5. Deep Dives
Ordering
Total ordering is needed only within a single conversation, not globally. Assign seq per channel from a single owner. Hash each channel_id to a Chat Service partition (Kafka partition keyed by channel_id, or a consistent-hash ring with leases). The owner increments an in-memory counter and persists it. An atomic Redis INCR backed by channels.last_seq is a practical implementation. Clients sort by seq and detect gaps. Avoiding global ordering is what makes the system horizontally scalable.
Fan-out Strategy
Two models exist: push (write to every member's inbox) and pull (store once, clients fetch by cursor). The right answer is a hybrid:
- Store every message once in the channel log (pull-based, O(1) writes).
- For online users, push lightweight real-time events through pub/sub to their gateways.
- For offline users in large channels, do no per-user writes at all. They catch up via
/syncwhen they reopen the app. - For DMs and small groups, a push-based inbox is acceptable since the member count is small.
Presence
Presence is high-churn and tolerates staleness, so optimize for availability. Gateways write a Redis key presence:{user_id} with a ~60s TTL, refreshed by client heartbeats. An expired key means the user is offline. Debounce flapping with a 30-second grace period before marking offline. Do not broadcast presence changes to the entire workspace. Clients subscribe only to users visible in their sidebar or open DMs. For large channels, presence is fetched lazily in batches.
Reconnection and Partitions
Mobile connections drop frequently. On reconnect, the client sends its cursors to /sync and receives all messages after last_seq per channel. Unacked sends are retried with the same client_msg_id, and the server dedupes. Gateways hold no persistent data, so a gateway crash simply triggers reconnection through the load balancer. Clients use jittered backoff to avoid thundering herd. During a network partition, a channel's sequencer lives on one side. Writes from the minority side fail and are retried, preserving ordering correctness at the cost of brief unavailability for that channel.
6. Consistency vs. Availability Trade-offs
Message persistence uses quorum writes to Cassandra, favoring consistency: a successful ack means the message is durably stored. Presence uses single-node Redis writes with TTL, favoring availability: presence may be briefly stale but never blocks messaging. The /sync endpoint provides a consistency repair mechanism: even if a real-time push is lost due to a dropped socket, the client catches up deterministically on reconnect using sequence cursors. This separation lets the system be highly available for reads and presence while maintaining strong ordering guarantees for message delivery.