Chat application with video messaging

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

Problem Statement

Design a real-time chat application that allows users to send text messages, media files (images, videos, documents), and short video messages (like WhatsApp, Telegram, or Instagram DMs).


The system should ensure low-latency message delivery, reliable video upload and playback, end-to-end encryption, and high availability across millions of concurrent users.


🎯 Objective


Build a scalable, secure, and performant messaging platform that supports:


•One-to-one and group chats.
•Sending/receiving text, images, and short video messages.
•Read receipts, online status, and message delivery acknowledgment.
•Real-time synchronization across multiple devices.
•Media storage and playback optimization for video messages.


✅ Functional Requirements


1. User & Authentication


•Users can register via email, phone number, or social login.
•Each user has a unique ID and can be active on multiple devices.
•Maintain online/offline status and session tokens.


2. Chat Functionality


•1:1 Chat: Direct conversation between two users.
•Group Chat: Multiple users, message broadcasting, and member management.
•Typing indicators, read receipts, and delivery status updates.
•Support emoji reactions, reply threads, and forwarding messages.


3. Video Messaging


•Users can record and send short video clips (e.g., up to 60 seconds).
•Videos are uploaded asynchronously to a media storage service (like S3).
•The system generates a thumbnail and compressed version for preview.
•Receivers can stream the video directly without full download.
•Handle upload retries, playback buffering, and progressive loading.


4. Real-Time Messaging


•Use WebSockets or gRPC streaming for live message delivery.
•Maintain persistent connections for active chats.
•Queue undelivered messages for offline users.
•Messages should appear in order (maintain message sequence per chat).


5. Media Storage & Retrieval


•Store large files (videos, images) in an object storage system (e.g., AWS S3, GCS).
•Maintain metadata in a media service database.
•Use CDN for optimized video delivery.
•Apply TTL or cleanup policy for expired messages.


6. Notifications


•Push notifications for new messages or missed video messages.
•Background sync for unread messages.
•In-app notifications for new group members or message replies.


7. Security & Privacy


•End-to-end encryption for text and video messages.
•Secure upload URLs for video content.
•Token-based authorization for accessing media.
•Data encryption at rest and in transit.


8. Message Sync & Backup


•Support multi-device sync with message history.
•Option to back up chat history and videos to cloud storage.
•Conflict resolution on message updates or deletes.


⚙️ Non-Functional Requirements


| Attribute | Goal |

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

| **Scalability** | Millions of concurrent users and chats |

| **Latency** | Message delivery < 100 ms; video upload < 2s |

| **Availability** | 99.99% uptime |

| **Consistency** | Eventual consistency across devices |

| **Durability** | No message loss even if servers crash |

| **Security** | E2E encryption + OAuth2 authentication |

| **Storage** | Efficient video compression + CDN caching |


🧩 Core Components


| Component | Responsibility |

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

| **User Service** | Manages authentication, sessions, and profiles. |

| **Chat Service** | Handles chat room creation, messaging logic, and metadata. |

| **Message Queue Service** | Manages message persistence and ordering. |

| **Media Service** | Uploads, stores, and serves videos/images. |

| **Notification Service** | Pushes alerts for messages and video events. |

| **Presence Service** | Tracks online/offline/typing status. |

| **Sync Service** | Syncs messages across multiple devices. |

| **Encryption Service** | Manages key exchange and E2E encryption. |


🧱 High-Level Architecture

1 2 +----------------------------+ 3 | Client Layer | 4 | (Web, Android, iOS Apps) | 5 +-------------+--------------+ 6 | 7 v 8 +------------+------------+ 9 | API Gateway | 10 +------------+------------+ 11 | 12 +-------------------------------------------------------+ 13 | Backend | 14 |-------------------------------------------------------| 15 | Auth Service Chat Service Media Service | 16 | Presence Service Message Broker Notification Svc | 17 |-------------------------------------------------------| 18 | Kafka / Redis Streams / RabbitMQ | 19 +-------------------------------------------------------+ 20 | 21 v 22 +-------------------+ +-----------------------+ 23 | Object Storage | | Database Layer | 24 | (S3 / GCS / CDN) | | (Cassandra / MongoDB) | 25 +-------------------+ +-----------------------+


🧾 Data Model (Simplified)


User Table

| Field | Description |

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

| user_id | Unique user identifier |

| name | Display name |

| phone/email | Contact info |

| status | Online/Offline |

| last_seen | Timestamp |


Chat Table

| Field | Description |

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

| chat_id | Unique ID |

| chat_type | 1:1 or group |

| participant_ids | List of users |

| created_at | Timestamp |


Message Table

| Field | Description |

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

| message_id | Unique ID |

| chat_id | Associated chat |

| sender_id | Sender |

| content | Text or media reference |

| message_type | TEXT / VIDEO / IMAGE |

| timestamp | Creation time |

| status | Sent / Delivered / Read |


⚡ Scalability Considerations


| Challenge | Solution |

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

| **High concurrency** | Shard chat storage by user_id or chat_id. |

| **Message ordering** | Use Kafka or Redis streams per chat. |

| **Video upload latency** | Use presigned URLs + async background encoding. |

| **CDN optimization** | Use regional edge caching for fast video loads. |

| **Multi-device sync** | Use timestamp/version-based reconciliation. |


🔐 Security


•E2E encryption using per-chat session keys.
•OAuth2 or JWT tokens for API access.
•Presigned S3 URLs for secure uploads/downloads.
•Rate limiting to prevent spam or DDoS attacks.


📊 Observability & Metrics


•Message delivery latency (avg, p95).
•Upload success rate and encoding time.
•Number of concurrent active users.
•Message queue lag per chat topic.
•Storage cost and CDN hit ratio.


⚙️ Tech Stack (Example)


| Layer | Technology |

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

| **Frontend** | React Native / Flutter |

| **Backend** | Go / Node.js / Java Spring Boot |

| **Database** | Cassandra / DynamoDB (for messages) |

| **Cache** | Redis |

| **Queue** | Kafka / RabbitMQ |

| **Media Storage** | AWS S3 + CloudFront CDN |

| **WebSocket Gateway** | NGINX + Socket.IO / gRPC |

| **Encryption** | libsodium / Signal Protocol |

| **Push Notifications** | Firebase Cloud Messaging (FCM) / APNs |


🧩 Key APIs


| API | Method | Description |

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

| `/api/auth/register` | POST | Register new user |

| `/api/chat/create` | POST | Create new chat |

| `/api/message/send` | POST | Send message or video |

| `/api/media/upload-url` | GET | Generate presigned upload URL |

| `/api/message/history` | GET | Fetch chat history |

| `/api/notifications/push` | POST | Send notification to users |


💡 Possible Extensions

•Voice messages & calls.
•Ephemeral messages (auto-delete after viewing).
•AI-based video compression or transcription.
•Multi-region message replication for global delivery.
•Chatbot integration (e.g., support or group bots).


✅ End Goal

Design a scalable, secure, and real-time chat system that supports text and video messaging, ensures low latency communication, encrypted media handling, and seamless user experience across devices and geographies.

Solution

Comments