Design a Real-Time Messaging and Collaboration Platform
System DesignModel answerLast updated
Architect a scalable real-time chat service supporting workspaces, channels, direct messaging, persistent history, and message editing with low-latency delivery.
Design the core backend infrastructure for a collaborative chat application similar to Slack or Discord.
Core Functionality
- Workspaces & Channels: Support multi-tenant workspaces hosting both public and private channels. Channel sizes vary from small group discussions to high-traffic announcement channels exceeding 100,000 members.
- Direct Messaging: Provide 1:1 and small group direct messages (DMs).
- Message Lifecycle: Users can publish text messages, retrieve historical messages using pagination, and modify (edit/delete) existing messages.
- Real-time Synchronization: Messages must be delivered instantly to active members across connected clients without requiring manual refreshes.
- Persistence: Message history must be permanently stored and queryable efficiently.
System Requirements & Expectations
- Outline high-level traffic and storage estimations based on reasonable scale parameters.
- Define primary API interfaces and data schemas across persistent storage tiers.
- Detail the end-to-end event delivery architecture (WebSocket management, pub/sub, fanout handling).
- Explain mechanisms for preserving strict per-conversation message ordering and consistency during concurrent writes or edits.
- Address strategies for mitigating performance bottlenecks caused by hot channels or massive group broadcasts.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Requirements & System Constraints
Functional Requirements
- Multi-tenant workspaces with public/private channels and 1:1 or group Direct Messages (DMs).
- Text-based message posting, editing, and soft deletion.
- Infinite scrollback for message history.
- Sub-second real-time delivery to online users.
- Unread message counters and tracking read states.
Non-Functional Requirements
- Low Latency: $p_{99}$ message delivery latency under 200 ms to online clients.
- Strict Per-Conversation Ordering: Messages within a single channel must be strictly ordered. Global ordering across conversations is not required.
- Read-Your-Writes: A user posting a message must see their write reflected immediately in their client state.
- High Availability & Durability: Once acknowledged by the server, a message must never be lost.
- Scalability: Gracefully support large broadcast channels (100k+ members) without degrading delivery performance for standard channels.
Scale Estimations
- Daily Active Users (DAU): 50 million users.
- Peak Concurrent Connections: 20 million active WebSocket connections.
- Throughput: Average 40 messages per user per day $\rightarrow 2 \text{ billion messages/day}$.
- Average Write QPS: $\approx 23,000 \text{ writes/sec}$.
- Peak Write QPS: $\approx 100,000 \text{ writes/sec}$.
- Storage Footprint:
- Average message size (including metadata): 500 bytes.
- Daily raw storage: $2\text{B} \times 500\text{ B} = 1\text{ TB/day}$.
- Annual storage requirement (with $3\times$ replication factor): $\approx 1\text{ PB/year}$.
2. High-Level Architecture
┌──────────────────────┐
│ Client Application │
└──────────┬───────────┘
│
┌────────────────┴────────────────┐
│ │
(WebSocket Events) (REST/gRPC)
│ │
▼ ▼
┌──────────────────────┐ ┌──────────────────────┐
│ Gateway Fleet │ │ API Service │
│ (Stateful WS Server) │ │ (Stateless) │
└──────────┬───────────┘ └──────────┬───────────┘
│ │
│ ┌───────────────────────────────┴──────────────┐
│ │ │
▼ ▼ ▼
┌──────────────────────┐ ┌──────────────────┐
│ Pub/Sub Engine │ │ Sequencer Service│
│ (Redis Cluster/NATS) │ └─────────┬────────┘
└──────────┬───────────┘ │
│ ▼
│ ┌──────────────────┐
│ │ Conversation DB │
│ │ (ScyllaDB) │
│ └──────────────────┘
▼
┌──────────────────────┐
│ Async Processing │
│ (Push, Search, Stats)│
└──────────────────────┘
Core Components
- API Gateway / Edge Router: Handles authentication, SSL termination, and rate limiting.
- Stateless API Service: Processes message posts, edits, history fetches, and channel management over REST/gRPC.
- Sequencer Service: Responsible for generating linear sequence IDs per conversation to guarantee monotonic ordering.
- Stateful Gateway Fleet: Maintains persistent WebSocket/SSE connections with clients, routing downstream real-time events.
- Pub/Sub Engine: Decouples message ingestion from stateful connection nodes using topic-based subscription mechanisms.
- Persistence Layer: Dual-database setup splitting low-volume relational metadata (PostgreSQL/Vitess) from high-volume immutable time-series message history (ScyllaDB/Cassandra).
3. API Design
Send Message
POST /v1/conversations/{conversation_id}/messages
Request Body:
{
"client_id": "c83f2a1b-3b7c-4a3d-9b0e-1f2a3b4c5d6e",
"content": "Hello team!",
"type": "text"
}
Response: 201 Created
{
"message_id": "1098327498127394812",
"conversation_id": "conv_9921",
"sequence_id": 48291,
"created_at": "2023-10-27T10:15:30Z"
}
Note: client_id serves as an idempotency key to prevent duplicate posts under retries.
Fetch Historical Messages
GET /v1/conversations/{conversation_id}/messages?cursor=48291&limit=50
Response: 200 OK
{
"messages": [
{
"message_id": "1098327498127394812",
"sequence_id": 48291,
"sender_id": "usr_102",
"content": "Hello team!",
"version": 1,
"is_deleted": false,
"created_at": "2023-10-27T10:15:30Z"
}
],
"next_cursor": 48241
}
Real-Time Gateway Connection
WS /v1/gateway/connect
Frame (Client $\rightarrow$ Server):
{
"action": "subscribe",
"conversations": {
"conv_9921": 48290,
"conv_1002": 1052
}
}
Frame (Server $\rightarrow$ Client):
{
"event": "MESSAGE_CREATE",
"conversation_id": "conv_9921",
"data": {
"message_id": "1098327498127394812",
"sequence_id": 48291,
"sender_id": "usr_102",
"content": "Hello team!"
}
}
4. Data Modeling & Storage Strategy
We use a polyglot persistence architecture to handle the distinct access patterns of metadata vs. message streams.
Metadata Store (PostgreSQL or Vitess)
Handles relational entities, access control list (ACL) checks, and directory lookups.
CREATE TABLE workspaces (
workspace_id BIGINT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE conversations (
conversation_id BIGINT PRIMARY KEY,
workspace_id BIGINT NOT NULL,
type VARCHAR(32) NOT NULL, -- 'public', 'private', 'dm', 'group_dm'
name VARCHAR(255),
max_sequence_id BIGINT DEFAULT 0,
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE conversation_members (
conversation_id BIGINT,
user_id BIGINT,
role VARCHAR(32) DEFAULT 'member',
last_read_sequence_id BIGINT DEFAULT 0,
PRIMARY KEY (conversation_id, user_id)
);
CREATE INDEX idx_user_conversations ON conversation_members (user_id);
Message History Store (ScyllaDB / Cassandra)
Wide-column NoSQL databases handle high write throughput and sequential range queries efficiently using Log-Structured Merge (LSM) trees.
CREATE KEYSPACE chat_data WITH replication = {
'class': 'NetworkTopologyStrategy',
'us-east': 3
};
CREATE TABLE chat_data.messages (
conversation_id bigint,
bucket int, -- Time-based partitioning window (e.g., year + month: 202310)
sequence_id bigint,
message_id bigint,
sender_id bigint,
content text,
version int,
is_deleted boolean,
created_at timestamp,
PRIMARY KEY ((conversation_id, bucket), sequence_id)
) WITH CLUSTERING ORDER BY (sequence_id DESC);
Partitioning Logic
Combining conversation_id and a time-based bucket into the partition key prevents single partitions from growing indefinitely in ultra-active channels. Range scans for pagination query a specific (conversation_id, bucket) partition, fetching items in sequence_id DESC order.
5. Messaging Lifecycle & Real-Time Delivery
Message Ingestion & Persistence Path
- Submit: Client submits a message payload via POST to the stateless API Service.
- Authorize: API Service validates sender permissions using local cached memberships (Redis).
- Sequence Allocation: The service calls an internal low-latency Sequencer Service to assign a strictly increasing
sequence_idforconversation_id. - Persist: Message metadata and body are written to ScyllaDB with quorum consistency.
- Acknowledge: HTTP
201 Createdresponse returned to sender client. - Publish Event: Background publisher broadcasts the
MESSAGE_CREATEevent to the message bus (NATS/Kafka) partitioned byconversation_id.
Gateway Synchronization & Broadcast
Instead of maintaining client subscriptions on every API worker, we use a Two-Tier Router Architecture:
- Stateful Gateway Fleet: Each gateway worker manages up to 100,000 WebSocket connections. When a client establishes a connection, it registers its active state on that gateway instance.
- Gateway Session Registry: Gateway instances register active
(user_id -> gateway_node_id)mappings in an in-memory cluster map (e.g., Redis Enterprise or HashiCorp Serf). - Optimized Fanout:
- The message bus routes channel events to gateways hosting active members of that channel.
- Node-Level Fanout: A gateway receiving an event for
conversation_idduplicates the frame in-memory to all local WebSocket connections subscribed to that channel. This avoids multiplying pub/sub network traffic across cluster nodes.
Message Bus ──> Gateway Node A ──┬──> Client 1 (WebSocket)
├──> Client 2 (WebSocket)
└──> Client 3 (WebSocket)
6. Fanout Trade-offs & High-Volume Channels
Handling message distribution requires distinct strategies based on target audience scale:
+-----------------------------------------------------------------------+
| CONVERSATION SCALE MAP |
+-----------------------------------------------------------------------+
| Small Channels / DMs (<1k Members) |
| ├── Direct Pub/Sub Event Push |
| ├── Push Notifications triggered for offline users |
| └── Immediate Unread Count Increment |
+-----------------------------------------------------------------------+
| Large Broadcast Channels (10k - 100k+ Members) |
| ├── Lazy Pull / Active-Client Push Only |
| ├── Suppress Global Push Notifications (Mentions Only) |
| └── Deferred Unread Counter Computation |
+-----------------------------------------------------------------------+
Small Channels & DMs (<1,000 members)
- Write Path: Message is written once to the database.
- Delivery: Event is pushed in real-time to active cluster gateways holding recipient connections. Mobile push notifications (APNs/FCM) are triggered immediately for offline members.
Mega Channels (100,000+ members)
- Storage: Always Read-Fanout. Messages are stored strictly once in the channel log. Never replicate message instances per inbox.
- Delivery Optimizations:
- Suppress Bulk Push Notifications: Notifications are suppressed unless a explicit
@mentionor@channelstring is parsed. - Presence-Aware Delivery: The message is delivered only to gateways hosting connected members currently viewing or connected to that workspace.
- Client-Side Throttling/Batching: Under extreme traffic (e.g., 500 msgs/sec), gateway nodes batch downstream events into a single WebSocket frame every 100–250 ms to prevent client render thread choking.
- Suppress Bulk Push Notifications: Notifications are suppressed unless a explicit
7. Consistency, Ordering, and Editing
Per-Conversation Strict Ordering
Global timestamp ordering (e.g., System time or standard Snowflake) suffers from clock drift across nodes.
- Monotonic Sequence Numbers: Each conversation tracks an atomic integer counter
max_sequence_id. - Sequencer Mechanism: Scaled via atomic updates in Redis (
INCR) backed by persistent log generation, or dedicated centralized lightweight leases per conversation (e.g., single-writer thread allocation in Go/Rust per active hot channel). - Gap Detection: Clients track the highest
sequence_idreceived. If a client receives sequence48293after48291, it immediately detects a missing event (48292) and issues a targeted REST pull to backfill the gap.
Editing and Soft Deletions
- Edits: An edit issues an update with an incremented
versioncounter and updated payload (content,edited_at). Old versions can be stored in anedit_historytable if auditing is required. - Deletions: Soft-delete pattern. Set
is_deleted = trueand blank thecontentcolumn. - Real-time Mutation Events: Edits/deletions publish
MESSAGE_UPDATEorMESSAGE_DELETEevents carrying(conversation_id, sequence_id, version). Connected clients locate the rendered payload in their local dynamic memory tree and update or redact the DOM node in place.
8. Failure Scenarios & Edge Cases
- Gateway Node Crash:
- Symptom: 100,000 active WebSocket connections drop simultaneously.
- Mitigation: Clients execute exponential backoff with full jitter to reconnect. Upon reconnection, clients supply their last known
sequence_idper conversation to quickly backfill missed events via a single batch request.
- Pub/Sub Partitioning Delay:
- If the real-time pipeline lags, clients polling or recovering from background state detect missing sequences via the REST history endpoints and self-heal automatically.
- Hot Partition in Storage:
- Very active channels spanning years could generate millions of rows in a single table partition. Time-based bucket keys (e.g.,
conversation_id + YYYYMM) guarantee that partitions remain within optimal sizes (<100MB) for ScyllaDB/Cassandra node repairs and SSTable compaction.
- Very active channels spanning years could generate millions of rows in a single table partition. Time-based bucket keys (e.g.,