{}DSA Atlas

Design a Chat System (WhatsApp / Messenger / Slack)

Real-time 1:1 and group messaging at billions of messages per day — persistent WebSocket gateways and connection routing, message flow with server acks and delivery/read receipts, per-conversation ordering with sequence numbers, offline delivery and sync, group fan-out, presence, push notifications, media, and end-to-end encryption.

Advanced5 interview questions

1. Requirements

Functional

  • 1:1 and group chat (up to ~1,000 members; large channels as a follow-up).
  • Delivery states: sent, delivered, read.
  • Offline messages delivered on reconnect; multi-device sync.
  • Presence and typing indicators.
  • Media (images, video, voice notes); push notifications.

Non-functional

  • 500M DAU, ~40 messages per user per day → ~20B messages/day.
  • End-to-end latency < 200 ms for online recipients.
  • Never lose an acknowledged message; no duplicates shown; ordered per conversation.
  • Highly available; mobile-friendly (flaky networks, battery).

2. Estimation

QuantityValue
Messages20B/day ≈ 230k/s avg, ~1M/s peak
Concurrent connections~200M
Connections per gateway (tuned)~500k–1M → ~300–500 gateway servers
Message size~200 B text + metadata → ~4 TB/day before replication
RetentionWhatsApp: until delivered (then device-side); Slack/Messenger: forever → PB scale

3. Protocol and API

JSON
// client → server over WebSocket
{"type": "send", "client_msg_id": "c7f1…", "conv_id": "cv_42", "body": "hi!", "ts": 1760000000123}
// server → sender
{"type": "ack", "client_msg_id": "c7f1…", "msg_id": "m_9001", "seq": 1734}
// server → recipient
{"type": "message", "conv_id": "cv_42", "seq": 1734, "msg_id": "m_9001", "from": "u_7", "body": "hi!"}
// recipient → server
{"type": "delivered", "conv_id": "cv_42", "up_to_seq": 1734}
{"type": "read", "conv_id": "cv_42", "up_to_seq": 1734}
// reconnect sync
{"type": "sync", "cursors": {"cv_42": 1700, "cv_77": 88}}

4. Data model

Text
messages        partition key: conv_id     clustering: seq DESC
                columns: msg_id, sender_id, body/ciphertext, media_ref, created_at, client_msg_id
conversations   conv_id → type, members (or membership table), last_seq
membership      user_id → [conv_id, last_read_seq, last_delivered_seq, muted]
sessions        user_id → [{device_id, gateway_id, connected_at}]    (Redis, TTL)

Cassandra/ScyllaDB/HBase suits the message store: write-heavy, partitioned by conversation, range reads by sequence (Discord moved from Cassandra to ScyllaDB; Messenger uses HBase-derived systems). Very active conversations can be bucketed by time ((conv_id, bucket)) to bound partition size.

5. High-level design

Alice Bob gateway 1WebSockets gateway 7WebSockets message svcseq · persist · route session registry (Redis) message store (Cassandra) group membership push svc → APNs / FCM media → S3 + CDN route to Bob's gateway
Gateways hold connections; stateless message services persist and route.
AliceserverBob send(client_msg_id) seq=1734, persist ack → ✓ sent message seq 1734 delivered ≤ 1734 ✓✓ delivered read ≤ 1734 blue ✓✓ read
Receipts are cumulative ("up to seq"), so one ack covers many messages.

6. Deep dives

Connection management

  • Gateways are stateful (sockets) but hold no durable data; L4 load balancers distribute connections; clients reconnect with backoff + jitter when a gateway dies (and sync from their cursors).
  • Session registry maps user/device → gateway; entries have TTL refreshed by heartbeats.
  • Routing between services and gateways: each gateway subscribes to its own channel (Redis pub/sub, NATS, or direct gRPC), so the message service publishes to gateway:7.
  • Drain gateways gracefully for deploys (stop accepting, ask clients to reconnect elsewhere gradually).

Offline sync and multi-device

Each device stores per-conversation cursors; on reconnect it sends them and receives missing messages in batches (paginated). The server tracks per-user last_delivered_seq per conversation for receipts. An inbox/change log per user (list of conversation updates since cursor X) avoids scanning all conversations.

Group fan-out

Python
def deliver(message, conv):
    members = membership.members(conv.id)                 # cached
    by_gateway = defaultdict(list)
    offline = []
    for user in members:
        sessions = registry.sessions(user)
        if not sessions:
            offline.append(user)
        for s in sessions:
            by_gateway[s.gateway_id].append(s.device_id)
    for gw, devices in by_gateway.items():
        bus.publish(f"gateway:{gw}", {"message": message, "devices": devices})
    push.notify_batch(offline, conv, message, collapse_key=conv.id)

Media

Client uploads to object storage via pre-signed URL (encrypted client-side for E2EE), then sends a message containing the media reference + key; recipients download from CDN. Thumbnails are generated client-side (E2EE) or server-side.

Push notifications

When no active session exists (or the app is backgrounded), send through APNs/FCM via a notification service with rate limiting and collapse keys for busy groups. See notification system.

7. Trade-offs

DecisionChoiceAlternative
TransportWebSocket (MQTT for low-power)long polling fallback
Orderingper-conversation server seqclient timestamps (unreliable)
Storewide-column partitioned by conversationSQL sharded by conversation
Group deliverystore once, fan-out to online, pull for offlinecopy per member inbox (costly for big groups)
PresenceTTL + subscribe-on-viewbroadcast to all contacts (doesn't scale)

Interview questions

0 / 5 marked confident

Answer out loud first, then open the model answer. Mark a question confident only when you could explain it to an interviewer without notes.