01

Requirements & scope

Problem Statement & Requirements

Functional Requirements

  • 1:1 messaging — send and receive text messages between two users in real-time
  • Group messaging — support group chats with up to 500 members (Slack-style) or 1024 (WhatsApp-style)
  • Online/offline presence — show whether a user is online, offline, or "last seen"
  • Message delivery status — sent, delivered, read (double/blue checkmarks)
  • Push notifications — notify offline users of new messages
  • Media sharing — images, videos, documents (up to 100 MB)
  • Message history — persistent storage, searchable, sync across devices
  • End-to-end encryption (E2E) — messages encrypted on sender, decrypted only by recipient

Non-Functional Requirements

  • Low latency — message delivery < 100 ms (same region), < 300 ms (cross-region)
  • High availability — 99.99% uptime (< 52 min downtime/year)
  • Ordering — messages within a conversation must be displayed in order
  • Durability — no message loss once server acknowledges
  • Scalability — support 500M+ daily active users, 100B+ messages/day
  • Multi-device sync — seamless experience across phone, web, desktop

Out of Scope

  • Voice/video calling (that's a separate WebRTC design)
  • Stories/status updates
  • Payment integration
  • Bots / slash commands (Slack-specific)
02

Scale estimations

Scale Estimations

Users & Traffic

MetricValue
Daily Active Users (DAU)500M
Average messages sent per user per day40
Total messages per day500M × 40 = 20B
Messages per second (avg)20B / 86400 = ~231K msg/s
Peak messages per second~700K msg/s (3x average)
Average concurrent connections~150M (30% of DAU)

Message Sizes

MetricValue
Average text message200 bytes
With metadata (sender, timestamp, IDs, status)500 bytes
Media messages (pointer only, media stored separately)500 bytes + media URL
Average message with encryption overhead~600 bytes

Storage

MetricValue
Text storage per day20B × 600 bytes = ~12 TB/day
Text storage per year12 TB × 365 = ~4.4 PB/year
Media storage per day (20% of messages have media)4B × 500 KB avg = ~2 PB/day
RetentionText: forever; Media: configurable

Network

MetricValue
Incoming bandwidth (messages)231K × 600 bytes = ~139 MB/s
Outgoing bandwidth (fan-out)~278 MB/s (avg 2 recipients per msg including 1:1)
WebSocket connections (concurrent)~150M
WebSocket servers needed (50K conn/server)~3,000 servers
03

Layered architecture

Phase 1 of 4 · Client & edge

Start with the entry points

First, define who uses the system and where requests enter. This is the boundary of the design, not yet a complete request path.

Chat clients
Assign stable message IDs and keep a local pending state until acknowledgement.
WebSocket gateway
Maintain bidirectional connections and route a user to the gateway holding their session.
Architecture after phase 1. Includes Chat clients, WebSocket gateway. Chat clients connects to WebSocket gateway.
Phase 1 — Start with Chat clients, WebSocket gateway.SVGSVGEditable diagramEditable diagram

This first layer defines the system boundary. The next chapters add application logic and data dependencies. After examining the request paths and tradeoffs, we will add operational safeguards and bring the complete architecture together.

04

API & contracts

Phase 2 of 4 · Application & compute

Add the application logic

Keep the entry points and add the services that do the work. Give each service a clear responsibility before defining its contracts. Storage and background dependencies come next.

Message service
Validate conversation membership and assign ordering within the conversation, not globally.
Push worker
Use push notifications for offline users; the message store remains the source of truth.
Architecture after phase 2. Includes Chat clients, WebSocket gateway, Message service, Push worker. Chat clients connects to WebSocket gateway. WebSocket gateway connects to Message service.
Phase 2 — Added Message service, Push worker. Earlier layers remain in place.SVGSVGEditable diagramEditable diagram

Communication Protocol — WebSocket Deep Dive

Why WebSocket Over HTTP?

Why WebSocket Over HTTP?
Why WebSocket Over HTTP?SVGSVGEditable diagramEditable diagram

WebSocket Connection Lifecycle

WebSocket Connection Lifecycle
WebSocket Connection LifecycleSVGSVGEditable diagramEditable diagram
05

Data model

Phase 3 of 4 · Data & async work

Connect data and background work

The services now need their dependencies: durable state, fast lookups, or work that continues outside a request. Separate these responsibilities rather than treating every component as a database.

Message queue
Buffer delivery work so a slow recipient or failed gateway does not block the sender.
Message store
Store messages durably and expose cursor-based history for reconnect and multi-device sync.
Presence store
Treat presence as soft state that expires when a client stops sending heartbeats.
Architecture after phase 3. Includes Chat clients, WebSocket gateway, Message service, Message queue, Message store, Presence store, Push worker. Chat clients connects to WebSocket gateway. WebSocket gateway connects to Message service. Message service connects to Message queue. Message service connects to Message store. WebSocket gateway connects to Presence store. Message queue connects to Push worker.
Phase 3 — Added Message queue, Message store, Presence store. Earlier layers remain in place.SVGSVGEditable diagramEditable diagram

Data Model

Message Table (Cassandra)

Message Table (Cassandra)
Message Table (Cassandra)SVGSVGEditable diagramEditable diagram

Conversation Table

Conversation Table
Conversation TableSVGSVGEditable diagramEditable diagram

User Conversation Index (for "list my chats")

User Conversation Index (for "list my chats")
User Conversation Index (for "list my chats")SVGSVGEditable diagramEditable diagram
06

Core design decisions

Message Ordering & IDs

Why Not Auto-Increment IDs?

Why Not Auto-Increment IDs?
Why Not Auto-Increment IDs?SVGSVGEditable diagramEditable diagram

Message Ordering Guarantee

Message Ordering Guarantee
Message Ordering GuaranteeSVGSVGEditable diagramEditable diagram
07

Request flows

Message Flow Diagrams

1:1 Message — Both Users Online

1:1 Message — Both Users Online
1:1 Message — Both Users OnlineWide diagram — scroll horizontally.SVGSVGEditable diagramEditable diagram

1:1 Message — Recipient Offline

1:1 Message — Recipient Offline
1:1 Message — Recipient OfflineWide diagram — scroll horizontally.SVGSVGEditable diagramEditable diagram

Group Message Flow

Group Message Flow
Group Message FlowWide diagram — scroll horizontally.SVGSVGEditable diagramEditable diagram
08

Performance & caching

Keep live connection routing separate from message history. A cache can tell a gateway where an online device is connected, but a missing cache entry must not erase an accepted message. Fetch history in bounded pages using a stable conversation cursor, and coalesce noisy presence updates rather than treating every heartbeat like durable chat content.

09

Advanced design

Presence (Online/Offline Status)

Presence Architecture

Presence Architecture
Presence ArchitectureSVGSVGEditable diagramEditable diagram

Presence at Scale — The Problem

Presence at Scale — The Problem
Presence at Scale — The ProblemSVGSVGEditable diagramEditable diagram

End-to-End Encryption (E2E)

Signal Protocol (used by WhatsApp)

Signal Protocol (used by WhatsApp)
Signal Protocol (used by WhatsApp)SVGSVGEditable diagramEditable diagram

E2E Encryption Flow

E2E Encryption Flow
E2E Encryption FlowSVGSVGEditable diagramEditable diagram

Group E2E Encryption

Group E2E Encryption
Group E2E EncryptionSVGSVGEditable diagramEditable diagram

Message Queue & Delivery Guarantees

Kafka as Message Bus

Kafka as Message Bus
Kafka as Message BusSVGSVGEditable diagramEditable diagram

Media Handling

Media Handling
Media HandlingSVGSVGEditable diagramEditable diagram

Multi-Device Sync

Multi-Device Sync
Multi-Device SyncSVGSVGEditable diagramEditable diagram

Chat Search

Chat Search
Chat SearchSVGSVGEditable diagramEditable diagram
10

Edge cases

Handling Edge Cases

Message Delivery Reliability

Message Delivery Reliability
Message Delivery ReliabilitySVGSVGEditable diagramEditable diagram

WebSocket Connection Failure

WebSocket Connection Failure
WebSocket Connection FailureSVGSVGEditable diagramEditable diagram
11

Tradeoffs

Tradeoffs & Design Decisions Summary

DecisionOption AOption BChosenWhy
ProtocolHTTP Long PollingWebSocketWebSocketBidirectional, low overhead, real-time push
Message DBMySQL (sharded)CassandraCassandraWrite-heavy (20B/day), partition by conversation, linear scaling
Message QueueRedis Pub/SubKafkaKafkaDurability, replay, consumer groups, ordering per partition
Presence StoreDatabaseRedis (TTL)RedisIn-memory speed, TTL auto-expiration, pub/sub for updates
Message IDsUUID v4Snowflake IDSnowflakeTime-sortable, compact 64-bit, no coordination
DeliveryPush onlyPush + offline queuePush + queueGuaranteed delivery even for offline users
EncryptionTLS only (server-side)E2E (Signal Protocol)E2EPrivacy — server never sees plaintext
Group encryptionN×encrypt per messageSender KeySender KeyO(1) encryption per message instead of O(N)
Presence fan-outPush to all contactsHybrid (push active + pull on demand)HybridBounded fan-out, scales to 500M users
Multi-devicePhone-primaryServer-primary with per-device keysServer-primaryAll devices work independently
Media uploadThrough API serverDirect to S3 (presigned URL)Direct S3Offloads bandwidth from API servers
SearchServer-side ElasticsearchOn-device searchDepends on E2EE2E → device only; no E2E → Elasticsearch
Redirect301 vs 302 for linksN/AN/AN/A
12

Reliability & fault tolerance

Phase 4 of 4 · Operations & resilience

Add operational safeguards

With the request paths and tradeoffs established, add the controls that help detect trouble and keep the system operating. The final diagram retains every layer introduced so far.

Delivery telemetry
Track accepted, delivered, and read states separately. Expect duplicate delivery and deduplicate by ID.
Architecture after phase 4. Includes Chat clients, WebSocket gateway, Message service, Message queue, Message store, Presence store, Push worker, Delivery telemetry. Chat clients connects to WebSocket gateway. WebSocket gateway connects to Message service. Message service connects to Message queue. Message service connects to Message store. WebSocket gateway connects to Presence store. Message queue connects to Push worker. Message store connects to Delivery telemetry.
Phase 4 — Added Delivery telemetry. Earlier layers remain in place.SVGSVGEditable diagramEditable diagram

A gateway can disappear after storing a message but before replying to its sender. The sender retries with the same message ID, and the service returns the existing result. On reconnect, devices resume from a known position in durable history. Delivery acknowledgements should advance monotonically even when old acknowledgements arrive late.

13

Production architecture

High-Level Architecture

High-Level Architecture
High-Level ArchitectureSVGSVGEditable diagramEditable diagram

Detailed Component Architecture

Detailed Component Architecture
Detailed Component ArchitectureWide diagram — scroll horizontally.SVGSVGEditable diagramEditable diagram

Production Architecture

Production Architecture
Production ArchitectureWide diagram — scroll horizontally.SVGSVGEditable diagramEditable diagram
14

Further exploration

Take a conversation with three devices belonging to the same person. Read a message on one device, disconnect another, and send from the third. Decide which state belongs to the user, which belongs to a device, and how each catches up without downloading the entire conversation.

15

Interview playbook

Interview Tips

  1. Start with protocol choice — "For real-time messaging, WebSocket is the clear winner over polling." Briefly explain why, then move on.

  2. Draw the 1:1 message flow first — It's the simplest. Show: sender → WS gateway → message service → persist + Kafka → delivery worker → recipient's WS gateway → recipient.

  3. Address "what if the recipient is offline?" early — This is the follow-up every interviewer asks. Show the offline queue + push notification path.

  4. Presence is a trap topic — Don't spend too long on it. Mention the fan-out problem, say "hybrid pull + push" and move on unless asked to deep-dive.

  5. Group messaging is just fan-out — "A group message is a 1:1 message sent to each member. The interesting part is how to fan out efficiently" → Kafka with conversation-level partitioning.

  6. E2E encryption shows depth — Mention Signal Protocol, X3DH, Double Ratchet. You don't need to derive the math — just show you understand why keys rotate per message (forward secrecy).

  7. Message ordering matters — Explain Snowflake IDs and why Kafka partitioning by conversation_id guarantees FIFO within a conversation.

  8. Multi-device sync is a common follow-up — "Sync cursor per device. On reconnect, replay from cursor."

  9. Don't forget media — "Media goes directly to S3 via presigned URL. Message contains only a pointer. CDN for delivery." This 3-sentence answer covers it.

  10. Scale numbers impress — "500M DAU × 40 messages = 20B messages/day = 231K messages/second. We need ~3,000 WebSocket servers at 50K connections each."