Build a Messaging Platform with Instant and Offline Delivery
System DesignModel answerLast updated
Design an instant messaging system supporting direct and group chats with real-time delivery, offline queuing, and cross-device history sync.
You're building a messaging platform for a consumer application. The platform needs to support both direct conversations between two people and group chats with multiple participants. Your design should handle:
- Messages delivered instantly to recipients who are currently connected
- Messages queued for recipients who are offline, delivered when they come back online
- Full conversation history accessible from any device a user logs in from
- Text messages (assume no media for initial scope)
Consider a scale of 100 million daily active users, with each user sending an average of 50 messages per day. Group sizes typically range from 3-50 members, with some large groups reaching 1,000+ members.
Your interviewer wants to understand:
- How you'll maintain persistent connections and route messages to the right recipients
- Your storage strategy for conversations and message history
- How you'll handle message ordering, deduplication, and reliability
- Your approach to offline delivery and syncing across multiple devices
- How group messages scale, especially for large groups
- Trade-offs in your design and what breaks at extreme scale
Walk through your high-level architecture, key components, data models, and API contracts. Discuss failure modes and how your system handles them.
Hints
Hint 1
Think about the lifecycle of a message from send to delivery - what needs to happen at each step and which components are involved?
Hint 2
Consider how you'll maintain a mapping from user ID to their active connection endpoints, and what happens when that mapping is stale.
Hint 3
For groups, evaluate whether you fan out at write time or read time, and how the group size influences that decision.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
High-Level Architecture
The system consists of several layers:
Connection Layer: Stateful gateway servers maintain WebSocket connections with clients. Each gateway tracks which users and devices are connected to it.
Routing & Presence Layer: A distributed service (using Redis or similar) maintains a live mapping of user_id + device_id → gateway_server. When a message arrives, we query this layer to find where to route it.
Message Service: Stateless application servers that handle message validation, persistence, fan-out logic, and coordination between components.
Storage Layer:
- Message database (Cassandra or similar) for conversation history
- Metadata store (PostgreSQL) for conversation membership, settings
- Queue system (Kafka/SQS) for offline message delivery
Connection Management
Clients establish WebSocket connections to gateway servers. On connect, the client sends an auth token and device ID. The gateway:
- Validates the token
- Registers the connection in the presence service:
SET user:123:device:abc gateway_host:port TTL=60s - Sends a heartbeat every 30s to keep the mapping fresh
When a gateway crashes, TTLs expire and stale routes disappear. Clients detect disconnection and reconnect to another gateway.
Message Flow - Direct Conversation
Sending:
- Client sends:
{msg_id: "uuid", conversation_id: "conv_456", text: "hello", timestamp: 1234567890} - Gateway forwards to message service
- Message service writes to storage:
INSERT INTO messages (msg_id, conv_id, sender_id, text, created_at) - Query presence service for recipient's active connections
- If online: route message through their gateway(s) for immediate delivery
- If offline: enqueue in their offline message queue
- Acknowledge to sender with server timestamp
Receiving:
Gateway pushes message to client. Client sends ack: {msg_id: "uuid", received_at: timestamp}. Gateway forwards ack to message service for receipt tracking.
Message Ordering and Idempotency
Ordering: Each message gets a server-assigned sequence number per conversation. Storage model:
messages(
conversation_id,
sequence_number, -- auto-increment per conversation
msg_id, -- client-provided UUID
sender_id,
text,
created_at
)
PRIMARY KEY (conversation_id, sequence_number)
Clients display messages by sequence number. This guarantees ordering within a conversation regardless of clock skew.
Idempotency: Client provides msg_id (UUID). Message service checks for existing message with that ID before writing. If found, return success without duplicate write. This handles retry storms.
Multi-Device Sync
Each device maintains a cursor: the highest sequence number it has seen for each conversation. On connect (or periodic sync):
- Client sends:
{conversation_id: "conv_456", last_seq: 1230} - Server queries:
SELECT * FROM messages WHERE conversation_id = 'conv_456' AND sequence_number > 1230 ORDER BY sequence_number LIMIT 100 - Returns messages + new cursor position
Incremental sync keeps bandwidth low. Full history paginated backwards for scrolling through old messages.
Group Message Fan-Out
Write-Time Fan-Out (for groups <100 members):
- Message service writes one message record
- Queries conversation membership: 50 members
- For each member, checks presence and either pushes immediately or enqueues offline
- Tracks per-recipient delivery status
Read-Time Fan-Out (for large groups 1000+ members): Write once to shared conversation stream. Each recipient has a cursor. On read, query messages since their cursor. This avoids overwhelming the fan-out system but adds read latency and complicates offline delivery.
Hybrid: Use write-time fan-out up to 100 members, read-time for larger groups.
Offline Delivery
Per-user offline queue (Kafka partition keyed by user_id). When user reconnects:
- Gateway notifies message service of connection
- Message service drains offline queue for that user
- Delivers queued messages in order
- Removes from queue after ack
Queue retention: 30 days. Very old messages treated as history rather than real-time delivery.
Read Receipts
Client sends: {conversation_id, read_up_to_seq: 1250}. Server:
- Updates:
conversation_members(user_id, conversation_id, last_read_seq) - Notifies other conversation participants:
{user_id: 123, read_up_to: 1250}
To show "read by 3 of 5", query last_read_seq for all members and count how many have read past this message's sequence.
Data Models
Conversations Table (metadata):
conversation_id, type (direct/group), created_at, last_message_seq
Conversation Members:
conversation_id, user_id, joined_at, last_read_seq, notification_settings
Messages (partitioned by conversation_id):
conversation_id, sequence_number, msg_id, sender_id, text, created_at, edited_at
Use Cassandra or similar with partition key = conversation_id for fast range scans within a conversation.
Scaling Numbers
100M DAU × 50 messages/day = 5B messages/day = 58K writes/sec. With replication and fan-out (avg group size ~5), actual writes ~300K/sec.
Gateway layer: 100M concurrent connections, assume 10K connections per gateway server = 10,000 gateway servers.
Storage: 5B messages/day × 500 bytes avg = 2.5 TB/day. With replication and retention, size grows linearly.
Failure Handling
Gateway crash: Clients reconnect, re-register with presence service, sync missed messages using cursor.
Duplicate sends: Client retries with same msg_id. Idempotency check prevents duplicate writes.
Lost messages: Client tracks sent messages locally. If no ack within timeout, retry. Sequence numbers reveal gaps; client requests missing messages.
Network partition: Offline queue absorbs messages. Bounded staleness: if queue exceeds capacity, drop oldest and mark as requiring full resync.
Common Mistakes
- Forgetting per-conversation sequence numbers and relying on timestamps (clock skew breaks ordering)
- Not handling duplicate sends, causing message duplication on retry
- Fan-out to all group members synchronously, blocking sends for large groups
- Storing presence in a relational DB instead of a fast in-memory store
- Not considering multi-device: each device needs independent sync cursors
- Overloading read receipts: sending per-message receipts for every user in large groups creates O(n²) traffic
Trade-Offs
Persistent connections vs. polling: WebSockets give instant delivery but require gateway fleet. Polling simpler but higher latency and wasted requests.
Write-time vs. read-time fan-out: Write-time gives instant delivery but expensive for large groups. Read-time cheaper but complicates offline delivery.
Strong vs. eventual consistency: Strong consistency (Paxos/Raft for sequence assignment) guarantees order but adds latency. Eventual consistency (single writer per conversation) is faster but needs careful conflict resolution.
This design balances real-time delivery, reliability, and scale for a modern messaging platform.