Building High-Performance Instant Messaging Systems: Architecture, Implementation Patterns, and Cross-Scenario Development

Instant Messaging systems have become foundational infrastructure for modern internet applications, enabling real-time communication across social networking, entertainment, enterprise, and productivity domains. This article provides a comprehensive technical analysis of IM system architecture, examining implementation strategies for social chat, live streaming interaction, and workplace collaboration scenarios with practical code demonstrations.

IM System Architecture Overview

Layered Architecture Design

Contemporary IM systems typically employ a four-layer architecture that separates concerns and enables independent scaling of system components:

┌─────────────────────────────────────────┐
│         Application Layer               │
│  (Social Features / Live Streaming /    │
│   Workplace Collaboration Logic)        │
├─────────────────────────────────────────┤
│            Service Layer                │
│  (Message Processing / User Management  │
│   / Session Management / Notifications) │
├─────────────────────────────────────────┤
│          Communication Layer            │
│  (WebSocket / Long Polling / Push       │
│   Protocols / Network Adaptation)       │
├─────────────────────────────────────────┤
│             Data Layer                  │
│  (Message Storage / User Data /         │
│   Session History / Cache Clusters)     │
└─────────────────────────────────────────┘

This layered approach provides clear separation between business logic, communication handling, and data persistance. The application layer implements feature-specific logic for different use cases, while the service layer manages core IM operations. The communicasion layer abstracts transport protocols, and the data layer handles persistence across distributed storage systems.

Distributed Deployment Architecture

Large-scale IM deployments require distributed microservices architecture to handle millions of concurrent connections and messages per second:

┌─────────────────────────┐ ┌─────────────────────────┐ ┌─────────────────────────┐
│     Gateway Layer       │ │    Business Layer       │ │    Storage Layer        │
│    (API Gateway)        │ │  (Message Service)      │ │(MySQL/Redis/MongoDB)    │
├─────────────────────────┤ ├─────────────────────────┤ ├─────────────────────────┤
│ - Authentication        │ │ - Message Engine        │ │ - Message Persistence   │
│ - Rate Limiting         │ │ - Session Management    │ │ - Cache Cluster         │
│ - Protocol Conversion   │ │ - Presence Management   │ │ - Distributed Storage   │
└─────────────────────────┘ └─────────────────────────┘ └─────────────────────────┘

    │             │                 ▼                 │
    ▼             ▼         ┌─────────────────────────┐  ▼
┌─────────────────────────┐ │    Real-time Layer      │ ┌─────────────────────────┐
│     Access Layer        │ │   (Real-time Comm)      │ │  Auxiliary Services     │
│    (Client Access)      │ ├─────────────────────────┤ ├─────────────────────────┤
├─────────────────────────┤ │ - WebSocket Cluster     │ │ - Push Services         │
│ - Web Clients           │ │ - Connection Management │ │ - Anti-Spam Systems     │
│ - iOS/Android Clients   │ │ - Message Routing       │ │ - Analytics             │
│ - Desktop Applications  │ └─────────────────────────┘ └─────────────────────────┘
└─────────────────────────┘

Technology Stack Selection

Different deployment scenarios demand specific technology choices optimized for their unique requirements:

Component Social Chat Live Streaming Workplace Collaboration
Backend Language Java (Netty) / Go Node.js / Python Java (Spring Cloud) / Go
Communication Protocol WebSocket / Socket.IO WebRTC / RTMP / RTSP WebSocket / HTTP2
Database MySQL + Redis MongoDB + Redis MySQL + Elasticsearch
Frontend Framework React / Vue React + WebRTC Vue + Electron
Message Queue Kafka / RocketMQ RabbitMQ RabbitMQ / Kafka

Social Chat IM System Implementation

Message Processing Core

The message subsystem forms the foundation of any IM platform. The following implementation demonstrates a Node.js-based message processing engine with robust handling of online and offline scenarios:

// Message model definition
interface MessagePayload {
  messageId: string;
  senderId: string;
  recipientId: string;
  messageCategory: number;
  body: string;
  timestamp: number;
  deliveryStatus: number;
  conversationType: number;
}

class MessageHandler {
  private socketIO: SocketIO.Server;
  private activeConnections: Map<string, string>;
  private messageQueue: MessagePayload[];
  private persistence: MessageRepository;

  constructor(io: SocketIO.Server, repository: MessageRepository) {
    this.socketIO = io;
    this.activeConnections = new Map();
    this.messageQueue = [];
    this.persistence = repository;
  }

  processOutgoingMessage(client: SocketIO.Socket, message: MessagePayload): void {
    if (!this.isValidMessage(message)) {
      this.sendError(client, 'Invalid message format');
      return;
    }

    message.messageId = this.generateUniqueId();
    message.timestamp = Date.now();

    this.persistence.save(message);

    if (this.activeConnections.has(message.recipientId)) {
      const recipientSocket = this.activeConnections.get(message.recipientId);
      this.socketIO.to(recipientSocket).emit('message:received', message);
      this.updateDeliveryStatus(message.messageId, 2);
    } else {
      this.storeOfflineMessage(message);
      this.updateDeliveryStatus(message.messageId, 1);
    }

    client.emit('message:acknowledged', {
      messageId: message.messageId,
      status: 1
    });
  }

  registerUserConnection(userId: string, socketId: string): void {
    this.activeConnections.set(userId, socketId);
  }

  handleUserDisconnect(userId: string): void {
    this.activeConnections.delete(userId);
    this.processQueuedMessages(userId);
  }

  private storeOfflineMessage(message: MessagePayload): void {
    const offlineKey = `offline:${message.recipientId}`;
    this.messageQueue.push(message);
  }

  private processQueuedMessages(userId: string): void {
    const userMessages = this.messageQueue.filter(
      m => m.recipientId === userId
    );
    
    userMessages.forEach(message => {
      if (this.activeConnections.has(userId)) {
        const socketId = this.activeConnections.get(userId);
        this.socketIO.to(socketId).emit('message:offline', message);
      }
    });
  }

  private isValidMessage(message: MessagePayload): boolean {
    return !!(message.senderId && message.recipientId && message.body);
  }

  private generateUniqueId(): string {
    return `${Date.now()}-${Math.floor(Math.random() * 1000)}`;
  }

  private updateDeliveryStatus(messageId: string, status: number): void {
    this.persistence.updateStatus(messageId, status);
  }

