Home Interview Design WhatsApp: System Design Interview Guide
Advanced 3 min · July 13, 2026

Design WhatsApp: System Design Interview Guide

Master WhatsApp system design for interviews.

N
Naren Founder & Principal Engineer

20+ years shipping production code across the stack, with years spent interviewing engineers. Notes here come from systems that actually shipped.

Follow
Production
production tested
July 13, 2026
last updated
2,165
articles · all by Naren
Before you start⏱ 15-20 min read
  • Basic understanding of distributed systems (CAP theorem, consistency models).
  • Familiarity with WebSocket, REST, and message queues (Kafka).
  • Knowledge of NoSQL databases (Cassandra) and caching (Redis).
  • Understanding of load balancing and horizontal scaling.
 ● Production Incident 🔎 Debug Guide ⚙ Triage Commands
Quick Answer
  • WhatsApp is a real-time messaging app requiring high availability, low latency, and end-to-end encryption.
  • Core components: chat servers, presence service, message store, media storage, and notification system.
  • Key challenges: handling millions of concurrent connections, message ordering, and delivery guarantees.
  • Use WebSocket for real-time communication, Cassandra for message storage, and CDN for media.
  • Scale with horizontal sharding, load balancing, and asynchronous processing.
✦ Definition~90s read
What is Design WhatsApp?

Design WhatsApp is a system design interview task where you architect a real-time messaging application capable of handling billions of users with low latency, high availability, and end-to-end encryption.

Imagine a postal system where letters are delivered instantly.
Plain-English First

Imagine a postal system where letters are delivered instantly. WhatsApp is like a super-efficient post office that handles billions of letters every day. Each letter is encrypted so only the sender and receiver can read it. The system has many post offices (servers) around the world to ensure fast delivery. If one post office is busy, another takes over. Messages are stored temporarily until delivered, and you can see when someone is typing or online, like a live tracking system for letters.

⚙ Browser compatibility
Latest versions — ✓ supported
ChromeFirefoxSafariEdge

WhatsApp is one of the most popular messaging apps globally, handling over 100 billion messages daily. Designing a system like WhatsApp is a classic system design interview question that tests your ability to build a real-time, scalable, and fault-tolerant application. In this guide, we'll walk through the key components, trade-offs, and interview strategies to ace this question.

Imagine you're asked: 'Design WhatsApp' in a 45-minute interview. The interviewer expects you to cover functional requirements (one-on-one chat, group chat, media sharing, online presence) and non-functional requirements (low latency, high availability, consistency, security). You'll need to propose a high-level architecture, dive into data models, discuss scaling strategies, and handle edge cases like offline messages or message ordering.

We'll start with requirements, then move to a deep dive on each component: WebSocket servers for real-time communication, Cassandra for message storage, Redis for presence, and CDN for media. We'll also cover end-to-end encryption, message delivery guarantees (at-least-once), and how to handle billions of users. By the end, you'll have a solid blueprint to impress any interviewer.

1. Requirements and Goals

Start by clarifying functional and non-functional requirements. Functional: send/receive messages (text, image, video), group chat (up to 256 users), online presence, delivery receipts (sent, delivered, read), media sharing, end-to-end encryption. Non-functional: low latency (<100ms for message delivery), high availability (99.999%), scalability (billions of users), consistency (messages ordered per conversation), security (encryption). Also consider offline messaging, multi-device support, and voice/video calls (optional).

💡Interview Tip
📊 Production Insight
In production, WhatsApp supports 2 billion users; requirements evolve, so design for extensibility.
🎯 Key Takeaway
Define clear functional and non-functional requirements before diving into design.

2. High-Level Architecture

The architecture consists of clients (mobile/web), load balancers, chat servers (WebSocket), presence servers (Redis), message queues (Kafka), databases (Cassandra for messages, MySQL for user metadata), media storage (S3/CDN), and notification servers (APNS/FCM). Clients connect via WebSocket to chat servers for real-time messaging. Messages are persisted in Cassandra for durability. Presence is tracked in Redis with TTL. Media is uploaded to S3 and served via CDN. Notifications are sent via push when app is backgrounded.

🔥Why WebSocket?
📊 Production Insight
WhatsApp uses Erlang for chat servers (high concurrency) and custom protocol (FunXMPP) based on XMPP.
🎯 Key Takeaway
Use WebSocket for real-time, Kafka for async processing, Cassandra for write-heavy message storage.

3. Data Model

