Back to Lego Blocks

Real-Time Chat

WebSocket-Powered Messaging System

Production-ready instant messaging platform with Socket.io, featuring rooms, threads, typing indicators, file sharing, reactions, and presence tracking for seamless real-time communication.

Sub-100ms Latency
10K+ Concurrent Users
Unlimited Rooms & Threads

Scope & Overview

A comprehensive real-time chat system covering essential messaging features with optional advanced capabilities for enhanced user experience.

Must-Have Features

  • Real-time messaging with Socket.io WebSocket connections
  • Room/channel creation with public/private visibility
  • Direct messaging between users (1-on-1 conversations)
  • Typing indicators showing who is currently typing
  • Message threading for organized conversations
  • File upload and sharing with preview support
  • Emoji reactions on messages
  • Online/offline presence tracking
  • Message history with pagination and infinite scroll
  • Unread message counters per room/conversation
  • Message search within rooms
  • User mentions with @ notifications

Nice-to-Have Features

  • Voice/video call integration (WebRTC stubs)
  • Message editing and deletion with history
  • Read receipts showing who has seen messages
  • Rich text formatting (bold, italic, code blocks)
  • Link previews for shared URLs
  • GIF integration with search
  • Message pinning for important announcements
  • User roles and permissions within rooms

Three-Tier Architecture

Modern, scalable architecture separating concerns across frontend, backend, and data layers with WebSocket for real-time communication.

Frontend Layer

Technologies

React / Next.jsSocket.io ClientTailwindCSSReact Query

Responsibilities

  • WebSocket connection management
  • Real-time message rendering
  • Typing indicator UI
  • File upload with drag-and-drop
  • Message threading display
  • Presence and status updates

Backend Layer

Technologies

Node.js / ExpressSocket.io ServerJWT AuthenticationRedis (pub/sub)

Responsibilities

  • WebSocket connection handling
  • Room management and broadcasting
  • Message validation and persistence
  • User authentication and authorization
  • Typing event coordination
  • Presence tracking with Redis

Data Layer

Technologies

MongoDBRedisAWS S3 / Blob Storage

Responsibilities

  • Message history storage
  • User profiles and relationships
  • Room metadata and members
  • Unread counters and receipts
  • File metadata with CDN URLs
  • Presence state caching

Core Concepts

Understanding the fundamental building blocks of the real-time chat system and how they work together.

Rooms/Channels

Organized spaces for group conversations. Can be public (anyone can join) or private (invite-only). Support unlimited members, custom names, descriptions, and cover images.

Examples

#general
#engineering
#random
Private: Leadership

Direct Messages

One-on-one conversations between users. Automatically created when users first message each other. Support all features like threads, reactions, and file sharing.

Examples

Alice ↔ Bob
Charlie ↔ Dana
Group DM: Alice, Bob, Charlie

Threads

Nested conversations that branch from a parent message. Keep discussions organized without cluttering the main channel. Support replies, reactions, and follow notifications.

Examples

Parent: 'What time is the meeting?'
Thread: 3 replies discussing times
Unread thread indicator

Presence & Status

Real-time tracking of user availability. Shows online, away, busy, or offline states. Displays last seen timestamp and custom status messages. Updates instantly across all clients.

Examples

🟢 Online
🟡 Away
🔴 Busy
⚫ Offline (Last seen: 5m ago)

MongoDB Collections

Document-based schema optimized for real-time messaging with flexible structure and efficient indexing.

users

User profiles, authentication, and preferences

_id: ObjectId
username: String (unique, indexed)
email: String (unique)
password_hash: String
display_name: String
avatar_url: String
status: String (online|away|busy|offline)
custom_status: String
last_seen: Date
created_at: Date

rooms

Group channels and their metadata

_id: ObjectId
name: String (indexed)
description: String
type: String (public|private)
cover_image_url: String
created_by: ObjectId (ref: users)
member_ids: Array<ObjectId>
admin_ids: Array<ObjectId>
created_at: Date
updated_at: Date

direct_messages

One-on-one and group DM conversations

_id: ObjectId
participant_ids: Array<ObjectId> (sorted, indexed)
type: String (direct|group)
name: String (optional, for group DMs)
created_at: Date
last_message_at: Date (indexed)