  private sendError(client: SocketIO.Socket, errorMessage: string): void {
    client.emit('error:occurred', { message: errorMessage });
  }
}

class MessageRepository {
  async save(message: MessagePayload): Promise<void> {
    console.log('Persisting message:', message.messageId);
  }

  async updateStatus(messageId: string, status: number): Promise<void> {
    console.log(`Updating message ${messageId} status to ${status}`);
  }

  async fetchConversation(
    userA: string,
    userB: string,
    conversationType: number,
    page: number = 1,
    limit: number = 20
  ): Promise<MessagePayload[]> {
    console.log(`Fetching conversation between ${userA} and ${userB}`);
    return [];
  }
}

Session Management and Presence

Session management enables users to maintain multiple concurrent conversations while presence tracking provides real-time availability information:

interface Conversation {
  conversationId: string;
  category: number;
  participants: string[];
  createdAt: number;
  lastActivity?: number;
  metadata?: Map<string, unknown>;
}

class ConversationManager {
  private conversations: Map<string, Conversation>;
  private userConversations: Map<string, Map<string, Conversation>>;

  constructor() {
    this.conversations = new Map();
    this.userConversations = new Map();
  }

  establishDirectConversation(userA: string, userB: string): Conversation {
    const conversationId = this.generateConversationId(userA, userB);
    
    if (this.conversations.has(conversationId)) {
      return this.conversations.get(conversationId)!;
    }

    const conversation: Conversation = {
      conversationId,
      category: 1,
      participants: [userA, userB],
      createdAt: Date.now()
    };

    this.conversations.set(conversationId, conversation);
    this.attachToUser(userA, conversation);
    this.attachToUser(userB, conversation);

    return conversation;
  }

  establishGroupConversation(
    administratorId: string,
    memberIds: string[],
    groupName: string = 'New Group'
  ): Conversation {
    const conversationId = `group_${Date.now()}`;
    
    const conversation: Conversation = {
      conversationId,
      category: 2,
      participants: [administratorId, ...memberIds],
      createdAt: Date.now(),
      metadata: new Map([
        ['administrator', administratorId],
        ['displayName', groupName]
      ])
    };

    this.conversations.set(conversationId, conversation);
    memberIds.forEach(member => this.attachToUser(member, conversation));

    return conversation;
  }

  private attachToUser(userId: string, conversation: Conversation): void {
    if (!this.userConversations.has(userId)) {
      this.userConversations.set(userId, new Map());
    }
    this.userConversations.get(userId)!.set(conversation.conversationId, conversation);
  }

  fetchUserConversations(userId: string): Conversation[] {
    const userConvMap = this.userConversations.get(userId);
    return userConvMap ? Array.from(userConvMap.values()) : [];
  }

  addGroupParticipants(conversationId: string, newMemberIds: string[]): boolean {
    const conversation = this.conversations.get(conversationId);
    
    if (!conversation || conversation.category !== 2) {
      return false;
    }

    const existingParticipants = new Set(conversation.participants);
    newMemberIds.forEach(id => existingParticipants.add(id));
    conversation.participants = Array.from(existingParticipants);
    
    newMemberIds.forEach(memberId => this.attachToUser(memberId, conversation));
    return true;
  }

  private generateConversationId(userA: string, userB: string): string {
    return userA < userB ? `${userA}_${userB}` : `${userB}_${userA}`;
  }
}

class PresenceTracker {
  private userPresence: Map<string, PresenceStatus>;
  private presenceHistory: Map<string, PresenceStatus[]>;

  constructor() {
    this.userPresence = new Map();
    this.presenceHistory = new Map();
  }

  updateUserStatus(
    userId: string, 
    status: PresenceState,
    clientType: number = 1
  ): PresenceStatus {
    const statusRecord: PresenceStatus = {
      userId,
      state: status,
      clientType,
      updatedAt: Date.now()
    };

    this.userPresence.set(userId, statusRecord);
    this.recordStatusHistory(userId, statusRecord);
    this.broadcastPresenceChange(userId, statusRecord);

    return statusRecord;
  }

  private recordStatusHistory(userId: string, status: PresenceStatus): void {
    if (!this.presenceHistory.has(userId)) {
      this.presenceHistory.set(userId, []);
    }
    
    const history = this.presenceHistory.get(userId)!;
    history.push(status);
    
    if (history.length > 100) {
      history.shift();
    }
  }

  private broadcastPresenceChange(userId: string, status: PresenceStatus): void {
    console.log(`User ${userId} presence changed to ${status.state}`);
  }

  queryUserStatus(userId: string): PresenceStatus {
    const status = this.userPresence.get(userId);
    
    if (!status) {
      return { userId, state: PresenceState.OFFLINE, updatedAt: 0 };
    }
    
    const thirtySecondsAgo = Date.now() - 30000;
    if (status.updatedAt < thirtySecondsAgo) {
      return { userId, state: PresenceState.OFFLINE, updatedAt: status.updatedAt };
    }
    
    return status;
  }

  isUserAvailable(userId: string): boolean {
    const status = this.queryUserStatus(userId);
    return status.state !== PresenceState.OFFLINE;
  }
}

enum PresenceState {
  OFFLINE = 0,
  ONLINE = 1,
  BUSY = 2,
  AWAY = 3
}

interface PresenceStatus {
  userId: string;
  state: PresenceState;
  clientType: number;
  updatedAt: number;
}

Extended Social Features

Modern social IM platforms require additional features beyond basic messaging to create engaging user experiences:

interface FriendRequest {
  requestId: string;
  requesterId: string;
  targetId: string;
  personalMessage: string;
  submittedAt: number;
  status: RequestStatus;
}

interface Friendship {
  userId: string;
  friendId: string;
  establishedAt: number;
  status: RelationshipStatus;
}

class SocialGraphManager {
  private relationships: Map<string, Friendship[]>;
  private pendingRequests: Map<string, FriendRequest[]>;

  constructor() {
    this.relationships = new Map();
    this.pendingRequests = new Map();
  }

