Skip to the content.

⭐ What is a Chat System?

A chat system lets two or more users send messages in real-time.

Example: WhatsApp, Slack, Instagram DM, Messenger.

To design it, you must handle:


⭐ Basic Architecture (Simple Version)

Image

Image

Image

Image

A simple chat system has:

1️⃣ Client (mobile/web app)

2️⃣ WebSocket Gateway

3️⃣ Backend Chat Service

4️⃣ Database

Stores:

5️⃣ Message Queue (Kafka/RabbitMQ)


⭐ How a Chat Message Flows (Step-by-Step)

💬 User A sends “Hi”

  1. A → WebSocket Server: “Hi”
  2. WebSocket Server → Chat Service: message event
  3. Chat Service → Stores message in DB
  4. Chat Service → Sends event to Kafka
  5. Kafka → Notifies consumer services (delivery, analytics, push)
  6. If user B is online → WebSocket Server pushes “Hi” to B instantly
  7. If user B is offline → Store as unread → Send push notification (FCM/APNs)

⭐ How Real-Time Works?

✔ WebSockets

Used to maintain a persistent connection between:

This enables:


⭐ Core Concepts You Must Know

A. Message Delivery

B. Read Receipts

WhatsApp style:

C. Message Ordering

You MUST maintain order inside a chat.

Common techniques:

D. Typing Indicator

Send a “typing” event over WebSocket:

E. Presence (Online/Offline)

Use heartbeat every 30 sec:

Store in Redis:

user123: online
user456: offline

⭐ Database Design (Simple)

Users Table

user_id
name
status

Conversations Table

conversation_id
user1_id
user2_id
last_message
timestamp

Messages Table

message_id
conversation_id
sender_id
content
timestamp
status (sent, delivered, seen)

⭐ Scaling the Chat System

✔ 1. WebSocket Sharding

✔ 2. Use Redis for presence

✔ 3. Use Kafka for message distribution

✔ 4. Event-driven system

Every message triggers an event:


⭐ Why Not Use HTTP Polling?

Approach Real-time? Efficient? Used in modern chat?
Short Polling ❌ No ❌ No ❌ No
Long Polling ⚠️ Okay ⚠️ Medium Rare
SSE ✔ One-way Good Not for chat
WebSockets ✔ Full real-time ✔ Best Yes (industry standard)

➡ Chat apps need two-way instant communication → WebSockets.


⭐ Offline Handling

If user is offline:


⭐ Interview Answer (Perfect 30-second answer)

A chat system uses WebSockets to maintain persistent real-time connections between users. Messages are passed through a WebSocket gateway to a Chat Service, which stores them in a database and publishes them to Kafka for reliable delivery. Online users receive messages instantly through WebSockets, while offline users receive push notifications and unread messages when they reconnect. The system uses Redis for online presence and heartbeat tracking, Kafka for scalability, and a message-store database to preserve ordering and history.