messages

All messages across rooms and DMs

_id: ObjectId
room_id: ObjectId (nullable)
dm_id: ObjectId (nullable)
parent_message_id: ObjectId (nullable, for threads)
sender_id: ObjectId (ref: users, indexed)
content: String
content_type: String (text|file|image|video)
file_url: String (nullable)
file_name: String (nullable)
file_size: Number (nullable)
mentions: Array<ObjectId>
reactions: Array<{emoji, user_id}>
edited: Boolean
edited_at: Date
deleted: Boolean
created_at: Date (indexed)

unread_counts

Tracks unread messages per user per conversation

_id: ObjectId
user_id: ObjectId (indexed)
room_id: ObjectId (nullable, indexed)
dm_id: ObjectId (nullable, indexed)
count: Number
last_read_message_id: ObjectId
updated_at: Date

Indexing Strategy

  • users.username and users.email: Unique indexes for fast lookups
  • rooms.name: Index for room search
  • direct_messages.participant_ids: Compound index for finding existing DM conversations
  • messages.created_at and messages.sender_id: For message pagination and user message history
  • unread_counts.user_id + room_id/dm_id: Compound index for fast unread count retrieval

Socket.io Event Protocol

Real-time bidirectional event communication between clients and server using Socket.io WebSocket protocol.

Connection Events

connectClient → Server

WebSocket connection established with auth

disconnectClient ↔ Server

User disconnected, update presence to offline

join_roomClient → Server

Join a room

{ room_id }
leave_roomClient → Server

Leave a room

{ room_id }

Messaging Events

send_messageClient → Server

Send a new message

{ room_id?, dm_id?, content, mentions? }
new_messageServer → Client

Broadcast new message to room members

{ message object }
typing_startClient → Server

User started typing

{ room_id?, dm_id? }
typing_stopClient → Server

User stopped typing

{ room_id?, dm_id? }
user_typingServer → Client

Broadcast typing indicator

{ user_id, username }

Interaction Events

add_reactionClient → Server

React to a message

{ message_id, emoji }
reaction_addedServer → Client

Broadcast reaction

{ message_id, emoji, user_id }
mark_readClient → Server

Mark messages as read

{ room_id?, dm_id?, message_id }
presence_updateServer → Client

Broadcast user status change

{ user_id, status }

Connection Management

  • Authentication: JWT token passed during connection handshake
  • Room Isolation: Users only receive messages from rooms they've joined
  • Reconnection: Automatic reconnection with exponential backoff on disconnect
  • Rate Limiting: Message sending limited to prevent spam (e.g., 10 messages/minute)

Advanced Features

Rich functionality to enhance user experience and productivity in real-time conversations.

File Sharing

Upload and share files with drag-and-drop support. Automatic image/video previews, file size limits, and secure cloud storage integration.

Implementation

  • Multipart upload to S3/Blob Storage
  • Generate signed URLs for secure access
  • Image thumbnails and video previews
  • File metadata stored in messages collection

Message Search

Full-text search across message history within rooms. Filter by sender, date range, and content type. Highlight search terms in results.

Implementation

  • MongoDB text index on messages.content
  • Search API: POST /api/search
  • Real-time search suggestions
  • Navigate to message context from results

Mentions & Notifications

@ mention users to grab attention and send notifications. Highlight mentioned messages and track unread mentions separately from regular unread messages.

Implementation

  • Parse @ mentions from message content
  • Store mention user_ids in messages.mentions array
  • Send push notifications to mentioned users
  • Special unread counter for mentions

Message Editing

Edit sent messages with visible edit indicator. Store edit history and timestamp. Delete messages with soft delete and optional redaction.

Implementation

  • Update message with edited: true, edited_at: Date
  • Broadcast message_edited event to all room members
  • Optional: Store edit history in separate collection
  • Soft delete sets deleted: true, preserves thread structure

Emoji Reactions

React to messages with emoji. Multiple reactions per user, aggregate counts, and instant UI updates. Supports custom emoji sets.

Implementation

  • Store reactions array in message: [{emoji, user_id}]
  • Deduplicate reactions per user per emoji
  • Aggregate reaction counts in UI
  • Broadcast reaction_added/removed events