  submitConnectionRequest(
    requesterId: string,
    targetId: string,
    message: string = 'Would like to connect'
  ): FriendRequest {
    const request: FriendRequest = {
      requestId: `${Date.now()}-${Math.random()}`,
      requesterId,
      targetId,
      personalMessage: message,
      submittedAt: Date.now(),
      status: RequestStatus.PENDING
    };

    if (!this.pendingRequests.has(targetId)) {
      this.pendingRequests.set(targetId, []);
    }
    
    this.pendingRequests.get(targetId)!.push(request);
    return request;
  }

  processConnectionRequest(
    targetId: string,
    requestId: string,
    approved: boolean
  ): FriendRequest | null {
    const requests = this.pendingRequests.get(targetId);
    if (!requests) return null;

    const requestIndex = requests.findIndex(r => r.requestId === requestId);
    if (requestIndex === -1) return null;

    const request = requests[requestIndex];
    request.status = approved ? RequestStatus.ACCEPTED : RequestStatus.DECLINED;

    if (approved) {
      this.establishRelationship(request.requesterId, targetId);
    }

    return request;
  }

  private establishRelationship(userA: string, userB: string): void {
    const friendshipA: Friendship = {
      userId: userA,
      friendId: userB,
      establishedAt: Date.now(),
      status: RelationshipStatus.ACTIVE
    };

    const friendshipB: Friendship = {
      userId: userB,
      friendId: userA,
      establishedAt: Date.now(),
      status: RelationshipStatus.ACTIVE
    };

    this.addRelationship(userA, friendshipA);
    this.addRelationship(userB, friendshipB);
  }

  private addRelationship(userId: string, friendship: Friendship): void {
    if (!this.relationships.has(userId)) {
      this.relationships.set(userId, []);
    }
    this.relationships.get(userId)!.push(friendship);
  }

  fetchConnections(userId: string): Friendship[] {
    return this.relationships.get(userId) || [];
  }
}

class MediaMessageHandler {
  private messageProcessor: MessageHandler;

  constructor(processor: MessageHandler) {
    this.messageProcessor = processor;
  }

  createEmojiMessage(
    senderId: string,
    recipientId: string,
    emojiCode: string,
    conversationType: number = 1
  ): MessagePayload {
    return this.buildRichMessage(
      senderId, 
      recipientId, 
      2, 
      emojiCode, 
      conversationType
    );
  }

  createVoiceMessage(
    senderId: string,
    recipientId: string,
    audioUrl: string,
    duration: number,
    conversationType: number = 1
  ): MessagePayload {
    const body = JSON.stringify({ audioUrl, duration });
    return this.buildRichMessage(
      senderId, 
      recipientId, 
      3, 
      body, 
      conversationType
    );
  }

  createImageMessage(
    senderId: string,
    recipientId: string,
    imageUrl: string,
    dimensions: { width: number; height: number },
    conversationType: number = 1
  ): MessagePayload {
    const body = JSON.stringify({ 
      url: imageUrl, 
      ...dimensions 
    });
    return this.buildRichMessage(
      senderId, 
      recipientId, 
      4, 
      body, 
      conversationType
    );
  }

  private buildRichMessage(
    senderId: string,
    recipientId: string,
    category: number,
    body: string,
    conversationType: number
  ): MessagePayload {
    return {
      messageId: `${Date.now()}-${Math.floor(Math.random() * 1000)}`,
      senderId,
      recipientId,
      messageCategory: category,
      body,
      timestamp: Date.now(),
      deliveryStatus: 0,
      conversationType
    };
  }

  recordReaction(userId: string, messageId: string, reactionType: string): void {
    console.log(`User ${userId} reacted ${reactionType} to message ${messageId}`);
  }
}

enum RequestStatus {
  PENDING = 1,
  ACCEPTED = 2,
  DECLINED = 3
}

enum RelationshipStatus {
  ACTIVE = 1,
  BLOCKED = 2,
  REMOVED = 3
}

Live Streaming Interaction Implementation

WebRTC-based Co-broadcasting

Live streaming scenarios require real-time audio and video capabilities for co-hosting features. WebRTC provides the foundation for peer-to-peer media communication:

interface SignalingMessage {
  type: 'offer' | 'answer' | 'ice-candidate' | 'bye';
  peerId: string;
  payload: RTCSessionDescriptionInit | RTCIceCandidateInit;
}

class MediaConnectionManager {
  private peerConnections: Map<string, RTCPeerConnection>;
  private localMediaStream: MediaStream | null;
  private iceServers: RTCIceServer[];
  private signalingChannel: SignalingService;

  constructor(signalingService: SignalingService) {
    this.peerConnections = new Map();
    this.localMediaStream = null;
    this.iceServers = [
      { urls: 'stun:stun.l.google.com:19302' },
      { 
        urls: 'turn:stream.example.com', 
        username: 'broadcaster', 
        credential: 'securepass'
      }
    ];
    this.signalingChannel = signalingService;
  }

  async initializeLocalMedia(
    videoEnabled: boolean = true,
    audioEnabled: boolean = true
  ): Promise<MediaStream> {
    try {
      this.localMediaStream = await navigator.mediaDevices.getUserMedia({
        video: videoEnabled ? { width: 1280, height: 720 } : false,
        audio: audioEnabled
      });
      return this.localMediaStream;
    } catch (error) {
      console.error('Failed to acquire local media:', error);
      throw error;
    }
  }

  establishPeerConnection(remotePeerId: string): RTCPeerConnection {
    const peerConnection = new RTCPeerConnection({
      iceServers: this.iceServers,
      iceCandidatePoolSize: 10
    });

    peerConnection.onicecandidate = (event) => {
      if (event.candidate) {
        this.sendSignalingMessage({
          type: 'ice-candidate',
          peerId: remotePeerId,
          payload: event.candidate.toJSON()
        });
      }
    };

    peerConnection.ontrack = (event) => {
      this.handleIncomingMediaStream(remotePeerId, event.streams[0]);
    };

    peerConnection.onconnectionstatechange = () => {
      this.handleConnectionStateChange(remotePeerId, peerConnection.connectionState);
    };

    if (this.localMediaStream) {
      this.localMediaStream.getTracks().forEach(track => {
        peerConnection.addTrack(track, this.localMediaStream!);
      });
    }

    this.peerConnections.set(remotePeerId, peerConnection);
    return peerConnection;
  }

