💬
Chat & Messaging System
Real-time bidirectional communication using WebSocket, Socket.io, and Redis Pub/Sub for scalable chat.
🔄 Real-time Chat Architecture
📋 Message Flow Step by Step
1
🔌User
Open chat page → Frontend establishes WebSocket connection to server (ws://)
2
🔐Server
Authenticate WebSocket connection using JWT token in query param or handshake
3
🏠Server
User joins room (chat_id) → Server tracks which socket belongs to which user
4
✉️User A
Type message → Click send → Frontend emits "send_message" event via WebSocket
5
⚙️WS Server
Receive event → Validate content → Save message to database (async)
6
⚡WS Server
Publish to Redis Pub/Sub channel (for multi-instance scaling)
7
📡Redis
All WS server instances subscribed to the channel receive the message
8
📤WS Server
Emit "receive_message" event to all users in the same room
9
💬User B
Frontend receives event → Append message to chat UI → Show notification if not in view
10
🗄️Database
Message saved: id, room_id, sender_id, content, type, status=DELIVERED, created_at
11
✅System
Update read receipt when User B reads → Emit "message_read" event back to User A
✨ Chat Features
✓✓
Read Receipts
Show when message was delivered and read (like WhatsApp double tick)
💬
Typing Indicator
"User is typing..." shown in real-time via WebSocket event
📎
File Sharing
Send images, documents, and media via upload system + URL in message
📜
Message History
Load previous messages with pagination (infinite scroll) on open
🟢
Online Status
Track online/offline status using WebSocket connect/disconnect events
📱
Push when Offline
If user is offline, fall back to push notification (FCM/APNs)
👥
Group Chat
Room-based: multiple users in one chat_id, server broadcasts to all
🔍
Message Search
Full-text search on message history using Elasticsearch or DB index
🛠️ Recommended Tech Stack
🌐
Frontend
•Socket.io-client
•React useEffect + useRef
•Infinite Scroll library
•Web Notifications API
⚙️
Backend
•Socket.io / ws (Node.js)
•Express / Fastify
•JWT authentication middleware
•Rate limiting per socket
⚡
Message Queue
•Redis Pub/Sub (multi-server)
•Bull Queue (background jobs)
•Message deduplication
•Delivery guarantees
🗄️
Database
•PostgreSQL / MongoDB
•Index on (room_id, created_at)
•Soft delete messages
•Separate read_at tracking
Need a real-time chat system? 💬
We build scalable chat systems with WebSocket, read receipts, push notifications, and file sharing.
← Back to LearnContact Us