Message Pinning

Pin important messages to room header for easy access. Only admins can pin/unpin. Display pinned messages in chronological order.

Implementation

  • Add pinned_message_ids array to rooms collection
  • Permission check: only admins can pin
  • GET /api/rooms/:id/pinned for pinned messages
  • Limit: max 10 pinned messages per room

REST API Endpoints

HTTP endpoints for authentication, room management, and message history. Real-time features use Socket.io events.

POST/api/auth/login

Authenticate user and return JWT token

Request

{ email, password }

Response

{ token, user: { id, username, avatar_url } }
GET/api/rooms

List all rooms user has access to

Request

?type=public|private

Response

{ rooms: [ { id, name, description, member_count, unread_count } ] }
POST/api/rooms

Create a new room

Request

{ name, description, type, member_ids }

Response

{ room: { id, name, ... } }
GET/api/rooms/:id/messages

Get message history with pagination

Request

?limit=50&before=messageId

Response

{ messages: [...], has_more: boolean }
GET/api/direct-messages

List all DM conversations for user

Response

{ conversations: [ { id, participants, last_message, unread_count } ] }
POST/api/direct-messages

Start or get existing DM conversation

Request

{ participant_ids: [user_id1, user_id2] }

Response

{ conversation: { id, participants, ... } }
GET/api/messages/:id/thread

Get thread replies for a message

Response

{ parent_message, replies: [...] }
POST/api/messages/:id/reactions

Add reaction to message

Request

{ emoji }

Response

{ success: true, message: { ...updated reactions } }
POST/api/upload

Upload file and get URL

Request

multipart/form-data: file

Response

{ url, file_name, file_size, content_type }

Authentication & Security

  • JWT Tokens: Include token in Authorization header for all protected endpoints
  • Socket.io Auth: Pass token during WebSocket handshake for real-time connections
  • Rate Limiting: API rate limits per user/IP to prevent abuse
  • Input Validation: Sanitize all user input to prevent XSS and injection attacks

React UI Components

Responsive, real-time chat interface built with React and modern UI patterns for seamless user experience.

Main Chat Interface

  • Sidebar: Rooms list, DMs, user status
  • Message area: Scrollable message history
  • Message input: Text box, file upload, emoji picker
  • Header: Current room/DM name, member count
  • Typing indicators below message list
  • Unread badges on room/DM items

Thread View

  • Split view or modal showing thread
  • Parent message at top
  • Threaded replies below
  • Reply input at bottom
  • Back to main conversation button
  • Thread participant avatars

Room Details

  • Room name, description, cover image
  • Member list with online status
  • Pinned messages section
  • Room settings (admins only)
  • Add members button
  • Leave room / Archive room

User Profile

  • Profile picture, display name
  • Status: Online/Away/Busy/Offline
  • Custom status message input
  • Notification preferences
  • Blocked users list
  • Account settings link

Real-Time UI Updates

  • Message Rendering: New messages appear instantly without refresh using Socket.io events
  • Optimistic Updates: Show sent messages immediately, reconcile with server response
  • Typing Indicators: Show "User is typing..." with 2-3 second timeout
  • Presence Updates: User status dots update in real-time across all views
  • Infinite Scroll: Load older messages as user scrolls up, maintain scroll position

Production Benefits

Enterprise-grade real-time chat system ready for immediate deployment with all essential features.

Real-Time Performance

Sub-100ms message delivery with WebSocket connections and optimized database queries.

Secure & Private

JWT authentication, encrypted connections, and permission-based access control.

Production Ready

Scalable architecture with Redis pub/sub, rate limiting, and error handling.

Definition of Done

WebSocket connections established and authenticated
Messages sent and received in real-time across rooms
Typing indicators working with proper timeout
File upload to cloud storage with secure URLs
Message threading with reply navigation
Emoji reactions added and displayed
Unread counters accurate per room/DM
Presence tracking: online, away, offline states
Message history pagination working
Search functionality across message content
User mentions with @ symbol and notifications
Mobile-responsive UI for all screen sizes

Build Your Next Product With AI Expertise

Experience the future of software development. Let our GenAI platform accelerate your next project.

Schedule a Free AI Blueprint Session