  async initiateCall(remotePeerId: string): Promise<RTCSessionDescriptionInit> {
    const peerConnection = this.establishPeerConnection(remotePeerId);
    
    const offer = await peerConnection.createOffer({
      offerToReceiveAudio: true,
      offerToReceiveVideo: true
    });
    
    await peerConnection.setLocalDescription(offer);
    
    this.sendSignalingMessage({
      type: 'offer',
      peerId: remotePeerId,
      payload: offer
    });

    return offer;
  }

  async handleIncomingOffer(
    remotePeerId: string,
    offer: RTCSessionDescriptionInit
  ): Promise<RTCSessionDescriptionInit> {
    const peerConnection = this.establishPeerConnection(remotePeerId);
    
    await peerConnection.setRemoteDescription(new RTCSessionDescription(offer));
    
    const answer = await peerConnection.createAnswer();
    await peerConnection.setLocalDescription(answer);
    
    this.sendSignalingMessage({
      type: 'answer',
      peerId: remotePeerId,
      payload: answer
    });

    return answer;
  }

  async handleAnswer(
    remotePeerId: string,
    answer: RTCSessionDescriptionInit
  ): Promise<void> {
    const peerConnection = this.peerConnections.get(remotePeerId);
    if (peerConnection) {
      await peerConnection.setRemoteDescription(new RTCSessionDescription(answer));
    }
  }

  async handleIceCandidate(
    remotePeerId: string,
    candidate: RTCIceCandidateInit
  ): Promise<void> {
    const peerConnection = this.peerConnections.get(remotePeerId);
    if (peerConnection) {
      await peerConnection.addIceCandidate(new RTCIceCandidate(candidate));
    }
  }

  private handleIncomingMediaStream(peerId: string, stream: MediaStream): void {
    console.log(`Received media stream from peer ${peerId}`);
    this.emit('remote-media', { peerId, stream });
  }

  private handleConnectionStateChange(
    peerId: string, 
    state: RTCPeerConnectionState
  ): void {
    console.log(`Connection with ${peerId} changed to: ${state}`);
    
    if (state === 'disconnected' || state === 'failed') {
      this.terminateConnection(peerId);
    }
  }

  terminateConnection(peerId: string): void {
    const peerConnection = this.peerConnections.get(peerId);
    if (peerConnection) {
      peerConnection.close();
      this.peerConnections.delete(peerId);
      
      this.sendSignalingMessage({
        type: 'bye',
        peerId,
        payload: null
      });
    }
  }

  private sendSignalingMessage(message: SignalingMessage): void {
    this.signalingChannel.send(message);
  }

  private emit(event: string, data: unknown): void {
    // Event emission implementation
  }
}

interface SignalingService {
  send(message: SignalingMessage): void;
  onMessage(callback: (message: SignalingMessage) => void): void;
}

Real-time Danmaku System

Danmaku (bullet comments) creates an interactive viewing experience by overlaying user messages on video content:

interface DanmakuPayload {
  danmakuId: string;
  userId: string;
  roomId: string;
  content: string;
  style: DanmakuStyle;
  timestamp: number;
}

interface DanmakuStyle {
  fontSize: string;
  color: string;
  position: DanmakuPosition;
}

enum DanmakuPosition {
  TOP = 1,
  BOTTOM = 2,
  SCROLLING = 3
}

class DanmakuCoordinator {
  private broadcastChannel: SocketIO.Server;
  private messageHistory: DanmakuPayload[];
  private rateLimiter: Map<string, number>;
  private spamFilter: ContentModerator;

  constructor(io: SocketIO.Server, moderator: ContentModerator) {
    this.broadcastChannel = io;
    this.messageHistory = [];
    this.rateLimiter = new Map();
    this.spamFilter = moderator;
  }

  postDanmaku(
    userId: string,
    roomId: string,
    content: string,
    color: string = '#FFFFFF',
    fontSize: number = 24
  ): DanmakuResult {
    if (this.isRateLimited(userId, roomId)) {
      return { success: false, error: 'Please slow down' };
    }

    const filteredContent = this.spamFilter.sanitize(content);
    if (!filteredContent) {
      return { success: false, error: 'Content filtered' };
    }

    const danmaku: DanmakuPayload = {
      danmakuId: `${Date.now()}-${Math.floor(Math.random() * 1000)}`,
      userId,
      roomId,
      content: filteredContent,
      timestamp: Date.now(),
      style: {
        fontSize: `${fontSize}px`,
        color,
        position: DanmakuPosition.SCROLLING
      }
    };

    this.archiveMessage(danmaku);
    this.broadcastToRoom(roomId, danmaku);
    this.updateRateLimit(userId, roomId);

    return { success: true, data: danmaku };
  }

  private isRateLimited(userId: string, roomId: string): boolean {
    const key = `${userId}:${roomId}`;
    const lastPost = this.rateLimiter.get(key) || 0;
    return Date.now() - lastPost < 1000;
  }

  private updateRateLimit(userId: string, roomId: string): void {
    const key = `${userId}:${roomId}`;
    this.rateLimiter.set(key, Date.now());
    
    setTimeout(() => {
      this.rateLimiter.delete(key);
    }, 10000);
  }

  private archiveMessage(message: DanmakuPayload): void {
    this.messageHistory.push(message);
    
    if (this.messageHistory.length > 1000) {
      this.messageHistory.shift();
    }
  }

  private broadcastToRoom(roomId: string, danmaku: DanmakuPayload): void {
    this.broadcastChannel.to(roomId).emit('danmaku:new', danmaku);
  }

  retrieveRoomHistory(roomId: string, count: number = 100): DanmakuPayload[] {
    return this.messageHistory
      .filter(m => m.roomId === roomId)
      .slice(-count);
  }

  retrieveUserHistory(userId: string, count: number = 50): DanmakuPayload[] {
    return this.messageHistory
      .filter(m => m.userId === userId)
      .slice(-count);
  }
}

class ContentModerator {
  private forbiddenTerms: Set<string>;
  
  constructor() {
    this.forbiddenTerms = new Set(['banned1', 'banned2']);
  }

  sanitize(content: string): string | null {
    let sanitized = content;
    
    this.forbiddenTerms.forEach(term => {
      const pattern = new RegExp(term, 'gi');
      sanitized = sanitized.replace(pattern, '***');
    });

    return sanitized.length > 0 ? sanitized : null;
  }
}

interface DanmakuResult {
  success: boolean;
  data?: DanmakuPayload;
  error?: string;
}

Live Streaming State Management

