Case study: Chat system

Topic 6 of 15 in Week 7: Classic case studies15 min readAdvancedFree course

Overview

Chat looks simple (send a message, see it appear) but combines real-time connections at huge scale, reliable delivery, ordering, multi-device sync and offline handling. It’s one of the most common interview problems.

Try the exercise first: 45 minutes, then compare.

1. Requirements

Functional

  • One-to-one and group chats (up to 500 members); text plus media.
  • Real-time delivery when online; push notification when offline.
  • Sent, delivered and read receipts; online/last-seen status.
  • History available on all of a user’s devices.

Non-functional

  • Low latency (under ~200 ms between users in the same region).
  • Messages are never lost and appear in the same order for everyone in a chat.
  • Highly available; scales to 100M DAU.

2. Estimates

Text
messages   : 100M × 40 = 4B / day ≈ 46,000 / s   (peak ~150,000 / s)
storage    : 4B × ~100 bytes (text + metadata) ≈ 400 GB / day ≈ 150 TB / year (before replication)
connections: suppose 30% online at peak → 30M concurrent WebSockets
gateways   : ~50k connections per server (conservative) → ~600+ gateway servers

3. API

Real-time traffic flows over a WebSocket as small frames:

Text
→ {"type": "send", "client_msg_id": "c-123", "conversation_id": "conv9", "body": "hi!"}
← {"type": "ack", "client_msg_id": "c-123", "seq": 5012, "server_ts": "…"}
← {"type": "message", "conversation_id": "conv9", "seq": 5013, "from": "u42", "body": "…"}
→ {"type": "read", "conversation_id": "conv9", "up_to_seq": 5013}

REST for everything else: GET /v1/conversations, GET /v1/conversations/{id}/messages?before_seq=…, media upload URLs.

4. Data model

Text
messages (Cassandra/ScyllaDB):
  PRIMARY KEY ((conversation_id), seq)   -- partition by chat, sorted by sequence
  sender_id | client_msg_id | body / media_ref | created_at
conversations:     conversation_id | type | members | last_seq
user_conversations: user_id | conversation_id | last_read_seq | last_activity   -- the inbox
sessions (Redis):  user_id:device_id → gateway_id   (TTL, refreshed by heartbeat)

5. High-level design

Chat system. Asha and Ben each hold a two-way WebSocket connection, Asha to WS gateway 1 and Ben to WS gateway 2. Asha’s message goes from gateway 1 to the chat service (1), which assigns a sequence number and fans out. The chat service stores the message in a Cassandra messages store (2), asks the Redis presence registry where Ben is connected (3), and sends the message to gateway 2, which delivers it to Ben (4). If the recipient is offline, they receive a push notification and, on reconnect, sync from the last seen sequence number. Group chats fan out per member for small groups or have members read from the group’s log for large ones. Messages are partitioned by conversation ID and ordered by a per-conversation sequence number.

Send path:

  1. Asha’s app sends the message over its WebSocket to gateway 1.
  2. The chat service assigns the next sequence number for the conversation, stores the message durably, and acknowledges Asha (one tick: sent).
  3. It looks up Ben’s devices in the session registry.
  4. If Ben is online, it forwards the message to his gateway, which pushes it down the socket; Ben’s app acknowledges (two ticks: delivered). If he’s offline, the notification service sends a push.

6. Deep dives

Connection gateways

Gateways only hold connections and relay frames; they keep no chat state, so any client can connect to any gateway (via a load balancer that supports WebSockets). On connect, the gateway records user/device → gateway in Redis with a TTL refreshed by heartbeats. Routing between gateways uses a pub/sub channel per gateway, or direct RPC.

When a gateway dies, its clients reconnect elsewhere and the registry updates. Deploys drain connections gradually to avoid reconnect storms.

Ordering and deduplication

Client clocks are unreliable, and two senders can send at the same moment. Give each conversation a single owner (the chat-service partition responsible for it) that assigns a strictly increasing sequence number; everyone sorts by it. Clients send a client_msg_id so a retried send after a lost ack isn’t stored twice.

Storage and multi-device sync

Messages are append-only and read by conversation, newest first: a wide-column store partitioned by conversation_id and clustered by seq fits well. Very long-lived chats can use time buckets in the partition key. Each device remembers the last seq it has per conversation; on reconnect it asks for everything newer, so phones and laptops converge.

Group chats

  • Small groups (up to a few hundred): fan out on write: route each message to every member’s devices, and update each member’s inbox entry.
  • Very large groups or channels: members read from the group’s log, and only online members get live pushes.

Receipts in groups are aggregated (“read by 12”) rather than sent as individual messages to everyone.

Presence

Online status uses heartbeats: if no heartbeat for, say, 30 seconds, the user is offline. Broadcasting every status change to every contact is expensive for users with thousands of contacts, so publish presence only to users currently viewing that contact, and batch updates.

Offline delivery and push

When a recipient has no active connection, the chat service triggers a push notification through the notification platform. Push payloads are hints; the app then connects and syncs the actual messages.

Media and encryption

Images and video are uploaded to object storage with presigned URLs and served through a CDN; the message carries the reference. End-to-end encryption (such as the Signal protocol) means servers store and route ciphertext only, which limits server-side features like search.

7. Trade-offs and bottlenecks

  • Persistent connections make gateways memory-bound; plan capacity on connections, not requests.
  • Hot conversations (huge active groups) concentrate on one partition: use time-bucketed partitions and caching.
  • Storing before acknowledging adds a write to the latency path, but guarantees no loss.

8. Follow-up questions

  • Message search? Without E2E encryption, index asynchronously in a search engine; with it, search on the device.
  • Edits and deletes? Store them as new events referencing the original sequence.
  • Multi-region? Home each conversation in one region (its sequencer) and route users there, or replicate with care.

Recap

Chat systems keep persistent WebSocket connections on stateless gateways, track who is connected where in a registry, and route messages through a chat service that assigns per-conversation sequence numbers and stores messages durably before acknowledging. Messages live in a store partitioned by conversation; devices sync by sequence number; groups fan out per member or read from a shared log; offline users get push notifications.

Exercise

Design it yourself (45 minutes)

Set a 45-minute timer and design a chat app supporting one-to-one and group chats (up to 500 members), online/offline status, delivery and read receipts, message history on all of a user's devices, and push notifications when offline. Assume 100 million daily active users, each sending 40 messages a day. Use the framework, then compare.

Text
1. Clarifying questions:
2. Functional requirements:
3. Non-functional requirements:
4. Estimates (messages/s, storage, connections):
5. API (WebSocket messages + REST):
6. Data model:
7. High-level design:
8. Deep dives (routing, ordering, groups, offline, presence):
9. Trade-offs and bottlenecks:

Summary

  • Clients keep persistent WebSocket connections to gateway servers; a registry records which gateway holds each user's connection.
  • The chat service stores each message durably before acknowledging, then routes it to online recipients or triggers a push notification.
  • Order messages per conversation with a server-assigned sequence number, and deduplicate with client-generated message IDs.
  • Store messages partitioned by conversation and sorted by sequence (e.g. Cassandra); devices sync from their last seen sequence.
  • Group chats fan out per member for small groups; presence uses heartbeats with expiry and limited fan-out.