skip to content
jaeaeichsysdes

Design a Real-Time Chat System

WhatsApp / Discord at 100M DAU and 10M concurrent WebSockets: L4 stateful gateways, user-keyed multi-device routing, DynamoDB cursor pagination, watermark read receipts, and S3 presigned media.

The whiteboard

Trace live chat (L4), history & presence (L7), and media (S3/CDN) below — combining Distributed Unique IDs, Queues vs Event Logs, and Concurrency & Failure Modes.

whiteboard · press 1–4 to trace flows

LIVE CHAT (L4 · 10M WEBSOCKETS)HISTORY & PRESENCE (L7 REST)MEDIA PIPELINE (DIRECT S3)fanoutofflinepersistRESTpull1. presign URL → 2. direct PUT to S3serveClient AWS + heartbeatsclient_msg_idL4 LBTCP balance10M socketsWS Fleet~150 stateful nodesSnowflake IDsMQ Channels1 queue / WS nodemulti-deviceFCM / APNsoffline pushfallbackRedis Conn Mapuser → {dev: ws_srv}Redis Presence30s beat · 60s TTLL7 GatewayREST auth / routehistory & presignChat REST APIcursor / syncpull presenceDynamoDBPK: group_idSK: SnowflakeS3 Mediapresigned PUT1h tmp/ cleanupCDN Edgemedia downloadcached globally

Full chat architecture: L4 balances 10M persistent WebSockets; L7 serves REST history/presence; media bypasses app servers via presigned S3 + CDN.Separating stateful sockets from stateless HTTP and binary uploads keeps each tier cheap to scale.

Scale & APIs

10M conns

~150 WS nodes (50–100K/node)

500K msg/s

~50 MB/s · ~5 TB/day text

< 200ms

end-to-end live delivery

DynamoDB:
Messages PK=group_id, SK=message_id (Snowflake) { sender_id, text, media_s3_path? }
Watermarks PK=user_id, SK=group_id { last_delivered_id, last_read_id }
WebSocket (/ws via L4):
send -> { group_id, client_msg_id, text } <- persisted { message_id }
deliver <- { group_id, message_id, text } -> ack / read { group_id, message_id }
REST (via L7):
GET /messages/groups/:id?before=:cursor&limit=50 -> Messages[]
GET /users/:id/presence -> { status, last_seen }
POST /media/presign -> { upload_url, media_id }

How it works

1. L4 WebSockets & user-keyed multi-device routing

  • L4 vs L7 split: L4 LB forwards 10M mostly-idle TCP sockets cheaply to ~150 stateful WS servers, while L7 Gateway handles stateless REST auth and routing.
  • Multi-device connection map: Redis stores one hash per user (conn:{user_id} → { device_id: ws_server_id }); on send, the WS server fans out to every online device’s MQ channel and falls back to FCM/APNs when offline.

2. Time-sorted storage & watermark receipts

  • 1:1 as a 2-person group: Modeling all chats uniformly as (PK: group_id, SK: Snowflake) enables O(log N) cursor pagination (before=:message_id) and clean offline catch-up (GET /sync?after=last_seen_id).
  • High-water marks: Storing one (user_id, group_id) → last_read_id pointer avoids writing N receipt rows per message in large groups because Snowflake IDs are k-sorted in time.

3. Flake-tolerant presence & direct media uploads

  • 30s heartbeat / 60s TTL: Clients refresh presence:{user_id} over their existing socket every 30s; the 60s grace window absorbs mobile blips, and clients fetch presence lazily (pull-on-view).
  • Zero media through WS: Clients upload straight to S3 tmp/ via presigned URLs, message send commits the object out of tmp/, CDN serves downloads, and a 1-hour S3 lifecycle rule reaps abandoned uploads.

lesson

Interview differentiator: Attach a client-generated client_msg_id (UUID v4) to every WebSocket send for idempotency — if a flaky mobile connection drops before receiving the persisted ack and retries, DynamoDB deduplicates the retry instead of double-posting.

Check yourself

interactive · stress-test this chat architecture against classic interview probes

01 · Why L4 for WebSockets and L7 for REST?

10M long-lived sockets · memory/CPU per conn · routing

Your architecture splits traffic into an L4 load balancer for WebSocket servers and an L7 gateway for history/media REST endpoints. Why not put all 10M WebSockets behind a single L7 proxy?

02 · User online on phone AND laptop

multi-device · Redis conn map · MQ server channels

Alice is connected on her phone (WS Server 12) and laptop (WS Server 87). Bob sends her a message. How does your routing layer deliver it to both devices?

03 · Why Snowflake SK makes cursor pagination fast

DynamoDB · pk: group_id · sk: message_id

A user scrolls up in a group with 500,000 messages. Why is GET /messages?before=:message_id dramatically faster than OFFSET 100000?

esc
⌘B sidebar[ ] prev/next1–5 flowsc copyt theme