Broadcast rooms require specialized state management to track participants, viewers, and streaming status:

interface BroadcastRoom {
  roomId: string;
  hostId: string;
  status: StreamingState;
  participantCount: number;
  createdAt: number;
  configuration: RoomConfiguration;
  hosts: string[];
  moderators: string[];
  audience: string[];
  coHostApplications: CoHostApplication[];
}

interface RoomConfiguration {
  title: string;
  coverImage: string;
  accessLevel: AccessType;
  allowCoHosting: boolean;
}

interface CoHostApplication {
  userId: string;
  reason: string;
  submittedAt: number;
  status: ApplicationStatus;
}

enum StreamingState {
  OFFLINE = 0,
  LIVE = 1,
  ENDED = 2,
  PAUSED = 3
}

enum AccessType {
  PUBLIC = 1,
  SUBSCRIBERS = 2,
  PRIVATE = 3
}

enum ApplicationStatus {
  PENDING = 1,
  APPROVED = 2,
  REJECTED = 3
}

class BroadcastRoomManager {
  private rooms: Map<string, BroadcastRoom>;
  private roomParticipants: Map<string, Set<string>>;
  private activeStreams: Map<string, string>;

  constructor() {
    this.rooms = new Map();
    this.roomParticipants = new Map();
    this.activeStreams = new Map();
  }

  createRoom(hostId: string, config: Partial<RoomConfiguration> = {}): BroadcastRoom {
    const roomId = `broadcast_${Date.now()}`;
    
    const room: BroadcastRoom = {
      roomId,
      hostId,
      status: StreamingState.LIVE,
      participantCount: 0,
      createdAt: Date.now(),
      configuration: {
        title: 'New Broadcast',
        coverImage: '',
        accessLevel: AccessType.PUBLIC,
        allowCoHosting: true,
        ...config
      },
      hosts: [hostId],
      moderators: [hostId],
      audience: [],
      coHostApplications: []
    };

    this.rooms.set(roomId, room);
    this.roomParticipants.set(roomId, new Set([hostId]));
    this.activeStreams.set(hostId, roomId);

    return room;
  }

  joinRoom(roomId: string, userId: string, isHost: boolean = false): BroadcastRoom | null {
    const room = this.rooms.get(roomId);
    if (!room) return null;

    const participants = this.roomParticipants.get(roomId)!;
    if (participants.has(userId)) return room;

    participants.add(userId);

    if (isHost && !room.hosts.includes(userId)) {
      room.hosts.push(userId);
    } else if (!room.audience.includes(userId)) {
      room.audience.push(userId);
    }

    room.participantCount = room.audience.length;
    return room;
  }

  leaveRoom(roomId: string, userId: string): boolean {
    const room = this.rooms.get(roomId);
    if (!room) return false;

    const participants = this.roomParticipants.get(roomId);
    if (!participants?.has(userId)) return false;

    participants.delete(userId);

    if (room.hosts.includes(userId)) {
      room.hosts = room.hosts.filter(id => id !== userId);
      if (room.hosts.length === 0) {
        room.status = StreamingState.ENDED;
      }
    } else {
      room.audience = room.audience.filter(id => id !== userId);
    }

    room.participantCount = room.audience.length;
    return true;
  }

  submitCoHostRequest(
    roomId: string,
    userId: string,
    reason: string = 'Requesting to co-host'
  ): ApplicationResult {
    const room = this.rooms.get(roomId);
    if (!room) {
      return { success: false, error: 'Room not found' };
    }

    const application: CoHostApplication = {
      userId,
      reason,
      submittedAt: Date.now(),
      status: ApplicationStatus.PENDING
    };

    room.coHostApplications.push(application);
    this.notifyHost(roomId, `User ${userId} requests co-hosting: ${reason}`);

    return { success: true, data: application };
  }

  processCoHostRequest(
    roomId: string,
    applicationUserId: string,
    approved: boolean
  ): ApplicationResult {
    const room = this.rooms.get(roomId);
    if (!room) {
      return { success: false, error: 'Room not found' };
    }

    const application = room.coHostApplications.find(
      a => a.userId === applicationUserId
    );
    
    if (!application) {
      return { success: false, error: 'Application not found' };
    }

    application.status = approved 
      ? ApplicationStatus.APPROVED 
      : ApplicationStatus.REJECTED;

    if (approved && !room.hosts.includes(applicationUserId)) {
      room.hosts.push(applicationUserId);
    }

    this.notifyUser(
      applicationUserId, 
      approved 
        ? 'Co-host request approved' 
        : 'Co-host request declined'
    );

    return { success: true, data: application };
  }

  private notifyHost(roomId: string, notification: string): void {
    const room = this.rooms.get(roomId);
    if (room) {
      console.log(`Notifying host: ${notification}`);
    }
  }

  private notifyUser(userId: string, message: string): void {
    console.log(`Notifying user ${userId}: ${message}`);
  }
}

interface ApplicationResult {
  success: boolean;
  data?: CoHostApplication;
  error?: string;
}

Workplace Collaboration IM Implementation

Enhanced Messaging for Enterprise

Enterprise environments require enhanced messaging capabilities including read receipts, mentions, and integration with work management systems:

interface EnterpriseMessage {
  messageId: string;
  senderId: string;
  recipientId: string;
  messageCategory: number;
  body: string;
  timestamp: number;
  deliveryStatus: number;
  conversationType: number;
  metadata: MessageMetadata;
}

interface MessageMetadata {
  readReceipt: boolean;
  mentionedUsers: string[];
  attachment?: AttachmentInfo;
  linkedTask?: TaskReference;
  linkedMeeting?: MeetingReference;
}

interface AttachmentInfo {
  fileId: string;
  fileName: string;
  fileSize: number;
  mimeType: string;
  downloadUrl: string;
}

interface TaskReference {
  taskId: string;
  taskTitle: string;
  taskUrl: string;
}

interface MeetingReference {
  meetingId: string;
  meetingTitle: string;
  meetingUrl: string;
  startTime: number;
}

class EnterpriseMessageBuilder {
  private message: EnterpriseMessage;

  constructor() {
    this.message = {
      messageId: '',
      senderId: '',
      recipientId: '',
      messageCategory: 0,
      body: '',
      timestamp: 0,
      deliveryStatus: 0,
      conversationType: 0,
      metadata: {
        readReceipt: false,
        mentionedUsers: []
      }
    };
  }

