Design WhatsApp or Messaging Service
Difficulty: MEDIUMCategory: HLDFrequency: 1Asked On 2022-04-28
Problem Statement
Design a scalable, highly available, and real-time messaging system similar to WhatsApp, where users can send and receive messages (text, images, videos, files) across devices. The system should support one-to-one chats, group messaging, notifications, and message synchronization across devices.
Functional Requirements
1.User Management
•Register/Login with phone number or username.
•Show online/offline and typing status.
2.Messaging
•Send and receive text messages, media (images, videos, voice notes), documents.
•Support message delivery states (sent, delivered, read).
•End-to-end encryption of messages.
•Synchronization across multiple devices.
3.Group Messaging
•Create groups, add/remove participants.
•Support group notifications and mentions.
4.Notifications
•Push notifications for new messages.
•Typing indicator & message seen status.
5.Search & History
•Retrieve past conversations (persistent storage).
•Support pagination for chat history.
6.Scalability & Reliability
•Handle millions of concurrent connections.
•Guarantee low latency message delivery.
•Ensure message durability in case of crashes.
Non-Functional Requirements
•Low Latency → Messages delivered in <200ms.
•Scalability → Support millions of concurrent users globally.
•High Availability → No downtime even during peak loads.
•Data Consistency → Exactly-once message delivery, no duplicates.
•Security → End-to-end encryption (E2EE).
•Fault Tolerance → Recover from server failures.
Design Considerations
•Message Queues
•Use Kafka/RabbitMQ or custom queues for reliable delivery.
•Support retry mechanism for failed deliveries.
•Storage
•Hot storage (Redis/Memcached) for recent messages.
•Cold storage (Cassandra/MongoDB) for older chat history.
•TTL-based cleanup for temporary messages (like WhatsApp Status).
•APIs
•sendMessage(senderId, receiverId, msg)
•receiveMessage(userId)
•createGroup(users)
•getChatHistory(userId, chatId, cursor)
•Architecture Components
•Client App → User sends/receives messages.
•Load Balancer → Routes requests to nearest chat server.
•Chat Service → Handles message routing, delivery, storage.
•Group Service → Manages group metadata and broadcasts.
•Notification Service → Push notifications, typing indicators.
•Message Store → Persistent DB for chat history.
•Cache Layer (Redis) → Fast retrieval of recent chats.
•Concurrency & Delivery Guarantees
•Use acknowledgments (ACKs) for sent, delivered, and read status.
•Idempotent message IDs to avoid duplicates.
•Quorum reads/writes in distributed DB for consistency.
•Performance Enhancements
•Sharding users by region for scalability.
•CDN for media files (images, videos, documents).
•WebSockets for persistent real-time connections.