Design a Real-Time Enterprise Team Chat Platform
System DesignModel answerLast updated
Architect a low-latency, highly durable workplace chat platform supporting real-time delivery, missed message catch-up, channel fanout, and per-conversation ordering.
Design a real-time workplace collaboration and messaging platform similar to Slack or Microsoft Teams. The platform must allow users to participate in organization workspaces, public/private channels, and direct message (DM) conversations.
Key Requirements & Objectives
- Core Data & Messaging: Support workspaces, channels, direct messages, user memberships, and conversation messages.
- Durability & Latency: Messages must be persisted durably before client acknowledgement. Online recipients should receive messages with sub-second end-to-end latency.
- Ordering Guarantees: Ensure strict, total message ordering within a single conversation (channel or DM). Global ordering across different conversations is not required.
- Real-Time Delivery & Fanout: Deliver messages to connected clients across multiple devices per user. Efficiently handle high-volume fanout for channels with up to 100,000 members.
- Catch-Up & Missed Messages: Allow clients returning from network disruptions or app restarts to seamlessly fetch missed messages without missing updates or seeing duplicate entries.
- Cold Start Optimization: Fast initial boot time for clients without fetching historical data for inactive channels.
- Push Notifications: Trigger external push notifications (APNs/FCM) for offline or inactive users without sending redundant alerts to actively engaged sessions.
Scale & Operating Assumptions
- Active Scale: 10 Million Daily Active Users (DAU), 10 Million Workspaces.
- Peak Write Load: ~100,000 incoming messages per second.
- Channel Sizes: Range from 2-person DMs to 100,000-member organization-wide channels.
- Client Footprint: Web, Desktop, iOS, and Android. A single user can have multiple concurrent active sessions.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. High-Level Architecture & System Boundaries
The system is split into three primary planes:
- Write & Storage Plane (Synchronous): Handles API requests, assigns sequential message IDs, persists messages to disk, and acknowledges the sender.
- Real-Time Delivery Plane (Asynchronous): Maintains long-lived persistent connections (WebSockets), tracks online session routing, and dispatches live events.
- Async Processing & Notification Plane: Processes message event streams for push notifications, search indexing, and presence management.
+----------------+ 1. Send Message (HTTP/gRPC) +---------------------+
| Sender Client | -----------------------------------> | Message Gateway / |
+----------------+ | Ingestion Service |
^ +---------------------+
| |
| 6. ACK (Client Message ID + Sequence ID) | 2. Persist Message
+-----------------------------------------------------------+
v
+---------------------+
| Primary Database |
| (NoSQL / Distributed|
| SQL) |
+---------------------+
|
| 3. Publish Event
v
+---------------------+
| Event Bus / Kafka |
+---------------------+
|
| 4. Consume Event
v
+---------------------+
| Real-Time Router / |
| Dispatcher Service |
+---------------------+
|
| 5. Forward to session
v
+---------------------+
| WebSocket Gateways |
+---------------------+
|
| WebSockets
v
+---------------------+
| Recipient Clients |
+---------------------+
2. Core Data Model & Schema Design
To achieve scale and local ordering guarantees, we partition data by conversation_id.
Key Entities
workspaces:workspace_id(PK),name,created_atusers:user_id(PK),email,display_name,statuschannel_memberships:(user_id, conversation_id)(Composite PK),workspace_id,last_read_sequence_id,joined_atconversations:conversation_id(PK),workspace_id,type(DIRECT_MESSAGE,PUBLIC_CHANNEL,PRIVATE_CHANNEL),current_sequence_idmessages:- Partition Key:
conversation_id - Clustering Key / Sort Key:
sequence_id(Monotonically increasing 64-bit integer per conversation) - Attributes:
message_id(UUID for client-side dedup),sender_id,payload(JSON text/formatting),created_at
- Partition Key:
Database Engine Choice
- Primary Message Store: Distributed NoSQL (e.g., Cassandra/ScyllaDB) or Distributed SQL (e.g., CockroachDB/YugabyteDB).
- Partitioning strategy: Partition key is
conversation_id. All messages within a channel live on the same node cluster range, allowing single-partition range queries for rapid scrollback and catch-up (WHERE conversation_id = X AND sequence_id > Y).
- Partitioning strategy: Partition key is
- Metadata Store: PostgreSQL or DynamoDB for workspaces, channels, user profiles, and channel membership queries.
3. Send & Receive Flow (Durability vs. Delivery)
Step-by-Step Send Path (Write Plane)
- Submission: Sender client posts a message to
/v1/conversations/{conversation_id}/messagescontaining aclient_message_id(UUID generated by client for idempotency) and payload. - Authentication & Authorization: The Message Ingestion Service checks if
sender_idis a valid member ofconversation_id(cached in Redis). - Sequence Generation & Persistence:
- An atomic increment engine (or database sequence counter per
conversation_id) assigns the nextsequence_id. - The message is written to the primary message database.
- An atomic increment engine (or database sequence counter per
- Synchronous ACK: Once persisted to quorum replicas in the primary store, the server responds to the sender with
{ client_message_id, sequence_id, created_at }. The message is now durably stored. - Event Emission: An event
{ conversation_id, sequence_id, message_id, sender_id, payload }is pushed to an Event Bus (e.g., Apache Kafka / Pulsar) partitioned byconversation_id.
Real-Time Delivery Path (Read/Delivery Plane)
- Event Consumption: Real-Time Dispatcher workers consume events from Kafka topics.
- Session Discovery: The Dispatcher queries a distributed Session Location Store (Redis cluster) to look up active WebSocket gateway connection nodes for all members of the conversation.
- Gateway Dispatch: The Dispatcher routes the message to the targeted WebSocket Gateway nodes housing active client sessions.
- Client Push: The WebSocket Gateway pushes the frame to the client devices.
4. Scalable Fanout Strategies
Fanout requirements differ significantly between small DMs and huge organizational channels:
Strategy A: Direct Connection Lookup (Small Channels / DMs, < 500 members)
- Read channel membership from Redis.
- Query Session Registry: Find active
(user_id, device_id)pairs and their assignedgateway_node_id. - Push directly over internal RPC to target gateways.
Strategy B: Pub/Sub Gateway Subscriptions (Large Channels, up to 100K members)
- Fetching 100,000 member lists and cross-referencing session tables per message creates severe bottlenecks.
- Solution: When a user opens a channel in their client UI, the client's WebSocket node subscribes to an internal Pub/Sub broker channel topic (
pubsub:channel:{conversation_id}). - When a message arrives for a massive channel, the Real-Time Dispatcher publishes once to
pubsub:channel:{conversation_id}. - Gateway servers hosting connected channel listeners receive the payload via broadcast sub-tree and forward it to local sockets.
5. Missed-Message Recovery & Cold Start
Clients disconnect frequently (e.g., switching from Wi-Fi to cellular, closing laptop lid). The catch-up protocol must guarantee no missed messages and zero duplicates.
Catch-Up Protocol (Delta Sync)
- Local State Snapshot: Clients maintain a local database (SQLite/WatermelonDB) tracking
last_sequence_idfor every channel loaded locally. - Reconnection Handshake: Upon reconnecting, the client sends a
sync_statemap:{ "conversations": [ {"conversation_id": "c123", "last_sequence_id": 4105}, {"conversation_id": "c456", "last_sequence_id": 890} ] } - Delta Fetch:
- If
server_current_sequence_id - client_last_sequence_idis within a reasonable threshold (e.g., < 100 messages), the server returns the missing message range:SELECT * FROM messages WHERE conversation_id = 'c123' AND sequence_id > 4105 ORDER BY sequence_id ASC; - If the gap is too large (e.g., thousands of messages), the server sends a signal to truncate local storage and load the latest top 50 messages on demand.
- If
Cold Start Optimization
Downloading all messages across 500 channels on app launch causes extreme network overhead and slow initial rendering.
- Workspace Sync Tiering:
- Phase 1 (Critical): Fetch user context, active channel list, and unread badges metadata (
conversation_id,highest_sequence_id,user_last_read_sequence_id). Render sidebar immediately. - Phase 2 (Active View): Load the latest 50 messages for only the currently selected active conversation.
- Phase 3 (Lazy Load): Fetch history for other channels only when the user selects them.
- Phase 1 (Critical): Fetch user context, active channel list, and unread badges metadata (
6. Strict Ordering & Idempotency
Per-Conversation Ordering Mechanics
- Each conversation possesses an epoch/counter.
- Using a distributed lock or database transaction on the
conversationsmetadata table:UPDATE conversations SET current_sequence_id = current_sequence_id + 1 WHERE conversation_id = $1 RETURNING current_sequence_id; - Alternatively, use a high-throughput sequence generator service (such as a Redis
INCRbacked by persistent log replication) perconversation_id. - Clients render messages ordered strictly by
sequence_id.
Handling Duplicate Submissions (Idempotency)
- Network retries from the client can cause duplicate write attempts.
- The client generates a unique
client_message_id(UUID v4) prior to transmission. - Ingestion nodes check a short-lived key-value deduplication cache (Redis with 24-hour TTL) keyed by
(conversation_id, client_message_id). - If the key exists, return the previously assigned
sequence_idimmediately without executing duplicate writes.
7. Notification Routing Tradeoffs
Not every message should trigger a loud push notification (APNs/FCM).
+-----------------------------+
| Incoming Message Event |
+-----------------------------+
|
v
+-----------------------------+
| Is recipient active on |
| active WebSocket session? |
+-----------------------------+
/ \
Yes / \ No
v v
+-----------------------+ +-----------------------+
| Suppress Push | | Evaluate Notification |
| Notification; send | | Rules (Mentions, DMs, |
| in-app silent badge | | Mute Settings) |
+-----------------------+ +-----------------------+
|
v
+-----------------------+
| Send APNs / FCM Push |
+-----------------------+
- Presence Delay / Coalescing Buffer: When a user transitions to offline, delay mobile push notifications by 5–10 seconds. If the user reconnects during this window (e.g., app swap), cancel the pending mobile push to prevent notification spam across multiple devices.
8. System Bottlenecks & Capacity Estimation
Scale Profile
- Writes: 100k msgs/sec peak. Assuming average message payload of 500 bytes: $$\text{Write Throughput} = 100,000 \times 500\text{ bytes} = 50\text{ MB/sec}$$
- Database Storage: $$\text{Daily Volume} = 100,000\text{ msgs/sec} \times 86,400\text{ sec/day} \approx 8.64\text{ Billion messages/day}$$ $$\text{Daily Storage} = 8.64\text{ Billion} \times 500\text{ bytes} \approx 4.32\text{ TB/day (uncompressed)}$$
Scaling Bottlenecks & Mitigations
- Hot Channels (e.g., 100k-member #announcements channel):
- Problem: A message sent to a massive channel triggers 100k simultaneous socket dispatches, overwhelming single gateway nodes.
- Mitigation: Use fanout trees via internal pub/sub networks and batch WebSocket payload transfers.
- WebSocket Gateway Connection Memory:
- 10M concurrent users keeping active connections requires dedicated edge servers. Assuming 10 KB of memory per connection (OS TCP buffers + WebSocket context), 10M users require ~100 GB RAM. Managed easily by scaling connection proxies horizontally behind an API Gateway layer.
- Database Write Locks on Sequence Counters:
- Problem: DB locks for monotonically increasing
sequence_idcan create bottlenecks for rapidly updated channels. - Mitigation: Sequence counter generation is decoupled using partitioned memory counters (e.g., Redis cluster running Lua script
INCR) with periodic sync to cold storage metadata.
- Problem: DB locks for monotonically increasing