Design a Chat Application

Difficulty: MEDIUMCategory: HLDFrequency: 1Asked On 2025-05-20

Problem Statement

Design a real-time chat application that allows users to send and receive messages instantly, both in one-on-one and group chats.


The system should support real-time delivery, message persistence, read receipts, and online/offline status, while being scalable, fault-tolerant, and capable of handling millions of concurrent users.


🎯 Core Requirements


Functional Requirements


User Management

•Users can register, login, and maintain contact lists.
•Users can set online/offline/away status.

Messaging

•Send and receive instant text messages between users.
•Support group chats.
•Messages should be delivered in real time with low latency.
•Messages should be persisted so that they can be retrieved later.
•Support read receipts and message status (sent, delivered, read).
•Handle offline users — store messages until they reconnect.

Group Chats

•Users can create groups, add members, and send messages to all participants.
•Manage group metadata (name, admins, members).

Delivery Guarantees

•Each message should be delivered exactly once and in the correct order (per conversation).

Notifications

•Push notifications for new messages when a user is offline.

Search (Optional)

•Search past conversations or contacts.

Media (Optional)

•Send media like images, files, or videos.


⚙️ Non-Functional Requirements


Attribute with Target


Latency


< 100 ms per message


Availability


99.99%


Scalability


Handle 10M+ concurrent users


Durability


Messages never lost


Consistency


Eventual consistency across devices


Security


End-to-end encryption, secure authentication


🧩 Core Components


Component with Description


API Gateway


Handles incoming HTTP/WebSocket connections and routes to backend.


User Service


Handles user registration, authentication, and presence.


Chat Service


Handles message routing, delivery, and storage.


Message Queue


Buffers messages for reliable delivery and ordering.


Group Service


Manages group chat metadata and membership.


Notification Service


Pushes notifications to offline users.


Storage Layer


Persists messages, users, and metadata.


Presence Service


Tracks online/offline status of users in real time.


WebSocket Gateway


Maintains persistent real-time connections for message streaming.


Media Service (Optional)


Manages upload/download of media files.


🧱 High-Level Architecture

1 2 +----------------------+ 3 | API Gateway | 4 +----------+-----------+ 5 | 6 +----------v----------+ 7 | Auth & User Svc | 8 +----------+----------+ 9 | 10 +-----------------------------------+ 11 | Real-Time Layer | 12 +-----------------------------------+ 13 | WebSocket Gateway | Presence Svc | 14 +-----------------------------------+ 15 | 16 +----------v----------+ 17 | Chat Service | 18 +----------+----------+ 19 | 20 +----------v----------+ 21 | Message Queue | <-- (Kafka / RabbitMQ) 22 +----------+----------+ 23 | 24 +-----------------------------------+ 25 | Storage Layer | 26 +-----------------------------------+ 27 | Messages DB | User DB | Group DB | 28 | (Cassandra) | (SQL/NoSQL) | | 29 +-----------------------------------+ 30 | 31 +-----------------------------------+ 32 | Notification / Media Svc | 33 +-----------------------------------+ 34 | 35 +----------v----------+ 36 | Mobile / Web UI | 37 +---------------------+

🧠 Detailed Component Breakdown


1. User Service


•Manages registration, login, and user profiles.
•Stores user metadata (username, phone number, last seen, etc.).
•Handles authentication via tokens (JWT/OAuth).


2. Chat Service


•Core service responsible for sending/receiving messages.
•Routes messages between users using WebSocket connections.
•Stores each message in a durable message store (e.g., Cassandra, DynamoDB).
•Publishes events to a message queue for async delivery and notifications.


3. WebSocket Gateway


•Maintains persistent TCP connections.
•Handles message delivery in real time.
•Supports reconnection and delivery acknowledgment.


4. Message Queue


•Ensures reliable message delivery and order preservation.
•Buffers messages for offline users.
•Enables fan-out for group messages.


5. Presence Service

\

•Tracks online/offline status.
•Uses in-memory store (Redis / Zookeeper) to maintain presence.
•Updates user status via heartbeats.


6. Notification Service


