FullStack AI Hub
Studio
System Design · 09. Whole Systems
13 min
10 steps
Intermediate

Design a Chat System

Architect a 50M-DAU WhatsApp/Slack-grade messaging platform with stateful WebSocket gateways, Snowflake IDs, wide-column history, presence heartbeats, and offline push.

System Design09. Whole SystemsLesson 4 of 4
13 minIntermediate10 steps

Design a Chat System

Architect a 50M-DAU WhatsApp/Slack-grade messaging platform with stateful WebSocket gateways, Snowflake IDs, wide-column history, presence heartbeats, and offline push.

DAILY USERS
50M DAU
OPEN SOCKETS
10M Live
PEAK MSGS
70K / s
DELIVERY P95
< 100 ms
WSS FramesPersistIf Offline50M DAUChat WSFleet42%< 100msMessage Store38%LSM Wide-Col0Offline Push22%Wake sleeping50M DAU Capacity MathMessages50M × 40 = 2B/day (~70K peak)Daily Text2B × 100B ≈ 200 GB/daySockets10M ÷ 150K/box ≈ 67 WS nodes
live WS frame / HTTP
message persist / cursor
instant push delivery
cross-node relay / push
heartbeat / session lookup
gateway drop / retry
In This LessonStep 1 of 10
What You Will Master
  • ✓Split stateful WebSocket messaging from stateless HTTP APIs and route cross-node frames via Redis Sessions
  • ✓Generate time-ordered 64-bit Snowflake IDs and store 2B daily messages in bucketed wide-column storage
  • ✓Scale presence heartbeats with debounced TTLs and switch small groups (push) vs mega-channels (pull)
  • ✓Support offline APNs/FCM push, O(1) per-device read cursors, and direct-to-S3 media uploads

Architectural Trade-Off Comparison Matrix

PatternBest ForKey Trade-Off
Stateful WS + Stateless HTTPSub-100 ms bi-directional chat frames while keeping auth, profiles & heavy media off socketsStateful WS gateways require service discovery, sticky sockets, and graceful draining
64-Bit Snowflake IDsLock-free, globally unique, chronologically sortable chat message IDs across distributed gatewaysRequires NTP clock-drift protection; gives k-ordering across separate machines
Cassandra ((channel_id, month), msg_id DESC)2B write-heavy daily messages with 1-seek paginated scrollback and bounded partition sizesFull-text message search requires an asynchronous inverted search index via CDC
Hybrid Group Fan-Out (Push ≤500 / Pull >500)Instant delivery for team chats without 50,000× write amplification on supergroupsClients must support both live inbox pushes and cursor-based channel log fetches

Step-by-Step Architectural Breakdown (10 Steps)

Full architectural walkthrough transcript and state transitions for Design a Chat System.

STEP 01 · SETUPJump to step →

Scale targets: 50M DAU, 10M sockets & <100 ms delivery

Serving **50M DAU** averaging 40 messages/day means **2B messages/day** (`~70K msg/s` peak) and **10 million concurrent persistent connections**.

Unlike read-heavy feeds or URL shorteners, chat is **1:1 write-and-read heavy** with tight latency expectations (`< 100 ms`), strict message ordering, multi-device sync, online indicators, and offline push.

idea:One tuned gateway holds ~150K idle WebSockets in RAM—so 10M live devices require ~67 aligned stateful gateways plus fast cross-node routing.

10M Concurrent SocketsWrite-Heavy Chat MathSub-100ms SLA
STEP 02 · SOLUTIONJump to step →

Split transport: persistent WebSockets + stateless HTTP

Never push login flows, profile edits, and 20 MB videos down your WebSocket tunnel—they bloat connection RAM and bypass CDN caching.

Split cleanly: **Stateless HTTP/2 REST** handles auth, history pagination, and presigned media URLs, while **Persistent WebSockets** carry tiny real-time chat frames, typing pings, and read acks.

good:Keep WebSocket frames lightweight (~250 bytes) so every gateway comfortably sustains 150K+ persistent sockets.

Dual TransportPersistent WebSocketsStateless REST Separation
STEP 03 · TECHNIQUEJump to step →

Cross-gateway routing with Redis Session Registry

Alice sits on `WS Gateway A` while Bob sits on `WS Gateway C`. How does Gateway A reach Bob across 67 servers without broadcasting to everyone?

Each socket connect registers `user_id → gateway_id` in a **Redis Session Registry**. Gateway A looks up `bob → ws-c` in `1 ms` and relays the frame directly over an internal Pub/Sub / gRPC mesh.

idea:Before dialing a WebSocket, apps ask Service Discovery for the nearest, least-loaded gateway—keeping socket counts balanced across the fleet.

Session RegistryService DiscoveryCross-Gateway Pub/Sub
STEP 04 · TECHNIQUEJump to step →

Strictly sortable messages with 64-bit Snowflake IDs

