Build a Multi-Device Chat Backend for Two-Party Conversations
System DesignModel answerLast updated
Design a low-latency chat service for two-party conversations where each user has several devices, covering delivery state, push fallback, retry-safe sends and stable history paging.
Problem
You are asked to design the backend for a direct-messaging feature between exactly two parties, for example a customer and a support agent, or two members of a marketplace. Each person may be signed in on several devices at once (phone, tablet, browser). A message sent from one device must show up on every other device of the sender, and on every device of the recipient. Devices that are offline or backgrounded should be reached through mobile push (APNs/FCM).
Functional requirements
- Send text messages between two users with low latency.
- Multi-device sync: all devices of both participants converge on the same conversation view.
- Message states:
sent,deliveredandread, visible consistently across devices. - Push fallback for devices with no live connection.
- History: clients can load older messages without gaps or duplicates, even while new messages keep arriving.
- Retry safety: flaky networks and client resends must never produce duplicate messages.
Non-functional requirements
- Online-to-online delivery under 150 ms.
- 99.99% availability of the messaging path.
- Strict ordering inside a single conversation; transport is at-least-once, so clients must process messages idempotently.
Scale
- 50 million daily active users, about 2 devices each.
- 500 million messages per day (about 6,000/s average, 25,000/s peak).
- Up to 10 million concurrent persistent connections.
What to cover
- APIs, data model, partitioning and the ordering mechanism.
- High-level architecture: connection gateways, session registry, storage, notification pipeline.
- How a message reaches every active session, and how read state propagates.
- A pagination scheme that stays correct under concurrent inserts.
- Failure handling: reconnects, deduplication, out-of-order arrival.
Back your design with rough capacity numbers and call out the trade-offs you are making.
Hints
Hint 1
Convert the scale into numbers first: peak sends multiplied by roughly four target devices (two for each participant) gives your fan-out rate, and 10M sockets tells you how many gateway nodes you need.
Hint 2
Order messages with a per-conversation sequence number assigned by a single owner for that conversation, and use a client-generated message ID so a retry can be recognised and answered with the same sequence number.
Hint 3
Track delivered and read as per-user, per-conversation watermarks (highest sequence number) rather than per-message flags, and give each device a sync cursor over a per-user event log so reconnecting is a simple replay.
Hint 4
For paging, avoid offsets: use a cursor on the sequence number (before for older pages, after for filling gaps), which stays stable while new rows are appended.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify and size
Assumptions to confirm: text only, a message size cap (say 4 KB), history kept indefinitely, ordering needed per conversation but not globally.
- Fan-out: 25K msgs/s at peak, each reaching about 4 devices (sender's other device plus both recipient devices, with the sending device getting an ack), so on the order of 100K device deliveries/s, plus a similar volume of receipt events (reduced by watermarks, see below).
- Connections: 10M sockets at roughly 100-200K per tuned gateway means about 50-100 gateway nodes, spread across regions and over-provisioned for failover.
- Storage: 500M/day at about 1 KB is roughly 0.5 TB/day, so about 180 TB/year raw and around 550 TB/year with 3x replication. This demands a partitioned store.
2. API
Real-time traffic goes over WebSocket; bootstrap and history go over REST.
POST /v1/conversations/{conv_id}/messages
{ client_msg_id: UUID, body }
-> { message_id, seq, created_at } // identical response on retry
GET /v1/conversations/{conv_id}/messages?before_seq=&limit=50
-> { messages, next_cursor }
GET /v1/sync?since=<cursor> // catch-up after reconnect
POST /v1/conversations/{conv_id}/read { up_to_seq }
WebSocket frames: SEND, SEND_ACK{client_msg_id, seq}, MSG{conv_id, seq, ...}, DELIVERED / READ{conv_id, up_to_seq}, PING.
3. Data model
Use a partitioned wide-column or key-value store (Cassandra, DynamoDB). The conversation is the unit of partitioning.
| Table | Partition key | Clustering | Notes |
|---|---|---|---|
conversations | conv_id (hash of the sorted user pair) | none | participants, next_seq |
messages | conv_id | seq DESC | message_id, client_msg_id, sender, body, created_at |
dedup | (conv_id, client_msg_id) | none | seq, TTL about 7 days |
read_state | (user_id, conv_id) | none | last_delivered_seq, last_read_seq |
inbox | user_id | last_activity DESC | conversation list with preview |
devices | user_id | device_id | push token, platform, sync cursor |
user_events | user_id | user_seq | per-user log of messages and receipts, TTL about 30 days |
Ordering. seq is a gap-free, monotonic counter per conversation. Route each conversation to one owner shard via consistent hashing on conv_id; the owner increments next_seq and writes the message and the dedup row in one transaction (or a conditional/lightweight transaction). Contention is tiny because one 1:1 chat rarely exceeds a few messages per second. Trade-off: a global ordering service would be a bottleneck and is unnecessary.
Receipts as watermarks. "Read up to 812" implies everything earlier is read. Storing a watermark per (user, conversation), updated with max(), collapses receipt traffic and makes updates idempotent and commutative.
4. Architecture
Devices --WS--> Gateways (socket state only) --> Message Service
^ | assign seq, dedup, persist
| v
Session Registry (Redis) Message store / inbox / user_events
^ |
| Kafka (key = conv_id)
| v
+------------------- Fan-out Service --> Push Service (APNs/FCM)
Send path:
- Device A1 sends
SEND{client_msg_id}. - Message Service looks up
dedup. On a hit it returns the storedseqand stops. On a miss it assignsseq, persists the message, updates both inboxes and appends to both users'user_events. - It returns
SEND_ACKto A1: state is sent. Durability comes before acknowledgement. - It publishes to Kafka keyed by
conv_id, which preserves per-conversation order for consumers. - Fan-out looks up sessions for both users and pushes
MSGto every live connection except A1. - Devices without a live session, or in the background, get a push notification.
Keeping gateways free of business logic lets them be scaled and deployed independently, and a gateway crash only costs reconnects.
5. Multi-device behavior
- Session registry: Redis hash
sessions:{user_id}mappingdevice_idto{gateway_id, conn_id, foreground}, with TTLs refreshed by roughly 30 s heartbeats and deletion on clean disconnect. A stale entry only costs one failed send, which then falls back to push. - Self-sync: the sender's other devices get the same
MSGand render it as outgoing. - Delivered: when any recipient device acks, the server advances
last_delivered_seqand emitsDELIVEREDto the sender's devices. - Read: when B1 opens the chat it posts
read{up_to_seq}; the server updates the watermark monotonically and notifies the sender's devices ("read") and the recipient's other devices (clear badge, retract the notification). - Catch-up: each device stores a cursor into
user_events; on reconnect it calls/sync?since=cursorand replays messages, receipts and its own sends from other devices in order.
6. Pagination
Offset paging breaks when new rows arrive, because every offset shifts and pages repeat or skip items. Use a seq cursor:
SELECT * FROM messages
WHERE conv_id = ? AND seq < :before_seq
ORDER BY seq DESC LIMIT 50;
The next cursor is the smallest seq returned. Because seq is immutable and unique per conversation, pages are stable regardless of inserts. A forward query (seq > :after_seq) fills gaps. Both are served straight from the clustering index. Make the cursor opaque so the encoding can evolve.
7. Failure modes
- Duplicates: the client creates
client_msg_idonce and reuses it on every retry; the serverdeduprow returns the sameseq. Clients also dedupe inbound frames by(conv_id, seq)since transport is at-least-once. - Out-of-order arrival: clients insert by
seq. Seeing 15 after 12 reveals a gap, so they fetch 13-14 immediately rather than wait. - Reconnect: exponential backoff with jitter to avoid a thundering herd after a gateway loss; re-register the session, then run
/sync. - Partial failure after persist: if the service crashes before Kafka publish, a recovery job (or a transactional outbox) republishes; duplicates are harmless because of idempotent clients.
- Shard owner failure: ownership moves via the consistent-hash ring; the transaction on
next_seqprevents two owners from issuing the same number. - Push failures: invalid tokens are pruned; push is best effort, and
/syncis the source of truth. - Multi-region: home each conversation in one region for sequencing, and accept cross-region latency for the minority of cross-region pairs, or pin gateways close to users and forward to the owner.
Common mistakes
- Using timestamps for ordering (clock skew, ties).
- Per-message, per-device receipt rows, which explode write volume.
- Offset-based history paging.
- Acknowledging the sender before the message is durably stored.
- Putting business logic in the gateways, which makes them hard to scale and deploy.