Key entities: User (userId, phoneNumber, displayName, avatarUrl), Message (messageId, conversationId, senderId, content, timestamp, type), Conversation (conversationId, participants, lastMessage, lastTimestamp), Media (mediaId, url, type, size). For one-on-one chat, conversationId = sorted(userId1, userId2) to ensure uniqueness. For group chat, conversationId is a UUID. Messages are stored in Cassandra with partition key = conversationId and clustering key = timestamp (for ordering). Example schema:

CREATE TABLE messages ( conversation_id text, message_id timeuuid, sender_id text, content text, media_url text, created_at timestamp, PRIMARY KEY (conversation_id, created_at, message_id) ) WITH CLUSTERING ORDER BY (created_at DESC);

schema.cqlSQL
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
CREATE TABLE messages (
  conversation_id text,
  message_id timeuuid,
  sender_id text,
  content text,
  media_url text,
  created_at timestamp,
  PRIMARY KEY (conversation_id, created_at, message_id)
) WITH CLUSTERING ORDER BY (created_at DESC);

CREATE TABLE users (
  user_id text PRIMARY KEY,
  phone_number text,
  display_name text,
  avatar_url text
);

CREATE TABLE conversations (
  conversation_id text PRIMARY KEY,
  participants list<text>,
  last_message text,
  last_timestamp timestamp
);
📊 Production Insight
WhatsApp uses custom database 'Mnesia' for some metadata, but Cassandra is a common interview choice.
🎯 Key Takeaway
Cassandra's wide-row model is perfect for storing messages ordered by time per conversation.

4. Real-Time Messaging Flow

When user A sends a message to user B: 1) Client A sends message via WebSocket to chat server. 2) Chat server assigns a unique message ID (timeUUID) and stores message in Cassandra. 3) Chat server pushes message to user B's WebSocket if B is online. 4) If B is offline, message is stored and later delivered via push notification. 5) Chat server sends acknowledgment back to A (sent receipt). 6) When B receives message, client sends delivery receipt. 7) When B reads message, read receipt is sent. All receipts are stored as special message types. For group chat, the server fans out messages to all group members (up to 256). For large groups, use multicast or separate queues.

message_flow.pyPYTHON
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import asyncio
import uuid

class ChatServer:
    def __init__(self, db, queue):
        self.db = db
        self.queue = queue

    async def handle_message(self, sender_id, conversation_id, content):
        message_id = uuid.uuid1()
        message = {
            'message_id': str(message_id),
            'sender_id': sender_id,
            'conversation_id': conversation_id,
            'content': content,
            'timestamp': int(time.time())
        }
        # Persist to Cassandra
        await self.db.insert_message(message)
        # Enqueue for delivery
        await self.queue.enqueue(message)
        # Send acknowledgment back to sender
        await self.send_ack(sender_id, message_id)

    async def deliver_message(self, message):
        # Get online users in conversation
        online_users = await self.presence.get_online_users(message['conversation_id'])
        for user_id in online_users:
            if user_id != message['sender_id']:
                await self.ws_send(user_id, message)
⚠ Delivery Guarantees
📊 Production Insight
WhatsApp uses a custom queue system for fan-out; Kafka is a good interview alternative.
🎯 Key Takeaway
Messages are persisted before delivery to ensure durability; receipts provide feedback.

5. Presence and Online Status

Presence is tracked using Redis with a key 'presence:{userId}' and TTL (e.g., 30 seconds). Clients send periodic heartbeats (every 10 seconds) to refresh TTL. When a user connects, set presence to 'online'. When they disconnect (WebSocket close), set to 'last seen' timestamp. For privacy, users can configure who sees their status. Presence updates are broadcast to friends' online sessions via WebSocket. To scale, use Redis Cluster with sharding by userId. For millions of users, use Redis with read replicas and local caching on chat servers.

presence.pyPYTHON
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import redis
import time

class PresenceService:
    def __init__(self):
        self.redis = redis.Redis(host='localhost', port=6379, decode_responses=True)

    def user_online(self, user_id):
        self.redis.setex(f'presence:{user_id}', 30, 'online')

    def user_offline(self, user_id):
        self.redis.set(f'presence:{user_id}', f'last_seen:{int(time.time())}')

    def is_online(self, user_id):
        return self.redis.get(f'presence:{user_id}') == 'online'

    def get_last_seen(self, user_id):
        val = self.redis.get(f'presence:{user_id}')
        if val and val.startswith('last_seen'):
            return int(val.split(':')[1])
        return None
💡Scaling Presence
📊 Production Insight
WhatsApp uses a custom presence server; they batch presence updates to reduce load.
🎯 Key Takeaway
Redis with TTL is simple and fast for presence; heartbeats prevent stale data.

