Skip to content
SD-2 · Back to the write-up

Design a Chat App

Keep a WebSocket open to every phone, give each chat one ordered log, and retry each message until the phone confirms it.

Follow a request

Clients
Edge
Services
Data
PhonesAlice and Bob
Media + CDNEncrypted files
GatewaysHold WebSockets
Push serviceApple, Google
RegistryDevice → gateway
Chat serversStateless, many
Offline inboxUntil acked
Ordered logPartition per chat
Message storeSharded by chat
1chat → registry · where is Bob?For each member of the chat, the server looks up the gateways holding their devices.1 / 6

The numbers, at a glance

Every message sent……is delivered to about 5 phones
1 send ≈ 23K/s5 deliveries ≈ 115K/s
History adds up2 billion messages a day × 200 bytes
Polling is mostly wastedA poll every 2 s, about 200 messages a day
That is why phones keep a connection open and the server pushes.

A message, from Alice to Bob

Bob is online. If he were not, the registry would say so and the message would go to his inbox.

Alice
Gateway A
Chat server
Ordered log
Registry
Gateway B
Bob
1 send a1f3
2 forward
3 append
4 seq 42
5 ack 42
6 ✓ sent
7 where is Bob?
8 gateway B
9 msg 42
10 msg 42
11 ack 42
12 ✓✓ delivered
RequestResponseAsync, does not block

How phones hear about new messages

The first decision, and the one the rest depends on.

Polling
Too wasteful
every 2 s
anything new? → no
anything new? → no
anything new? → msg 42
+ Plain HTTP.− A second of delay; 99.5% of polls are empty.
Long polling
Workable
request held open
msg 42 → reply
open a new request
+ Near real time over HTTP.− A new request after every message.
WebSocket
Our pick
one open connection
← msg 42→ ack 42
← msg 43
+ Instant, both ways, one connection.− Gateways hold millions of connections.

How it grows

Add a box only when a number forces you to. Highlighted boxes are new at each stage.

Stage 1 · ~1,000 phonesMake it work
Phones
Chat server
Database
Phones poll one server every 2 seconds. Fine for a demo.
Stage 2 · ~100,000 phonesPush, don’t poll
Phones
Gateways × N
Chat × NRegistry
Database
Open connections replace polls; a registry sends each message to one gateway.
Stage 3 · ~1M phonesOrder, never lose
Phones
Gateways × NPush service
Chat × NRegistryOffline inbox
Ordered logSharded store
One log partition per chat for order, an inbox for offline phones, sharded history.
Stage 4 · 10M phonesMedia, presence, devices
Phones + linked devices
Gateways × 334Push serviceMedia + CDN
Chat × NRegistryPresenceOffline inbox
Ordered logSharded store
334 gateways; photos bypass them through object storage and a CDN; presence lives only in memory.
Was this walkthrough useful?Your vote tells us what to improve next.