  composeText(
    senderId: string,
    recipientId: string,
    content: string,
    conversationType: number = 1
  ): this {
    this.message.senderId = senderId;
    this.message.recipientId = recipientId;
    this.message.messageCategory = 101;
    this.message.body = content;
    this.message.timestamp = Date.now();
    this.message.conversationType = conversationType;
    this.message.messageId = this.generateId();
    return this;
  }

  composeNotification(
    senderId: string,
    recipientId: string,
    title: string,
    notificationBody: string,
    conversationType: number = 3
  ): this {
    this.message.senderId = senderId;
    this.message.recipientId = recipientId;
    this.message.messageCategory = 102;
    this.message.body = JSON.stringify({ title: title, content: notificationBody });
    this.message.timestamp = Date.now();
    this.message.conversationType = conversationType;
    this.message.messageId = this.generateId();
    return this;
  }

  composeTaskLink(
    senderId: string,
    recipientId: string,
    taskId: string,
    taskTitle: string,
    conversationType: number = 2
  ): this {
    this.message.senderId = senderId;
    this.message.recipientId = recipientId;
    this.message.messageCategory = 103;
    this.message.body = JSON.stringify({ taskId, taskTitle });
    this.message.metadata.linkedTask = { taskId, taskTitle, taskUrl: `/tasks/${taskId}` };
    this.message.timestamp = Date.now();
    this.message.conversationType = conversationType;
    this.message.messageId = this.generateId();
    return this;
  }

  withReadReceipt(enabled: boolean = true): this {
    this.message.metadata.readReceipt = enabled;
    return this;
  }

  mentionUsers(...userIds: string[]): this {
    this.message.metadata.mentionedUsers = [
      ...new Set([...this.message.metadata.mentionedUsers, ...userIds])
    ];
    return this;
  }

  attachFile(file: AttachmentInfo): this {
    this.message.metadata.attachment = file;
    return this;
  }

  build(): EnterpriseMessage {
    return { ...this.message };
  }

  private generateId(): string {
    return `${Date.now()}-${Math.floor(Math.random() * 1000)}`;
  }
}

class EnterpriseMessageProcessor extends MessageHandler {
  private taskManager: TaskIntegrationService;
  private meetingManager: MeetingIntegrationService;

  constructor(
    io: SocketIO.Server,
    repository: MessageRepository,
    taskService: TaskIntegrationService,
    meetingService: MeetingIntegrationService
  ) {
    super(io, repository);
    this.taskManager = taskService;
    this.meetingManager = meetingService;
  }

  processEnterpriseMessage(
    client: SocketIO.Socket, 
    message: EnterpriseMessage
  ): void {
    super.processOutgoingMessage(client, message);

    if (message.metadata.mentionedUsers.length > 0) {
      this.dispatchMentionNotifications(message);
    }

    if (message.metadata.linkedTask) {
      this.linkToTask(message);
    }

    if (message.metadata.linkedMeeting) {
      this.linkToMeeting(message);
    }
  }

  private dispatchMentionNotifications(message: EnterpriseMessage): void {
    message.metadata.mentionedUsers.forEach(userId => {
      const notification = new EnterpriseMessageBuilder()
        .composeNotification(
          message.senderId,
          userId,
          'You were mentioned',
          `${message.senderId} mentioned you in a message`
        )
        .build();
      
      super.processOutgoingMessage(null, notification);
    });
  }

  private linkToTask(message: EnterpriseMessage): void {
    if (this.taskManager && message.metadata.linkedTask) {
      this.taskManager.associateMessage(
        message.metadata.linkedTask.taskId,
        message.messageId
      );
    }
  }

  private linkToMeeting(message: EnterpriseMessage): void {
    if (this.meetingManager && message.metadata.linkedMeeting) {
      this.meetingManager.associateMessage(
        message.metadata.linkedMeeting.meetingId,
        message.messageId
      );
    }
  }

  queryReadReceipts(messageId: string): ReadReceiptInfo[] {
    return this.persistence.getReadReceipts(messageId);
  }

  markConversationAsRead(
    userId: string, 
    conversationId: string, 
    lastReadMessageId: string
  ): void {
    this.persistence.markAsRead(userId, conversationId, lastReadMessageId);
  }
}

interface ReadReceiptInfo {
  messageId: string;
  readerId: string;
  readAt: number;
}

interface TaskIntegrationService {
  associateMessage(taskId: string, messageId: string): void;
  getTaskMessages(taskId: string): string[];
}

interface MeetingIntegrationService {
  associateMessage(meetingId: string, messageId: string): void;
  getMeetingMessages(meetingId: string): string[];
}

Document Collaboration Features

Enterprise IM systems often require real-time document collaboration capabilities:

interface CollaborativeDocument {
  documentId: string;
  ownerId: string;
  title: string;
  content: string;
  createdAt: number;
  modifiedAt: number;
  collaborators: string[];
  currentVersion: number;
  versionHistory: string[];
}

class DocumentCollaborationService {
  private documents: Map<string, CollaborativeDocument>;
  private collaborationSessions: Map<string, string>;
  private changeBroadcast: SocketIO.Server;

  constructor(io: SocketIO.Server) {
    this.documents = new Map();
    this.collaborationSessions = new Map();
    this.changeBroadcast = io;
  }

  createDocument(
    creatorId: string,
    title: string,
    initialContent: string = ''
  ): CollaborativeDocument {
    const documentId = `doc_${Date.now()}`;
    
    const document: CollaborativeDocument = {
      documentId,
      ownerId: creatorId,
      title,
      content: initialContent,
      createdAt: Date.now(),
      modifiedAt: Date.now(),
      collaborators: [creatorId],
      currentVersion: 1,
      versionHistory: [initialContent]
    };

    this.documents.set(documentId, document);
    return document;
  }

  joinCollaboration(documentId: string, userId: string): boolean {
    const document = this.documents.get(documentId);
    if (!document) return false;

    if (!document.collaborators.includes(userId)) {
      document.collaborators.push(userId);
    }

    return true;
  }

