Chat Server: Design a Real-Time Messaging System with Rooms, Message History, and User Presence
Question Details
Problem
Design a ChatServer class that manages chat rooms:
- create_room(room_id) -- create a new room.
- join_room(user_id, room_id) -- add user to room.
- leave_room(user_id, room_id) -- remove user from room.
- send_message(user_id, room_id, text) -> Message -- broadcast message;
return message object with timestamp.
- get_history(room_id, limit=50) -> list[Message] --
return the limit most recent messages.
- online_users(room_id) -> list[str] --
return currently joined users.
python
from dataclasses import dataclass
from datetime import datetime
@dataclass
class Message:
id: int
user_id: str
room_id: str
text: str
timestamp: datetime
class ChatServer:
...
Example:
server.create_room("general")
server.join_room("alice", "general")
server.send_message("alice", "general", "hello")
server.get_history("general") -> [Message(...)]
Follow-ups
1. get_history must be fast even with millions of messages. What storage structure and index would you use?
2. A user disconnects without calling leave_room. How do you detect and clean up stale presence?
3. How would you fan out a message to 10,000 users in the same room with low latency?
4. Add read receipts: track which users have seen each message up to which message id.
Full Details
Problem
Design a ChatServer class that manages chat rooms:
- create_room(room_id) -- create a new room.
- join_room(user_id, room_id) -- add user to room.
- leave_room(user_id, room_id) -- remove user from room.
- send_message(user_id, room_id, text) -> Message -- broadcast message;
return message object with timestamp.
- get_history(room_id, limit=50) -> list[Message] --
return the limit most recent messages.
- online_users(room_id) -> list[str] --
return currently joined users.
python
from dataclasses import dataclass
from datetime import datetime
@dataclass
class Message:
id: int
user_id: str
room_id: str
text: str
timestamp: datetime
class ChatServer:
...
Example:
server.create_room("general")
server.join_room("alice", "general")
server.send_message("alice", "general", "hello")
server.get_history("general") -> [Message(...)]
Follow-ups
1. get_history must be fast even with millions of messages. What storage structure and index would you use?
2. A user disconnects without calling leave_room. How do you detect and clean up stale presence?
3. How would you fan out a message to 10,000 users in the same room with low latency?
4. Add read receipts: track which users have seen each message up to which message id.
About This Question
This is a reported interview question from a discord interview during the phone round.