•Sends push notifications for new messages when users are offline.
•Integrates with Apple/Google push notification APIs.


7. Storage Layer


| Data | Store | Rationale |

| -------------- | -------------------- | ----------------------------------------- |

| User Info | PostgreSQL / MySQL | Relational data |

| Messages | Cassandra / DynamoDB | High write throughput, time-series nature |

| Group Metadata | Redis / PostgreSQL | Fast lookups |

| Media | S3 / GCS | Durable blob storage |


🧱 Data Model (Simplified)


User

1 2{ 3 "user_id": "u123", 4 "username": "sahil", 5 "phone_number": "+9198xxxxxx", 6 "status": "online", 7 "last_seen": "timestamp" 8}


Message

1 2{ 3 "message_id": "m567", 4 "sender_id": "u123", 5 "receiver_id": "u456", 6 "content": "Hey, are you free?", 7 "timestamp": "2025-10-24T10:00:00Z", 8 "status": "DELIVERED" 9}


Group

1 2{ 3 "group_id": "g101", 4 "name": "Weekend Plan", 5 "members": ["u123", "u456", "u789"], 6 "created_at": "timestamp" 7}


⚡ Message Delivery Flow


1. User Sends a Message


1.Sender sends message via WebSocket → Chat Service.
2.Chat Service validates and persists message in DB.
3.Publishes message to Kafka topic: message_events.


2. Message Routing


1.If receiver is online, message is delivered instantly via WebSocket.
2.If receiver is offline, message is queued for delivery later.
3.Message status updated: SENT → DELIVERED → READ.


3. Acknowledgment


1.Once the receiver reads the message, acknowledgment is sent back.
2.Sender’s client updates message status to “READ”.


🚀 Scalability & Optimization


| Area | Approach |

| ---------------------------- | ---------------------------------------------------------------------------- |

| **Scaling Chat Servers** | Horizontally scale WebSocket gateways (use consistent hashing to map users). |

| **Message Persistence** | Use Cassandra (partition by chat_id and timestamp). |

| **Load Balancing** | Sticky sessions for WebSockets via consistent hashing. |

| **Caching** | Store recent chats in Redis. |

| **Offline Message Delivery** | Use message queue + persistence layer. |

| **Fan-out for Groups** | Use Kafka topic per group or a single topic with partitioning by group_id. |

| **High Availability** | Multi-region replication for fault tolerance. |

| **Data Sharding** | Partition users by user_id modulo N for load distribution. |


🔒 Security Considerations

•Authentication: JWT tokens or OAuth 2.0.
•Encryption: End-to-end encryption for private chats.
•Transport Security: HTTPS/WSS for secure channels.
•Data Privacy: Encrypt messages at rest and in transit.


📈 APIs


| Method | Endpoint | Description |

| ------ | --------------------- | ------------------------------- |

| `POST` | `/register` | Register a new user |

| `POST` | `/login` | Authenticate and create session |

| `POST` | `/message` | Send a new message |

| `GET` | `/messages/{chat_id}` | Fetch message history |

| `GET` | `/presence/{user_id}` | Get user online/offline status |

| `POST` | `/group` | Create a new group |

| `POST` | `/group/{id}/message` | Send message to group |



💬 Message Delivery Status Lifecycle

1 2SENT → DELIVERED → READ


•SENT: Message stored successfully.
•DELIVERED: Message received by recipient’s device.
•READ: Recipient opened chat window.


⚙️ Challenges & Trade-offs


| Challenge | Solution |

| ----------------------------------------------- | -------------------------------------------- |

| High concurrency (millions of open connections) | Use async I/O + WebSocket clustering |

| Message ordering | Per chat ordered Kafka partition |

| Offline message storage | Persistent queues + DB |

| Scalability | Horizontal scaling of chat and gateway nodes |

| Group fan-out explosion | Use Kafka topic partitioning |

| Data consistency | Eventual consistency with idempotent writes |


✅ Goal:

Design a real-time, scalable, fault-tolerant chat system that ensures low-latency message delivery, durability, presence tracking, and eventual consistency, while being extensible for features like media sharing and push notifications.

Solution

Comments