Design a Real-Time Chat System: WebSockets, Presence Heartbeats & Message Sync
Why Chat Breaks Traditional Stateless HTTP
Real-Time Chat System Architecture
1. Protocol Choice: HTTP Polling vs. SSE vs. WebSockets
- Long Polling: Client opens HTTP request and waits; server holds connection until a message arrives, then closes and client immediately reconnects. Wastes HTTP overhead when idle.
- Server-Sent Events (SSE): Great for server-to-client streams (like LLM token streaming), unidirectional only.
- WebSockets (
wss://): Full-duplex, bidirectional persistent TCP channel after an initial HTTP Upgrade handshake. A single tuned server (Go/Elixir/Rust/C++) easily holds 500K+ open WebSocket connections.
2. Routing Messages Across Stateful Chat Servers
Chat Server 1) sends a message to User B (connected to Chat Server 3), how does Server 1 locate Server 3?- Service Discovery (ZooKeeper / etcd): Assigns each client the best regional WebSocket server at login (
Presence/Session map: user_id -> chat_server_ip). - Message Sync & Pub/Sub Relay:
- User A sends payload
{ msg_id (Snowflake), channel_id, text }toChat Server 1. Chat Server 1persists the message to the Message KV Store and publishes it to a Message Sync Queue / Pub-Sub (Kafka or Redis Pub/Sub).- If User B is online (
Server 3),Server 3pushes the frame immediately over User B's open WebSocket. - If User B is offline, the notification pipeline routes to APNs / FCM Push.
- User A sends payload
3. Storing Billions of Messages: Why Wide-Column NoSQL Wins
- Access Pattern: Users almost exclusively read recent messages by
channel_idor search exact messages, never cross-table SQL JOINs. - Database Choice: Apache Cassandra or HBase (like Discord/Slack), partitioned by
channel_idand clustered bymessage_id(a Snowflake 64-bit ID!).- Partition key
channel_idkeeps an entire conversation localized; clustering keymessage_idenforces chronological ordering without locking across servers!
- Partition key
4. Multi-Device Sync & Online Presence Indicators
Multi-Device Sync (cur_max_message_id)
cur_max_message_id locally. On reconnect, it requests all messages in channel_id with message_id > cur_max_message_id from the KV store—guaranteeing zero missed messages.Taming Presence Fanout Storms
"User logged in" immediately on brief mobile network drops!- Clients send lightweight heartbeat pings every 5 seconds; if no heartbeat arrives within 30 seconds, mark offline.
- Use Pub/Sub between a user's presence channel and online friends—for massive group servers (100K+ Discord members), fetch presence lazily on scroll instead of broadcasting every online/offline flip to 100K sockets.