6. Media Sharing and Storage

Media (images, videos, documents) is uploaded directly to a CDN or blob store (e.g., S3) from the client. The client gets a pre-signed URL for upload. After upload, the media URL is sent as a message. For thumbnails, generate on the server side. Use CDN for fast global delivery. For large files, support chunked upload and resume. Media is encrypted at rest and in transit. To reduce storage costs, deduplicate media using hash (SHA256). For interview, mention using S3 with CloudFront CDN.

🔥Pre-signed URLs
📊 Production Insight
WhatsApp compresses media heavily; they use in-house CDN for cost efficiency.
🎯 Key Takeaway
Offload media to CDN; use pre-signed URLs for secure uploads.

7. End-to-End Encryption

WhatsApp uses the Signal Protocol for end-to-end encryption. Each user has a public/private key pair. When two users chat, they exchange public keys and establish a session key using the Double Ratchet algorithm. Messages are encrypted with AES-256. The server never has access to plaintext. For group chats, each message is encrypted per recipient (sender keys). In an interview, you don't need to implement the protocol, but explain the concept: keys are stored on client, server relays encrypted messages. Mention key distribution and verification (safety numbers).

⚠ Key Management
📊 Production Insight
WhatsApp's encryption is open-source; they use Curve25519, AES-256, and HMAC-SHA256.
🎯 Key Takeaway
End-to-end encryption ensures privacy; server only sees ciphertext.

8. Scaling and Performance

To scale to billions of users: 1) Horizontal scaling of chat servers with load balancers (e.g., HAProxy). 2) Shard databases: Cassandra partitions by conversationId; use consistent hashing. 3) Use CDN for media. 4) Asynchronous processing with Kafka for message delivery, presence updates, and analytics. 5) Caching: Redis for presence and session data; local caches for user metadata. 6) Geo-distributed data centers to reduce latency. 7) Use connection pooling and multiplexing on WebSocket. 8) For group chat fan-out, use a message broker with topic-based routing.

💡Database Sharding
📊 Production Insight
WhatsApp runs on Erlang/OTP, which provides lightweight processes for millions of concurrent connections.
🎯 Key Takeaway
Scale horizontally, use async processing, and geo-distribute to handle billions of users.

9. Fault Tolerance and Reliability

Ensure no message loss: 1) Persist messages before acknowledging. 2) Use replication in Cassandra (RF=3). 3) Kafka provides durability with replication. 4) WebSocket reconnection with exponential backoff. 5) Idempotent message delivery: clients deduplicate using messageId. 6) Graceful degradation: if database is slow, queue messages and deliver later. 7) Circuit breakers for external services (e.g., push notifications). 8) Regular backups and disaster recovery across regions.

🔥At-Least-Once Delivery
📊 Production Insight
WhatsApp uses a custom 'Offline Messages' system that stores messages for 30 days on server.
🎯 Key Takeaway
Design for failure: replicate data, use retries, and deduplicate at client.

10. Interview Tips and Common Pitfalls

Common mistakes: 1) Not clarifying requirements (e.g., group chat size). 2) Ignoring offline messaging. 3) Overcomplicating the design (e.g., microservices for everything). 4) Forgetting about encryption. 5) Not discussing trade-offs (e.g., consistency vs availability). Tips: 1) Start with a simple design and iterate. 2) Use whiteboard to draw architecture. 3) Mention numbers (e.g., 100B messages/day). 4) Discuss bottlenecks and how to address them. 5) Show you can think about edge cases (e.g., user blocking, message recall).

💡Interview Strategy
📊 Production Insight
WhatsApp's architecture is a result of years of evolution; don't be afraid to mention real-world constraints.
🎯 Key Takeaway
Be structured, discuss trade-offs, and show depth in one or two components.
● Production incidentPOST-MORTEMseverity: high

WhatsApp Outage: The DNS Hijack That Took Down Messaging

Symptom
Users worldwide could not send or receive messages; app showed 'connecting' indefinitely.
Assumption
Engineers assumed a server overload or database failure due to traffic spike.
Root cause
A BGP route leak from a small ISP caused traffic to be rerouted through a congested network, making WhatsApp servers unreachable.
Fix
ISPs updated BGP filters; WhatsApp added redundant network paths and monitoring for BGP anomalies.
Key lesson
  • Network infrastructure failures can cascade globally; design for network diversity.
  • Monitor BGP routes and have automated failover mechanisms.
  • Use multiple ISPs and peering agreements to avoid single points of failure.
  • Implement graceful degradation: show cached messages when servers are unreachable.
  • Conduct regular chaos engineering to test network resilience.
