Design WhatsApp: Real-Time Chat System Design
Step 7 β Persist Chat History
Users scroll back months of chat. The Database must store messages durably and make fetching recent history fast, even at petabyte scale.
Request Flow
1
Write-ahead: DB first, always
Every message is written to the Database BEFORE the sender's ACK is sent. The write is the source of truth. Queue and delivery are derived from it.
// Order matters: 1. INSERT INTO messages β first, always 2. queue.push(msg) β then enqueue 3. ACK to sender β only after DB commit // If service crashes between 2-3: replay from DB
2
Fetch chat history on open
When User B opens a chat, the app fetches the last N messages from the Database via a cursor-based paginated query.
GET /messages?conversation=A_B&cursor=last_id&limit=50 β SELECT * FROM messages WHERE conversation_id = "A_B" AND message_id > :cursor ORDER BY message_id DESC LIMIT 50
Key Insight
The DB is the single source of truth. Queue and WebSocket delivery can fail and be replayed from the DB. Never ACK a message to the sender before it is committed to durable storage.
Step 7 of 7