UUIDv4 is random (bad for sorting and B-Tree/LSM locality) and phone clocks can be minutes off. How do 67 chat servers stamp globally unique, chronologically ordered IDs with **zero central lock**?

Use **64-bit Snowflake IDs**: `41 bits` millisecond timestamp + `10 bits` machine ID + `12 bits` sequence (`4,096 IDs/ms per node`). Every conversation sorts cleanly by `message_id` alone!

good:Order messages per channel using server-minted Snowflake IDs—never trust client device timestamps for conversation history.

64-Bit Snowflake IDsLock-Free MintingMonotonic Sort Order
STEP 05 · SOLUTIONJump to step →

Store 2B messages/day in a wide-column LSM cluster

Chat history is append-heavy writes plus recent-page scrollback (`last 50 messages of channel X`). A wide-column LSM store (`Cassandra` / `ScyllaDB`) turns 70K writes/s into blazing sequential disk appends.

Model primary key `((channel_id, bucket_month), message_id DESC)` so every active channel reads its latest page in **one disk seek**, while monthly bucketing prevents multi-year channels from creating giant unbounded partitions.

idea:Add `bucket_month` (`YYYY_MM`) to the partition key so a 5-year Slack channel never grows into a single 10-million-row hot partition.

Wide-Column LSMTime-Bucketed PartitionsPaginated Scrollback
STEP 06 · PROBLEMJump to step →

Online presence: heartbeats, TTLs & flap debounce

Broadcasting `online/offline` to 500 friends every time a commuter’s phone drops in a subway tunnel creates a massive **presence fan-out storm**.

Instead, clients send a tiny heartbeat every `25 s` refreshing a `40 s Redis TTL`. Wait `15 s` before declaring a user offline and push updates only to friends **actively viewing the roster**.

watch:Never push presence diffs to all 50,000 members of a Discord/Slack server—lazily fetch online dots only for the ~30 visible avatars in the viewport.

Heartbeat TTLsPresence DebouncingViewport-Scoped Fan-Out
STEP 07 · TRADE-OFFJump to step →

Small group push vs supergroup pull fan-out

In a **20-person team chat**, pushing a frame pointer to every online member’s WebSocket takes `< 5 ms` (**Fan-out on Write**).

In a **50,000-member announcement channel**, copying 50K rows per message explodes your cluster! Above `~500 members`, switch to **Single-Write Channel Logs** streamed only to active viewers.

idea:Hybrid fan-out combines the best of both worlds: instant push for small groups (≤ 500) and 1× write channel logs for massive supergroups.

Hybrid Group Fan-OutPush vs Pull ThresholdSupergroup Scaling
STEP 08 · SOLUTIONJump to step →

Offline delivery: APNs/FCM push & unread cursors

When `Session Registry` shows Bob has no live socket, `Message Service` still writes durably to Cassandra and queues a banner payload onto **Push Queue → APNs / FCM**.

Instead of storing `is_read = true` on billions of messages, store one tiny cursor per `(user_id, channel_id)`: **`last_read_message_id`**. Marking 500 messages read is a single `O(1)` write!

good:Per-channel read cursors (`last_read_message_id`) turn unread badge counts and reconnect catch-up into instant sorted range scans.

APNs / FCM Push QueueO(1) Unread CursorsReconnect Catch-Up
STEP 09 · TECHNIQUEJump to step →

Multi-device sync & direct-to-S3 media uploads

Users run chat on phone, laptop, and tablet simultaneously. Each device tracks its own `device_sync_cursor`—reading a thread on laptop fans out a tiny `read_receipt` event to clear badges on your phone.

For photos, voice notes, and videos, apps request a **Presigned S3 URL**, upload directly to Object Storage, and send only the tiny `CDN media_url` + thumbnail hash through the WebSocket.

good:Direct S3 + CDN offloading slashes WebSocket gateway bandwidth by 94% while serving global photos at edge speeds.

Multi-Device CursorsDirect S3 Presigned MediaBlurHash Thumbnails
STEP 10 · RECAPJump to step →

Full 50M-DAU chat architecture end-to-end

Zooming out across the complete platform: **Aligned WS Gateways** hold 10M persistent connections, **Redis Sessions & Presence** routes cross-node frames in `1 ms`, **Snowflake IDs + Bucketed Cassandra** persist 2B daily messages cleanly, **Push Queue** wakes offline phones, and **S3 + CDN** keeps heavy media off the real-time path.

good:Flagship Interview Summary: WS + HTTP split · Redis Session Registry · 64-bit Snowflake IDs · Bucketed Cassandra LSM · Debounced presence · Push ≤500 / Pull >500 · Per-device read cursors.

WhatsApp / Slack ArchitectureEnd-to-End MessagingStateful + LSM Scaling

Related Production Deep-Dives & Simulators

Included In Free Course
Free · Verifiable Credential

FS-102LLM Systems Foundations

Build a connected mental model from tokens through retrieval evaluation security and operations.

24 concepts~18h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.