  applyChanges(
    documentId: string,
    userId: string,
    delta: DocumentDelta
  ): boolean {
    const document = this.documents.get(documentId);
    if (!document) return false;

    if (!document.collaborators.includes(userId)) return false;

    document.content = this.applyDeltaOperation(document.content, delta);
    document.modifiedAt = Date.now();
    document.currentVersion++;

    if (document.versionHistory.length >= 10) {
      document.versionHistory.shift();
    }
    document.versionHistory.push(document.content);

    this.broadcastChanges(documentId, userId, delta);
    return true;
  }

  private applyDeltaOperation(
    currentContent: string, 
    delta: DocumentDelta
  ): string {
    // In production, use a diff library like jsdiff or operational transformation
    console.log('Applying document delta:', delta);
    
    switch (delta.operation) {
      case 'insert':
        return 
          currentContent.substring(0, delta.position) + 
          delta.text + 
          currentContent.substring(delta.position);
      case 'delete':
        return 
          currentContent.substring(0, delta.position) + 
          currentContent.substring(delta.position + delta.length);
      case 'replace':
        return 
          currentContent.substring(0, delta.position) + 
          delta.text + 
          currentContent.substring(delta.position + delta.length);
      default:
        return currentContent;
    }
  }

  private broadcastChanges(
    documentId: string, 
    userId: string, 
    delta: DocumentDelta
  ): void {
    const sessionId = this.getSessionIdentifier(documentId);
    
    const updateNotification = {
      type: 'document-update',
      documentId,
      editorId: userId,
      delta,
      timestamp: Date.now()
    };

    this.changeBroadcast.to(sessionId).emit('collaboration:update', updateNotification);
  }

  private getSessionIdentifier(documentId: string): string {
    if (!this.collaborationSessions.has(documentId)) {
      this.collaborationSessions.set(documentId, `doc_session_${documentId}`);
    }
    return this.collaborationSessions.get(documentId)!;
  }

  retrieveVersion(
    documentId: string, 
    versionNumber?: number
  ): string | null {
    const document = this.documents.get(documentId);
    if (!document) return null;

    if (versionNumber === undefined || versionNumber >= document.versionHistory.length) {
      return document.content;
    }

    return document.versionHistory[versionNumber];
  }

  retrieveDocument(documentId: string): CollaborativeDocument | null {
    return this.documents.get(documentId) || null;
  }
}

interface DocumentDelta {
  operation: 'insert' | 'delete' | 'replace';
  position: number;
  text?: string;
  length?: number;
}

Meeting Management Integration

IM systems often integrate with video conferencing capabilities:

interface Meeting {
  meetingId: string;
  organizerId: string;
  title: string;
  description: string;
  scheduledStart: number;
  scheduledEnd: number;
  participants: string[];
  status: MeetingStatus;
  createdAt: number;
  joinUrl: string;
  accessCode: string;
}

enum MeetingStatus {
  SCHEDULED = 1,
  IN_PROGRESS = 2,
  COMPLETED = 3,
  CANCELLED = 4
}

class MeetingManagementService {
  private meetings: Map<string, Meeting>;
  private activeSessions: Map<string, Set<string>>;
  private messageHandler: EnterpriseMessageProcessor;

  constructor(messageProcessor: EnterpriseMessageProcessor) {
    this.meetings = new Map();
    this.activeSessions = new Map();
    this.messageHandler = messageProcessor;
  }

  scheduleMeeting(
    organizerId: string,
    config: MeetingConfiguration
  ): Meeting {
    const meetingId = `meeting_${Date.now()}`;
    
    const meeting: Meeting = {
      meetingId,
      organizerId,
      title: config.title || 'New Meeting',
      description: config.description || '',
      scheduledStart: config.startTime || Date.now(),
      scheduledEnd: config.endTime || (Date.now() + 3600000),
      participants: [organizerId, ...(config.invitees || [])],
      status: MeetingStatus.SCHEDULED,
      createdAt: Date.now(),
      joinUrl: `https://meet.example.com/${meetingId}`,
      accessCode: this.generateAccessCode()
    };

    this.meetings.set(meetingId, meeting);
    return meeting;
  }

  joinMeeting(
    meetingId: string,
    userId: string,
    accessCode: string
  ): JoinResult {
    const meeting = this.meetings.get(meetingId);
    if (!meeting) {
      return { success: false, error: 'Meeting not found' };
    }

    if (meeting.status !== MeetingStatus.SCHEDULED && 
        meeting.status !== MeetingStatus.IN_PROGRESS) {
      return { success: false, error: 'Meeting has not started or has ended' };
    }

    if (meeting.accessCode !== accessCode) {
      return { success: false, error: 'Invalid access code' };
    }

    if (!meeting.participants.includes(userId)) {
      meeting.participants.push(userId);
    }

    if (meeting.status === MeetingStatus.IN_PROGRESS) {
      this.addToActiveSession(meetingId, userId);
    }

    return { success: true, data: meeting };
  }

  startMeeting(meetingId: string, initiatorId: string): boolean {
    const meeting = this.meetings.get(meetingId);
    if (!meeting) return false;

    if (meeting.organizerId !== initiatorId) return false;

    meeting.status = MeetingStatus.IN_PROGRESS;
    meeting.scheduledStart = Date.now();
    
    this.addToActiveSession(meetingId);
    this.notifyParticipants(meetingId, 'Meeting has started');

    return true;
  }

  endMeeting(meetingId: string, initiatorId: string): boolean {
    const meeting = this.meetings.get(meetingId);
    if (!meeting) return false;

    const isAuthorized = 
      meeting.organizerId === initiatorId || 
      meeting.participants.includes(initiatorId);
    
    if (!isAuthorized) return false;

    meeting.status = MeetingStatus.COMPLETED;
    meeting.scheduledEnd = Date.now();
    
    this.activeSessions.delete(meetingId);
    this.notifyParticipants(meetingId, 'Meeting has ended');

    return true;
  }

  private addToActiveSession(meetingId: string, userId?: string): void {
    if (!this.activeSessions.has(meetingId)) {
      this.activeSessions.set(meetingId, new Set());
    }

    if (userId) {
      this.activeSessions.get(meetingId)!.add(userId);
    }
  }

  private notifyParticipants(meetingId: string, message: string): void {
    const meeting = this.meetings.get(meetingId);
    if (!meeting) return;

    meeting.participants.forEach(participantId => {
      const notification = new EnterpriseMessageBuilder()
        .composeNotification(
          'system',
          participantId,
          'Meeting Update',
          message
        )
        .build();
      
      this.messageHandler.processOutgoingMessage(null, notification);
    });
  }

