Design WhatsApp: Real-Time Chat System Design
Step 3 β Introduce the Message Service
The WebSocket server should only handle connection management. Business logic β validation, routing, persistence, retries β belongs in a dedicated Message Service.
Request Flow
WebSocket receives, Message Service routes
User A sends a frame. The WS server immediately hands off to the Message Service β routing, validation, and persistence happen there.
// WebSocket server (thin transport layer):
ws.on('message', (frame) => {
msgService.handle(frame); // hand off immediately
});Message Service validates and persists
The Message Service assigns a unique ID, checks rate limits, writes to the Database, then checks if User B has an active connection.
// Message Service internals: 1. Assign messageId (UUID) 2. Validate: size β€ 4096B, rate β€ 100 msg/s 3. INSERT INTO messages (id, from, to, body, ts) 4. Lookup: is userB's WS connection alive?
Deliver or queue
If User B is online: push immediately. If offline: the message persists in the Database waiting for Step 4's queue to deliver it.
if (conn = wsRegistry.get('userB')) {
conn.send(frame); // push directly
} else {
// offline: enqueue for later delivery
}Why We Need This
Separating concerns lets each component scale independently. WebSocket servers scale with concurrent connections. The Message Service scales with message throughput.
Key Insight
The Message Service owns the message lifecycle: receive β validate β persist β route β deliver. The WebSocket server is just the transport. This separation is what makes the system horizontally scalable.
Step 3 of 7