Production debug guideSymptom to Action4 entries
Symptom · 01
Messages not delivered
Fix
Check WebSocket connection status; verify message queue backlog in Kafka; inspect Cassandra for missing rows.
Symptom · 02
High latency in message delivery
Fix
Profile WebSocket server CPU; check network latency between data centers; optimize Cassandra queries with proper indexes.
Symptom · 03
User presence shows offline incorrectly
Fix
Verify Redis presence keys TTL; check WebSocket heartbeat interval; ensure load balancer session affinity.
Symptom · 04
Media upload fails
Fix
Check CDN upload endpoint; verify media size limits; inspect blob store (S3) permissions.
★ Quick Debug Cheat SheetCommon symptoms and immediate actions for WhatsApp system issues.
Message not sent
Immediate action
Check WebSocket connection
Commands
ping websocket-server:443
tail -f /var/log/chat-server/error.log
Fix now
Restart WebSocket server or check firewall rules.
High message latency+
Immediate action
Check Cassandra read latency
Commands
nodetool cfstats messages
top -H -p $(pgrep cassandra)
Fix now
Add read replicas or optimize queries.
User presence stale+
Immediate action
Check Redis TTL
Commands
redis-cli TTL user:presence:123
redis-cli INFO stats
Fix now
Increase heartbeat frequency or extend TTL.
Media upload timeout+
Immediate action
Check CDN status
Commands
curl -I https://cdn.whatsapp.net/upload
aws s3api head-bucket --bucket whatsapp-media
Fix now
Switch to backup CDN or increase timeout.
FeatureWhatsAppTelegramSignal
End-to-End EncryptionYes (default)Optional (secret chats)Yes (default)
Group Chat Size256200,0001000
Message StorageServer stores for 30 daysUnlimited cloud storageMinimal server storage
Open SourcePartially (client)Partially (server)Fully open source
ProtocolCustom (FunXMPP)MTProtoSignal Protocol
⚙ Quick Reference
3 commands from this guide
FileCommand / CodePurpose
schema.cqlCREATE TABLE messages (3. Data Model
message_flow.pyclass ChatServer:4. Real-Time Messaging Flow
presence.pyclass PresenceService:5. Presence and Online Status

Key takeaways

1
Design for real-time, low-latency communication using WebSocket and async processing.
2
Use Cassandra for message storage due to its write-optimized, scalable nature.
3
Implement end-to-end encryption to ensure privacy and trust.
4
Scale horizontally with load balancers, sharding, and geo-distribution.
5
Handle offline messages and delivery guarantees with persistent storage and retries.

Common mistakes to avoid

5 patterns
×

Not considering offline messaging

×

Using SQL database for messages

×

Ignoring delivery receipts

×

Overcomplicating with microservices

×

Forgetting about security and encryption

INTERVIEW PREP · PRACTICE MODE

Interview Questions on This Topic

Q01SENIOR
Design WhatsApp's messaging system. How would you ensure messages are de...
Q02SENIOR
How would you design the presence feature for 1 billion users?
Q03SENIOR
How would you handle media uploads in WhatsApp?
Q04SENIOR
Explain how WhatsApp's end-to-end encryption works at a high level.
Q05SENIOR
How would you scale WhatsApp's chat servers to handle 100 million concur...
Q01 of 05SENIOR

Design WhatsApp's messaging system. How would you ensure messages are delivered exactly once?

ANSWER
Exactly-once delivery is hard; WhatsApp uses at-least-once with dedup. Use message IDs and client-side dedup. For idempotency, store processed message IDs in a set. Trade-off: storage vs accuracy.
FAQ · 5 QUESTIONS

Frequently Asked Questions

01
How does WhatsApp handle message ordering?
02
What database does WhatsApp use?
03
How does WhatsApp achieve high availability?
04
How does WhatsApp handle group chat scalability?
05
How does WhatsApp ensure end-to-end encryption?
N
Naren Founder & Principal Engineer

20+ years shipping production code across the stack, with years spent interviewing engineers. Notes here come from systems that actually shipped.

Follow
Verified
production tested
July 13, 2026
last updated
2,165
articles · all by Naren
🔥

That's System Design Interview. Mark it forged?

3 min read · try the examples if you haven't

Previous
Design a Leaderboard System
8 / 12 · System Design Interview
Next
Design Netflix: System Design Interview