Designing a real-time messaging application like WhatsApp, Facebook Messenger, or Telegram is one of the most common and comprehensive system design interview questions. It tests your understanding of stateful services, real-time communication protocols, database scaling, and distributed system synchronization.
In this article, we will design a highly scalable chat system. While actual WhatsApp famously deletes messages from its servers once delivered (acting purely as a store-and-forward mechanism) and uses Erlang for massive concurrency, we will design a more standard, persistent chat architecture (similar to Telegram or Facebook Messenger) as this is what interviewers typically expect unless they specifically ask for the ephemeral model.
Requirements (functional and non-functional)
Always start your interview by clarifying the scope. A chat application can have hundreds of features, but you only have 45 minutes.
Functional Requirements
- 1-on-1 Messaging: Users should be able to send and receive text messages in real-time.
- Delivery Receipts: Users should see the status of their messages (Sent, Delivered, Read).
- Online Presence: Users should be able to see if their contacts are online or their "Last Seen" time.
- Message History: Users should be able to access their chat history across multiple devices.
(Out of scope for the core design: Group chats, media sharing, end-to-end encryption, voice/video calls. We will touch on these at the end).
Non-functional Requirements
- Low Latency: Messages must be delivered with minimal delay (sub-500ms).
- High Availability: The system must be highly available. However, for real-time messaging, we strongly favor consistency in message ordering.
- High Scalability: The system should support 1 billion Daily Active Users (DAU).
- Durability: Messages should not be lost once sent.
Capacity estimates
Let's crunch some numbers to understand the scale of the system. We will use concrete assumptions.
- Users: 1 Billion Daily Active Users (DAU).
- Messages per user: Let's assume an average user sends 50 messages a day.
- Total Messages: 1 Billion * 50 = 50 Billion messages per day.
Throughput (QPS):
- 50 Billion / 86,400 seconds ≈ 600,000 requests per second (QPS) on average.
- Peak QPS is usually 2x to 3x the average, so expect around 1.5 Million QPS at peak.
Storage:
- Assume each message is about 100 bytes (text + metadata).
- 50 Billion messages * 100 bytes = 5 Terabytes (TB) per day.
- Over 5 years: 5 TB * 365 * 5 ≈ 9 Petabytes (PB) of message data.
Bandwidth:
- 5 TB / 86,400 seconds ≈ 58 MB/second ingress (and roughly the same for egress).
Connection State Memory:
- To push messages in real-time, we need active connections (WebSockets). If 500 Million users are online concurrently, and each connection takes roughly 10 KB of memory on the server:
- 500,000,000 * 10 KB = 5 Terabytes of RAM distributed across our chat servers.
API design
For a real-time chat application, traditional HTTP request-response is not sufficient because the server needs to push data to the client when a new message arrives.
Protocol Choice
| Protocol | Description | Pros | Cons |
|---|---|---|---|
| HTTP Long Polling | Client requests data, server holds request open until data is available. | Easy to implement, works everywhere. | High overhead (headers), connection churn. |
| Server-Sent Events (SSE) | Persistent one-way connection from server to client. | Native browser support, auto-reconnect. | Unidirectional (Server -> Client only). |
| WebSockets | Persistent, full-duplex, bidirectional TCP connection. | Low latency, minimal overhead, bidirectional. | Requires stateful server management. |
We will use WebSockets for the chat functionality, as it provides the lowest latency for bidirectional communication. For standard operations (login, fetching history, updating profile), we will use standard REST APIs.
WebSocket Payload Examples
Instead of HTTP endpoints, our WebSocket connection will pass JSON payloads.
1. Sending a message (Client -> Server):
{
"action": "send_message",
"payload": {
"temp_id": "client-uuid-1234",
"receiver_id": "user_987",
"content": "Hey, how are you?"
}
}2. Server Acknowledgment (Server -> Client):
{
"action": "message_ack",
"payload": {
"temp_id": "client-uuid-1234",
"message_id": "server-snowflake-5678",
"timestamp": 1690000000
}
}3. Receiving a message (Server -> Client):
{
"action": "receive_message",
"payload": {
"message_id": "server-snowflake-5678",
"sender_id": "user_123",
"content": "Hey, how are you?",
"timestamp": 1690000000
}
}Data model
Choosing the right database is critical. We have a massive write-heavy system (1.5M peak QPS) and a massive read-heavy system (users opening the app and fetching history).
We need a database that handles high write throughput, scales horizontally, and provides fast range queries (to load a chunk of chat history). A Wide-Column NoSQL store like Apache Cassandra or HBase is the industry standard for this use case (Discord and Facebook Messenger use similar architectures).
1. Messages Table (Cassandra)
We need to query messages by a specific chat (between User A and User B) and order them by time.
- Table:
messages - Partition Key:
chat_id(A unique hash of User A and User B's IDs, e.g.,hash(min(A,B) + max(A,B))). This ensures all messages for a specific 1-on-1 chat land on the same database node. - Clustering Key:
message_id(A time-sortable identifier like a Snowflake ID or TimeUUID). This sorts the messages chronologically on disk. - Columns:
sender_id,content,status(sent, delivered, read),created_at.
2. User Connections Table (Redis)
To route a message, the system must know which specific Chat Server holds the recipient's WebSocket connection. This data is highly ephemeral and read/written constantly.
- Key:
user_id - Value:
chat_server_id(e.g.,server-ws-042) - Data Store: Redis Cluster (Key-Value store).
High-level architecture
Here is the high-level flow of how components interact when users send messages.
Component Breakdown
- Load Balancer: Balances incoming WebSocket connections. It must support long-lived connections and ideally route users to servers geographically close to them.
- Chat Servers (WebSocket Servers): Stateful servers holding millions of open WebSocket connections. They receive messages, look up recipients, and push messages out.
- Redis Connection Cache: A fast, in-memory store mapping
user_id->chat_server_id. - Message Bus (Kafka): Used to decouple the sending server from the receiving server. If User A is on Server 1 and User B is on Server 2, Server 1 drops the message into a Kafka topic that Server 2 is listening to.
- Cassandra DB: The persistent storage for all chat history.
- Push Notification Service: If User B is not connected to any WebSocket server (offline), the system triggers an Apple Push Notification (APNs) or Firebase Cloud Message (FCM) to wake up their phone.
Deep dives
Let's explore the three hardest parts of this system: the real-time message flow, delivery receipts, and online presence.
1. Real-time Message Flow & Connection Management
Handling millions of concurrent connections (the C10M problem) requires careful server configuration. Each Chat Server is a stateful machine.
Step-by-step flow when User A sends a message to User B:
- User A's app sends a message payload over their active WebSocket to Chat Server 1.
- Chat Server 1 generates a unique, time-sortable
message_id(using a Snowflake ID generator) and immediately sends an ACK back to User A (One tick: Sent). - Chat Server 1 asynchronously writes the message to Cassandra.
- Chat Server 1 queries Redis for User B's connection status.
- Case A (Offline): Redis returns null. Chat Server 1 sends a payload to the Push Notification Service.
- Case B (Online): Redis returns
Chat Server 2.
- Chat Server 1 cannot talk directly to User B. It must route the message to Chat Server 2. It does this via an internal RPC call or by publishing to a Kafka topic partitioned by
server_id. - Chat Server 2 picks up the message and pushes it down the WebSocket to User B.
Below is a simplified representation of how a Chat Server might route an incoming message internally.
class MessageRouter:
def __init__(self, redis_client, kafka_producer, db_client):
self.redis = redis_client
self.kafka = kafka_producer
self.db = db_client
def handle_incoming_message(self, sender_id, receiver_id, content):
# 1. Save to DB
msg_id = generate_snowflake_id()
self.db.save_message(msg_id, sender_id, receiver_id, content)
# 2. Find recipient
target_server = self.redis.get(f"user_conn:{receiver_id}")
if target_server:
# 3a. Route to the server holding the connection
payload = {"msg_id": msg_id, "to": receiver_id, "content": content}
self.kafka.publish(topic=target_server, message=payload)
else:
# 3b. User is offline, trigger push notification
trigger_push_notification(receiver_id, sender_id, content)
return msg_id2. Delivery Receipts (Sent, Delivered, Read)
Delivery receipts are essentially just special system messages routed exactly like text messages, but they update the UI and the database state instead of showing a chat bubble.
- Sent (One Tick): The moment Chat Server 1 successfully writes the message to Cassandra, it sends an ACK back to User A.
- Delivered (Two Ticks): When User B's device receives the message payload via WebSocket, the device immediately automatically replies with a
message_deliveredreceipt. This receipt flows from User B -> Chat Server 2 -> Kafka -> Chat Server 1 -> User A. The DB is also updated asynchronously to mark the status as 'delivered'. - Read (Blue Ticks): When User B actually opens the chat screen containing the message, the app fires a
message_readreceipt. This follows the exact same path to reach User A.
3. Online Presence (Last Seen)
Building a presence system for 1 billion users is notoriously difficult. If every user sends a heartbeat every 5 seconds, that's 200 Million QPS just for presence! We must optimize this.
Optimization 1: Heartbeat Batching Instead of the client sending a heartbeat every 5 seconds, the client sends it every 30 seconds. When the WebSocket connects, the user is marked "Online" in Redis with a TTL (Time-To-Live) of 40 seconds. If the heartbeat is missed, the TTL expires, and the user drops offline.
Optimization 2: Fan-out on Read (Lazy Loading) Do we broadcast User A's online status to all of User A's contacts? No, that's an massive fan-out problem. Instead, we use a pull-based approach combined with a targeted push:
- When User B opens their app, they fetch the presence status of only the users currently visible on their screen (e.g., the top 10 chats).
- If User B opens a specific chat with User A, User B subscribes to User A's presence changes. Now, only while that chat is open, any heartbeat from User A is routed to User B.
Bottlenecks and trade-offs
1. The C10M Problem (Connection Limits)
A single Linux server can traditionally handle 10,000 to 65,000 connections due to port exhaustion. To scale a single Chat Server to millions of WebSockets (C10M), you must tune the OS:
- Increase file descriptor limits (
fs.file-max). - Use efficient I/O event notification mechanisms like
epoll(Linux) orkqueue(FreeBSD). - Bypass standard OS networking stacks using technologies like DPDK if extreme optimization is needed.
2. Ephemeral vs Persistent Storage
In this design, we used Cassandra to store history forever.
- Trade-off: Storing 9 PB of data is incredibly expensive.
- WhatsApp's approach: WhatsApp stores messages on the server only until they are delivered. Once delivered, they are deleted from the server and live only on the users' devices (and in their Google Drive/iCloud backups). This drastically reduces server storage costs but makes multi-device sync much harder (which is why WhatsApp Web historically required your phone to be online).
3. Load Balancer Connection Draining
Because WebSockets are long-lived, standard Round Robin load balancing can lead to uneven load over time (some servers might end up with users who stay connected for days, while others have users who disconnect quickly).
- Solution: Use "Least Connections" routing at the Load Balancer level, and implement server-side connection culling (forcing clients to reconnect periodically with a random jitter) to rebalance the cluster during deployments.
Questions an interviewer will ask next
1. How would you handle group chats?
Answer: Group chats introduce a "fan-out" problem. If a group has 200 members, one incoming message must be fanned out to 199 recipients. I would introduce a Group Message Handler service. When a message hits this service, it queries the group members, checks their routing info in Redis, and publishes 199 individual tasks to Kafka to be routed to the respective Chat Servers.
2. How do you support multi-device sync (e.g., phone and web app simultaneously)?
Answer: The Redis connection cache would map a user_id to a list of active sessions, e.g., user_123 -> [server-ws-1, server-ws-5]. When routing a message or a delivery receipt, the Chat Server iterates through all active sessions and pushes the payload to all of them.
3. How does End-to-End Encryption (E2EE) fit into this?
Answer: E2EE (like the Signal Protocol used by WhatsApp) operates entirely on the client side. The server never sees plaintext. The sender fetches the receiver's public key from a Key Server, encrypts the message, and sends the ciphertext. Our Chat Servers and Cassandra DB only route and store encrypted blobs. Delivery receipts work exactly the same, as they just reference the message_id.
4. How would you handle media (images/videos)? Answer: Media is too large for WebSockets. The client would upload the image to an Object Store (like Amazon S3) via a standard HTTP POST request. S3 returns a URL. The client then sends a standard chat message containing the S3 URL (and perhaps a tiny blurred thumbnail) over the WebSocket. The receiver gets the URL and downloads the image via a CDN.