Design a Scalable Chat Application

Difficulty: MEDIUMCategory: HLDFrequency: 1Asked On 2025-04-08

Problem Statement

Design a chat application that allows users to communicate via 1:1 and group chats, supporting real-time messaging via WebSockets, offline message storage, and the ability to scale gracefully under a sudden surge of messages (e.g., viral group or breaking news scenarios).


🎯 Functional Requirements:

1️⃣ 1:1 Chat

•Users can send and receive messages instantly.
•Chat history is preserved and synchronized across devices.
•Message status: Sent, Delivered, Read.

👥 Group Chat

•Multiple users per group (e.g., 100–500 members).
•Message fan-out to all group members.
•Admins can add/remove users.

📡 Offline Messaging

•Messages must be stored and delivered when the user comes online.
•Notifications must be sent if supported.

💥 Message Surge Handling

•System must handle spikes in message volume (e.g., 1M msgs/minute).
•Graceful degradation and message ordering should be maintained.

📦 Additional

•Message persistence and history (per chat).
•Basic user authentication and contact discovery.
•Support emoji, text, and media messages.

⚙️ Non-Functional Requirements:

•Sub-second latency for real-time messages
•Scalability to millions of users
•Fault tolerance (e.g., message retries)
•Horizontal scalability
•End-to-end encryption (optional for now)
•High availability


🧱 Key Components:

ComponentDescription

Client App

Web/iOS/Android app with WebSocket connection

API Gateway

Auth, routing, rate-limiting

Auth Service

JWT-based login and user verification

Chat Service

Core logic for sending, receiving, and processing messages

WebSocket Gateway

Bi-directional messaging using WebSocket or MQTT

Message Queue

Kafka/Redis Streams for decoupling producer/consumer

Notification Service

Push notifications for offline users

Group Service

Manage groups and memberships

Message Store

Persistent chat history store

Presence Service

Tracks online/offline status

Media Service

Stores and retrieves images, videos, files (CDN/S3)


🗂️ Database Design (Simplified):

User

1sql 2CopyEdit 3user_id (PK) | name | email | last_seen | profile_pic_url

Chat

1sql 2CopyEdit 3chat_id (PK) | is_group | created_at

ChatMember

1sql 2CopyEdit 3chat_id (FK) | user_id (FK) | role (admin/member)

Message

1sql 2CopyEdit 3message_id (PK) | chat_id (FK) | sender_id (FK) | content | timestamp | message_type | status
•message_type: text, image, video, file
•status: sent, delivered, read


🔌 API Contracts (REST + WebSocket)


📥 REST APIs

•POST /messages/send
•GET /messages/history?chatId={id}&limit=50
•POST /groups/create
•POST /groups/{id}/addMember
•GET /users/{id}/chats


📡 WebSocket Events

•message:send → {chat_id, sender_id, content}
•message:receive → {message_id, chat_id, sender_id, content, timestamp}
•message:read → {message_id, user_id}


🧠 Scalability and Surge Handling:


✅ Use:

•Kafka to buffer incoming messages and decouple writes
•Sharded message stores per chat or user
•WebSocket gateways that scale horizontally (stickiness via Redis)
•Fan-out optimization for group messages (e.g., fan-out-on-write vs read)
•Rate limiting + backpressure handling on send API


🔐 Security & Reliability

•Idempotent message send requests (via client-generated message IDs)
•Retry logic for message delivery
•Message signing or encryption (optional)
•Store undelivered messages in Redis/DB and flush when user reconnects


🧪 Optional Enhancements:

•Search messages across chats
•Media compression
•Voice/video calling module
•Multi-device sync
•Self-destructing messages


Solution

Comments