Full answer
Requirements
Functional:
- One-to-one and group chats (groups up to 1,024 members).
- Sent, delivered and read receipts; online and last-seen presence.
- Offline users receive messages when they reconnect, plus a push notification.
- Message history synced across a user's devices; media sent as attachments.
Non-functional:
- Low latency: under about 300 ms end to end for users in the same region.
- Messages are never lost once the sender sees "sent", and they appear in the same order for all members of a conversation.
- High availability; end-to-end encryption means the server stores only ciphertext.
Capacity estimates
Assumptions: 500M DAU; 40 messages sent per user per day; 200 bytes per stored message (ciphertext plus metadata, media stored separately); peak factor 2; 30% of DAU connected at peak; one gateway server holds 100,000 connections (an assumption that depends on hardware and tuning).
- Messages: 500M x 40 = 20B per day; 20B / 86,400 = about 231,000 per second; about 463,000 per second at peak.
- Storage: 20B x 200 B = 4 TB per day; about 1.46 PB per year before replication. If, like WhatsApp, the server deletes messages after delivery to all devices, stored volume drops to the undelivered backlog, but multi-device history sync requires keeping them.
- Connections: 30% x 500M = 150M concurrent; 150M / 100,000 = 1,500 gateway servers, plus headroom.
API
Over the WebSocket (JSON shown for readability; production often uses a binary format):
client -> server {"type":"send","client_msg_id":"c-71","conv_id":"g42","body":"<ciphertext>"}
server -> client {"type":"ack","client_msg_id":"c-71","msg_id":"m-9001","seq":5512}
server -> client {"type":"message","conv_id":"g42","seq":5512,"from":77,"body":"..."}
client -> server {"type":"receipt","conv_id":"g42","up_to_seq":5512,"kind":"read"}
HTTP for the rest: GET /v1/conversations/{id}/messages?after_seq=5400, POST /v1/media (returns an upload URL).
Data model
messages(wide-column store such as Cassandra or ScyllaDB): partition keyconv_id(with a time bucket for very active groups), clustering keyseq; columnsmsg_id,sender_id,body,created_at.conversationsandmembers:conv_id,user_id,last_read_seq,last_delivered_seq.user_inbox(per user, per device): pending message references for offline delivery.sessions(Redis):user_id -> [gateway_id, device_id], refreshed by heartbeats.
High-level design
flowchart LR
A[Sender app] -- WebSocket --> GW1[Gateway]
GW1 --> CS[Chat service]
CS --> SEQ[Per-conversation sequencer]
CS --> MS[(Message store)]
CS --> SR[(Session registry)]
CS --> GW2[Recipient gateway]
GW2 -- WebSocket --> B[Recipient app]
CS --> PN[Push notification service]
PN --> APNS[APNs / FCM]Message flow
- Sender sends with a
client_msg_id(for idempotent retries). - Chat service assigns the next
seqfor the conversation (owned by one partition leader, or an atomic counter per conversation), writes the message, then acks the sender: one tick. - It looks up each recipient's sessions. Online: forward to their gateway. Offline: add to their inbox and send a push notification.
- Recipient device acks delivery; the sender gets two ticks. Read receipts update
last_read_seq. - On reconnect, a device asks for everything after its last seen
seqper conversation, so missed messages are filled in order.
Group chats
Write the message once per conversation, then fan out delivery to members. With a cap of 1,024 members the fan-out is bounded. For end-to-end encryption, the sender's client encrypts for each member device (or uses a group key scheme), which is one reason group sizes are capped.
Bottlenecks and trade-offs
- Gateways are stateful. Deploys drain connections gradually; clients reconnect with jittered backoff to avoid a reconnect storm after a gateway failure.
- Sequencing per conversation gives a total order inside a chat without global coordination. A very hot group serialises on one sequencer; that is acceptable because one conversation's write rate is modest.
- Presence is expensive at scale: publishing every online/offline change to every contact is a large fan-out. Update presence lazily (when a chat is opened) and batch changes.
- Storage choice: a wide-column store handles the write rate and "latest messages in a conversation" reads well; it does not offer cross-partition transactions, which chat does not need.
- Multi-region: users connect to the nearest region; a conversation has a home region for sequencing, so cross-region chats pay one extra hop. The alternative, multi-leader writes, would break the single order per chat.
By level
Fresher: Explain why chat uses WebSockets, sketch the message table and the send-deliver-read flow, and how offline users get messages later. A fresher should describe what the single and double ticks mean.
Mid: Estimate messages, storage and connections, design the session registry and per-conversation ordering, and choose a storage engine. Expect per-conversation sequence numbers to explain ordering.
Senior: Address gateway failure and reconnect storms, presence fan-out, end-to-end encryption effects on groups and multi-device, multi-region sequencing, and storage retention cost. Expect a plan for reconnect storms after a gateway fails.
Key points
- Persistent WebSocket connections through a stateful gateway tier
- Session registry maps users to gateways for routing
- Per-conversation sequence numbers give consistent order and gap-free sync
- 20B messages per day is about 231k per second; 150M connections needs about 1,500 gateways at 100k each
- Offline delivery through per-device inbox plus push notification
Common mistakes
- Ordering by client timestamps
- Polling the server for new messages
- Storing messages partitioned by user instead of conversation, duplicating writes
- Ignoring reconnect storms when a gateway dies
Follow-ups
- How do you sync history to a newly added device?
- How would you implement "last seen" without a huge fan-out?
- What changes for groups of 100,000 members (channels)?
Tips
- Lead with the connection model, then the message path
- Use client_msg_id and seq to show idempotency and ordering
- Do the connection count math to size gateways
Evaluation rubric
- Complete requirements including receipts and offline delivery
- Correct capacity math with assumptions
- Sound routing, ordering and storage design
- Discusses gateways, presence, groups and multi-region trade-offs