System Design
Object-Oriented Design
Instant Messaging Service

Design Example: Instant Messaging Service

An Instant Messaging Service (like WhatsApp or Slack) manages real-time communication, group interactions, and delivery statuses.


Step 1: Requirements Gathering

Core Use Cases:

  • Messaging: Users can send one-to-one or group messages.
  • Media Support: Support for Text, Image, and Voice messages.
  • Delivery Status: SENT, DELIVERED, READ.
  • User Presence: Online, Offline, Last Seen.
  • Group Management: Create groups, add/remove members, and manage admins.
  • Encryption: High-level mention of end-to-end security.

Relationship Types:

  • Private Chat: One-to-one relationship between two users.
  • Group Chat: Many-to-many relationship between users and groups.

Step 2: Identify Core Objects

  • User: Represents a registered account with contact info.
  • Message: Abstract base for different content types.
  • Conversation: Abstract base for OneToOneChat and GroupChat.
  • MessageLog: History of messages in a conversation.
  • StatusTracker: Manages delivery and read receipts.
  • NotificationEngine: Alerts users for incoming messages.

Step 3: Design Class Diagram


Step 4: Implementation in TypeScript

enum MessageStatus { SENT, DELIVERED, READ }
 
abstract class Message {
  private status: MessageStatus = MessageStatus.SENT;
  constructor(public id: string, public sender: User, public timestamp: Date) {}
}
 
class TextMessage extends Message {
  constructor(id: string, sender: User, public content: string) {
    super(id, sender, new Date());
  }
}
 
abstract class Conversation {
  protected messages: Message[] = [];
  constructor(public id: string, protected participants: User[]) {}
 
  public addMessage(msg: Message) {
    this.messages.push(msg);
    this.notifyParticipants(msg);
  }
 
  abstract notifyParticipants(msg: Message): void;
}
 
class OneToOneChat extends Conversation {
  notifyParticipants(msg: Message) {
    const receiver = this.participants.find(p => p.id !== msg.sender.id);
    // Send push notification to receiver
  }
}

Deep Dive: Observer Pattern for Real-time Updates

The Observer Pattern is essential for instant messaging. Each conversation acts as a subject, and active user sessions act as observers that receive updates whenever a new message is added.


Wrap Up

Designing an Instant Messaging service tests your ability to handle Concurrency (multiple users typing/sending at once) and State Synchronization. Decoupling the message content from the delivery logic ensures the system can handle different media types and protocols.

[!IMPORTANT] Use the Flyweight Pattern for common UI elements (like emojis or status icons) to optimize memory in long-running chat applications.