System Design · Lesson 21
How WhatsApp-Style Chat Works
Learn scaling, estimation, interview frameworks, rate limiters, URL shorteners, consistent hashing, KV stores, and distributed IDs. Diagrams, labs, and mock interview links included.
On this page
Diwali night, family WhatsApp group
Fifty-three relatives in "Sharma Family 🪔". Mummy sends a photo of diyas. Chacha forwards a Good Morning meme from 2019. Your cousin in Toronto replies at 3 AM his time. Nani types "happy diwali beta" without punctuation. Messages arrive out of order sometimes. Blue ticks appear. Someone sends a voice note. The group never sleeps.
That is a chat system. Not email. Not a news feed. Real-time (or near-real-time) messaging with delivery states, 1:1 and group conversations, and the expectation that if you sent it, the other person will see it — even if they were offline.
This chapter covers the core: message flow, WebSocket vs polling, schema, delivery states. No gateway clusters, no presence at scale. Lesson 22.

Diwali family WhatsApp group chaos
Fifty-three relatives. One group. Zero punctuation from Nani.
Chat system architecture
Blue ticks are a distributed systems problem wearing a UX costume.
Requirements — functional and non-functional
Functional
- 1:1 chat — two users exchange messages in a private conversation
- Group chat — N users in one conversation (family group, office team)
- Message history — scroll up to see older messages
- Delivery states — sent ✓, delivered ✓✓, read ✓✓ (blue)
- Offline support — messages queue and deliver when user comes back
- Optional: media, typing indicators, reply-to (mention, do not over-build)
Non-functional
- Delivery latency — < 100 ms for online recipients; feels instant
- Message ordering — mostly chronological per conversation; perfect global order not required
- Durability — once server ACKs send, message must not be lost
- Scale hint: write-heavy during festivals; 1:1 is symmetric, groups fan out
Clarify: WhatsApp-scale or startup MVP? I commit to text messages, 1:1 + group, three delivery states. Skip E2E encryption implementation unless asked — mention it exists in production.
Clarifying with the interviewer
1You: "1:1 and group chat both in scope?"
2 -> Interviewer: "Yes, group up to 256 members."
3
4You: "Real-time delivery — WebSocket acceptable?"
5 -> Interviewer: "Yes."
6
7You: "Do we need read receipts and delivery ticks?"
8 -> Interviewer: "Yes, like WhatsApp."
9
10You: "Offline messages — store and deliver on reconnect?"
11 -> Interviewer: "Yes."
12
13You: "I will cover send/store/deliver flow, schema, WebSocket
14 transport, and delivery state machine. Scale in follow-up."
1:1 vs group chat
1:1 conversation:
- Exactly two participants
- Message sent once, delivered to one recipient
- Simple routing: recipient_id known at send time
Group conversation:
- N participants (cap at 256 for MVP — WhatsApp limit)
- Message sent once, fan-out to N-1 other members
- Each member has own delivery/read state per message
Group chat is a mini news feed fan-out inside one room. Same push pattern, smaller N. Diwali family group with 53 members is manageable synchronously; 256-member office group needs async fan-out.
WebSocket vs long polling
Client needs server-initiated delivery — HTTP request/response alone cannot push.
Long polling
1Client: GET /messages/poll?since=msg_123
2Server: holds connection open up to 30 sec
3 if new message → return immediately
4 else → return empty, client reconnects
Pros: works through corporate firewalls, no special protocol
Cons: high connection churn, latency spikes, wasteful on mobile battery
WebSocket (recommended)
1Client: WS connect wss://chat.schoolabe.com/ws?token=...
2Server: persistent bidirectional channel
3Client sends: { "type": "send", "conversation_id": "...", "body": "..." }
4Server pushes: { "type": "message", "payload": { ... } }
Pros: low latency, single connection, efficient for mobile
Cons: load balancer sticky sessions or connection registry at scale (Lesson 22)
Interview pick: WebSocket for real-time chat. Mention long polling as fallback for restrictive networks. Nobody designs WhatsApp on long polling in 2026.
Message flow: send → store → deliver
The happy path for 1:1 chat:
11. Sender types message, taps Send
22. Client sends via WebSocket (or POST if WS down)
33. Chat server validates, assigns message_id, persists to DB
44. Server ACKs sender → "sent" ✓
55. Server looks up recipient's active WebSocket connection
66. If online: push message → recipient ACKs → "delivered" ✓✓ to sender
77. Recipient opens chat → "read" ✓✓ blue to sender
88. If offline: message stays in DB; push notification via notification service
Chat system architecture
Critical rule: persist before ACK. If server crashes after ACK but before DB write, message is lost. Write to DB (or durable queue) first, then ACK sender.
Delivery state machine
1 ┌──────────┐
2 │ sending │ (client optimistic UI)
3 └────┬─────┘
4 │ server ACK
5 ┌────▼─────┐
6 │ sent │ ✓
7 └────┬─────┘
8 │ recipient device ACK
9 ┌────▼─────┐
10 │ delivered│ ✓✓
11 └────┬─────┘
12 │ recipient opens chat / read_receipt
13 ┌────▼─────┐
14 │ read │ ✓✓ blue
15 └──────────┘
Each state transition is a separate event — sender's UI updates via WebSocket push.
1def on_message_received_by_device(message_id, recipient_id):
2 db.update_delivery_state(message_id, recipient_id, "delivered")
3 notify_sender(message_id, state="delivered")
4
5def on_message_read(message_id, recipient_id):
6 db.update_delivery_state(message_id, recipient_id, "read")
7 notify_sender(message_id, state="read")
Group chat: track delivery state per participant per message. 53-member group = 53 rows in message_delivery table for one message.
Database schema
Conversations
1CREATE TABLE conversations (
2 id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
3 type VARCHAR(10) NOT NULL CHECK (type IN ('direct', 'group')),
4 title VARCHAR(100), -- group name; NULL for 1:1
5 created_at TIMESTAMP DEFAULT NOW()
6);
Participants
1CREATE TABLE participants (
2 conversation_id UUID NOT NULL REFERENCES conversations(id),
3 user_id BIGINT NOT NULL REFERENCES users(id),
4 joined_at TIMESTAMP DEFAULT NOW(),
5 last_read_at TIMESTAMP, -- for unread badge
6 PRIMARY KEY (conversation_id, user_id)
7);
8
9CREATE INDEX idx_participants_user ON participants(user_id);
Index on user_id — "list all conversations for this user."
Messages
1CREATE TABLE messages (
2 id BIGSERIAL PRIMARY KEY,
3 conversation_id UUID NOT NULL REFERENCES conversations(id),
4 sender_id BIGINT NOT NULL REFERENCES users(id),
5 body TEXT NOT NULL,
6 created_at TIMESTAMP DEFAULT NOW()
7);
8
9CREATE INDEX idx_messages_conv_created ON messages(conversation_id, created_at DESC);
Message delivery (per-recipient state)
1CREATE TABLE message_delivery (
2 message_id BIGINT NOT NULL REFERENCES messages(id),
3 recipient_id BIGINT NOT NULL REFERENCES users(id),
4 state VARCHAR(20) NOT NULL DEFAULT 'sent'
5 CHECK (state IN ('sent', 'delivered', 'read')),
6 updated_at TIMESTAMP DEFAULT NOW(),
7 PRIMARY KEY (message_id, recipient_id)
8);
For 1:1 chat, sender is excluded from message_delivery — only the other participant gets a row.
API design
Send message (WebSocket frame)
1{
2 "type": "send_message",
3 "conversation_id": "a1b2c3d4-...",
4 "client_msg_id": "local-uuid-for-dedup",
5 "body": "Happy Diwali! 🪔"
6}
Server response:
1{
2 "type": "message_ack",
3 "client_msg_id": "local-uuid-for-dedup",
4 "message_id": 84729163,
5 "state": "sent",
6 "created_at": "2026-11-01T18:30:00Z"
7}
client_msg_id lets the client deduplicate retries — tap Send twice on slow network should not create two messages.
Get message history (HTTP)
1GET /api/v1/conversations/{id}/messages?limit=50&before=84729100
2Authorization: Bearer <token>
Cursor-based pagination on created_at or message_id. User scrolls up → fetch older batch.
List conversations
1GET /api/v1/conversations
Returns conversations sorted by last_message_at — denormalized column updated on each new message.
Group chat send flow
1def send_group_message(conversation_id, sender_id, body):
2 msg = db.insert_message(conversation_id, sender_id, body)
3 recipients = db.get_participants(conversation_id) - {sender_id}
4 for rid in recipients:
5 db.insert_delivery(msg.id, rid, state="sent")
6 if is_online(rid):
7 ws_push(rid, msg)
8 else:
9 notification_service.send_push(rid, preview=body[:50])
10 return msg
Push notification for offline users ties into the notification system — separate service, separate chapter. Link: Notification System.
Offline sync (brief)
On reconnect: client sends last_synced_message_id per conversation → server returns gap → client merges local SQLite cache → batch delivery ACKs. Lesson 22 covers sync at 100M DAU.
Preview: what Lesson 22 adds
Core design breaks when:
- 100M DAU, each holding a WebSocket open
- Gateway needs to route message to correct server holding recipient's connection
- Group with 256 members during festival = fan-out storm
- "Exactly once" delivery under network partitions
Continue here: Chat System at Scale — Gateways, Presence, and Partitioning.