Case Study: Chat System
Design a WhatsApp/Slack-style messenger — persistent WebSocket connections, message routing across servers, storage, ordering, delivery receipts, presence, group chats and push notifications.
1. Requirements
Functional: one-to-one and group chat (up to ~500 members), online presence, delivery/read receipts, message history across devices, push notifications when offline, media attachments.
Non-functional: low latency (under ~200 ms delivery), messages never lost, ordered per conversation, high availability.
2. Estimates
- 500M daily active users × 40 messages/day = 20B messages/day ≈ 230k messages/s average.
- ~100 bytes per message → 2 TB/day of text (before replication).
- Tens of millions of concurrent connections: at ~100k–1M per server, that's hundreds of connection servers.
3. Connections
Clients keep a persistent WebSocket to a chat (gateway) server, so the server can push messages instantly (WebSockets & real-time). Gateway servers are stateful (they hold connections) but hold no durable data.
4. High-level design
5. Sending a message
- Persist before acking: once Alice sees "sent", the message is durable.
- The client's client_msg_id makes retries idempotent (no duplicates if Alice resends after a timeout).
- If Bob is offline (not in the registry), send a push notification; he fetches missed messages on reconnect.
6. Routing between gateways
Alice and Bob are connected to different gateways. A session registry (Redis: user_id → gateway_id, with heartbeats and TTLs) tells the chat service where to deliver. Alternatives: a pub/sub channel per user (Redis pub/sub, or Kafka keyed by user) that each gateway subscribes to for its connected users.
7. Storage and ordering
Access pattern: "latest N messages of conversation X, then page backwards". This suits a wide-column store:
-- Cassandra
CREATE TABLE messages (
conversation_id bigint,
message_id bigint, -- time-ordered (Snowflake-style)
sender_id bigint,
body text,
PRIMARY KEY ((conversation_id), message_id)
) WITH CLUSTERING ORDER BY (message_id DESC);- Ordering: wall clocks on different servers disagree, so assign a per-conversation sequence (or a time-ordered ID from a single owner of the conversation). Clients sort by it and can detect gaps.
- Very large conversations may need bucketing by time in the partition key so partitions don't grow unbounded.
8. Multi-device sync
Each device tracks the last sequence number it has seen per conversation. On reconnect it asks "give me everything after seq 1042". This also covers offline periods.
9. Group chats
For small groups, fan-out on write: deliver each message to every member's connection (and their inboxes). For very large channels (Slack/Discord-style), store once and let clients pull, or fan out only to currently connected members.
10. Presence
Clients send heartbeats every ~30 s; a presence service marks users online with a TTL in Redis. Publish presence changes only to interested users (contacts with the chat open), and debounce flapping connections. Presence is "best effort" — slight staleness is fine.
11. Other concerns
- Media: upload directly to object storage with a pre-signed URL; send only the URL in the message; serve via CDN.
- End-to-end encryption (Signal protocol): servers relay ciphertext only; this limits server-side search.
- Reconnect storms: when a gateway dies, its clients reconnect elsewhere with jittered backoff.
- Read receipts are just small messages flowing the other way.
- Persistent WebSockets to stateless-data gateway servers; a registry maps users to gateways.
- Persist before ack; client message IDs make sends idempotent.
- Wide-column store partitioned by conversation, ordered by a per-conversation sequence.
- Devices sync by "everything after my last sequence"; push notifications for offline users.
- Fan-out on write for small groups; presence via heartbeats with TTL.