  private generateAccessCode(): string {
    return Math.floor(1000 + Math.random() * 9000).toString();
  }

  getMeetingDetails(meetingId: string): Meeting | null {
    return this.meetings.get(meetingId) || null;
  }
}

interface MeetingConfiguration {
  title?: string;
  description?: string;
  startTime?: number;
  endTime?: number;
  invitees?: string[];
}

interface JoinResult {
  success: boolean;
  data?: Meeting;
  error?: string;
}

Performance Optimization and Security

Performance Optimization Strategies

High-concurrency IM systems require careful optimization across multiple system layers:

Message Queue Utilization

Kafka or RocketMQ provide the throughput necessary for handling burst message loads. Implementing batch processing and asynchronous consumption patterns allows the system to smooth out traffic spikes while maintaining low message latency.

Caching Architecture

Redis-based caching dramatically improves system performance. Session state caching eliminates repeated database queries, while bloom filters optimize online status checks. Recent message caching with configurable TTL provides quick access to frequently accessed content.

Horizontal Scaling

Message service sharding using consistent hashing on user identifiers enables linear scalability. Connection load balancing across WebSocket servers using the same hashing strategy ensures even distribution. Database read replicas separate query workloads from write operations.

Security Implementation

Transport Security

WebSocket connections should terminate with TLS 1.3 encryption. Application-layer end-to-end encryption using established protocols like the Signal Protocol provides message confidentiality even against server compromise.

Data Protection

Sensitive fields in the database require field-level encryption. Message storage should implement access control lists and encrypted backups with geographic redundancy for disaster recovery.

Application Security

Content moderation systems combining keyword filtering with behavioral analysis identify spam and abuse. Rate limiting at multiple levels prevents resource exhaustion attacks. Granular permission controls ensure users access only permitted functionality.

End-to-End Encryption Implementation

interface EncryptedPayload {
  ciphertext: Uint8Array;
  iv: Uint8Array;
  authTag?: Uint8Array;
}

class EncryptionService {
  private keyStorage: Map<string, CryptoKeyPair>;
  private sessionKeys: Map<string, CryptoKey>;
  
  constructor() {
    this.keyStorage = new Map();
    this.sessionKeys = new Map();
  }

  async generateKeyPair(userId: string): Promise<CryptoKeyPair> {
    const keyPair = await window.crypto.subtle.generateKey(
      {
        name: 'RSA-OAEP',
        modulusLength: 2048,
        publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
        hash: { name: 'SHA-256' }
      },
      true,
      ['encrypt', 'decrypt']
    );
    
    this.keyStorage.set(userId, keyPair);
    return keyPair;
  }

  async encryptMessage(
    plaintext: string, 
    recipientPublicKey: CryptoKey
  ): Promise<EncryptedPayload> {
    const encoder = new TextEncoder();
    const encoded = encoder.encode(plaintext);
    
    const encrypted = await window.crypto.subtle.encrypt(
      { name: 'RSA-OAEP' },
      recipientPublicKey,
      encoded
    );
    
    return {
      ciphertext: new Uint8Array(encrypted),
      iv: new Uint8Array(0)
    };
  }

  async decryptMessage(
    payload: EncryptedPayload,
    privateKey: CryptoKey
  ): Promise<string> {
    const decrypted = await window.crypto.subtle.decrypt(
      { name: 'RSA-OAEP' },
      privateKey,
      payload.ciphertext
    );
    
    return new TextDecoder().decode(decrypted);
  }

  async generateSymmetricKey(): Promise<CryptoKey> {
    return await window.crypto.subtle.generateKey(
      {
        name: 'AES-GCM',
        length: 256
      },
      true,
      ['encrypt', 'decrypt']
    );
  }

  async encryptWithSymmetricKey(
    plaintext: string,
    key: CryptoKey
  ): Promise<EncryptedPayload> {
    const encoder = new TextEncoder();
    const encoded = encoder.encode(plaintext);
    const iv = window.crypto.getRandomValues(new Uint8Array(12));
    
    const encrypted = await window.crypto.subtle.encrypt(
      {
        name: 'AES-GCM',
        iv: iv,
        tagLength: 128
      },
      key,
      encoded
    );
    
    return {
      ciphertext: new Uint8Array(encrypted),
      iv: iv
    };
  }

  async decryptWithSymmetricKey(
    payload: EncryptedPayload,
    key: CryptoKey
  ): Promise<string> {
    const { ciphertext, iv } = payload;
    
    const decrypted = await window.crypto.subtle.decrypt(
      {
        name: 'AES-GCM',
        iv: iv,
        tagLength: 128
      },
      key,
      ciphertext
    );
    
    return new TextDecoder().decode(decrypted);
  }

  async wrapSymmetricKey(
    key: CryptoKey,
    publicKey: CryptoKey
  ): Promise<Uint8Array> {
    const keyData = await window.crypto.subtle.exportKey('raw', key);
    
    return await window.crypto.subtle.encrypt(
      { name: 'RSA-OAEP' },
      publicKey,
      keyData
    );
  }

  async unwrapSymmetricKey(
    wrappedKey: Uint8Array,
    privateKey: CryptoKey
  ): Promise<CryptoKey> {
    const keyData = await window.crypto.subtle.decrypt(
      { name: 'RSA-OAEP' },
      privateKey,
      wrappedKey
    );
    
    return await window.crypto.subtle.importKey(
      'raw',
      keyData,
      { name: 'AES-GCM', length: 256 },
      true,
      ['encrypt', 'decrypt']
    );
  }

  getPublicKey(userId: string): CryptoKey | null {
    const pair = this.keyStorage.get(userId);
    return pair?.publicKey || null;
  }
}

Modern instant messaging systems continue to evolve with emerging requirements. Cross-platform integration across social, entertainment, and enterprise scenarios demands flexible architectures. Artificial intelligence enhances message classification and provides intelligent assistance. Low-code platforms democratize IM integration, while immersive technologies introduce new interaction paradigms. Building effective IM systems requires balancing real-time performance with security, scalability with reliability, and feature richness with usability.

Tags: instant-messaging WebSocket WebRTC real-time-communication scalable-architecture

Posted on Tue, 19 May 2026 17:23:15 +0000 by happyness