LOAD-BEARINGfree
Architecture labTier 13 · unit 4 of 31

Chat messaging

One-to-one and group messaging with delivery receipts, offline delivery, and permanent history. Clients hold live connections when the app is open and get push notifications when it is not.

Envelope50M concurrent connections · delivery p99 < 500 ms · full history

What the design must do

  • Persistent connection per online client
  • Messages durable before acknowledgement
  • Offline recipients get a push notification
  • Locate which gateway holds a given user

The worked envelope

Assumed. 50M concurrent connections, 40 messages sent per active user per day, groups averaging 20 members, history kept forever.

Worked envelope
Memory per socketkernel buffers + app state ≈ 20 KB
Connection RAM50M × 20 KB = 1 TB, fleet-wide
Boxes~500k connections/box → ~100 boxes, 150 with headroom
Messages50M × 40 = 2B/day ≈ 23k/s, peak ~70k/s
Deliveriesgroup fan-out ~5× ≈ 350k/s at peak
Storage2B/day × 300 B = 600 GB/day = 220 TB/yr
Egress350k/s × 300 B ≈ 105 MB/s

What the numbers decide. One terabyte of RAM exists purely to hold sockets that are idle almost all the time. That is the defining cost of this system, and it is why the connection layer must be its own tier: it scales on concurrency, while the message layer scales on throughput, and 23k messages a second against 50M connections means the average socket is silent for half an hour at a time.

Bind those two jobs into one service and you buy RAM to add CPU. Separate them and the stateless message path scales independently, at the price of needing a registry to answer "which of my 150 gateways is user X attached to right now".

The decisions, and what each one costs

A dedicated connection gateway tier, separate from message handling

Because
1 TB of RAM is bought for concurrency while 23k msg/s is bought for CPU; fusing them means scaling the expensive axis to get the cheap one
The cost
A routing problem you did not previously have: every delivery needs to find the right gateway
Rejected
Handling sockets in the application tier, which makes every deploy drop 50M connections

A presence registry mapping user to gateway, in memory with a short TTL

Because
Delivery has to find one box out of 150 in single-digit milliseconds, and the mapping changes on every reconnect
The cost
A stale entry sends a message to the wrong gateway; entries must expire and be re-asserted on heartbeat
Rejected
Broadcasting each message to all gateways — simple, and 150× the internal traffic

Wide-column store partitioned by conversation, clustered by time

Because
220 TB/yr with the dominant read being "last 50 messages in this conversation" is a range scan on one partition
The cost
Cross-conversation queries — search, unread counts across chats — need separate derived structures
Rejected
A relational store, where 220 TB/yr forces sharding and the shard key ends up being conversation anyway

Client-generated message ids, server-side dedup

Because
Mobile networks make retries routine, and a duplicate message is visible to the user in a way a duplicate read never is
The cost
You must trust and validate a client-supplied id, and store it long enough to catch a late retry
Rejected
Server-assigned ids only, which cannot tell a retry from a genuine second message

Components in the reference design

Client
Browser or mobile app
Load Balancer
L7 routing, TLS termination, health checks
WS Gateway
Holds persistent client connections
NoSQL Store
Wide-column or document, horizontal scale
Cache
Redis / Memcached, sub-ms lookups
Queue
Work distribution, one consumer per message
Push Service
APNs / FCM delivery

What not to draw

  • CDN — A CDN caches shared content. Every message here is private to two parties and read once.

The reference design

Connection layer. WebSocket gateways hold the live connections. They are stateful, which makes them the hardest part of the system: deploys drop connections, so clients need reconnect-with-backoff and a resume protocol, and the load balancer must handle long-lived connections rather than short requests.

The routing problem. User A is connected to gateway 7. User B sends A a message and lands on gateway 22. Gateway 22 must find gateway 7. Keep a user_id → gateway_id registry in Redis with a TTL refreshed by heartbeat, then either call gateway 7 directly or publish to a channel it subscribes to. This registry is the piece candidates most often forget.

Ordering. Server-assigned sequence numbers per conversation, not client timestamps — client clocks are wrong and adversarial. The client sorts by sequence and can detect gaps to request a resend.

Storage. Wide-column, partitioned by conversation ID and clustered by sequence descending. That layout makes "last 50 messages in this conversation" a single contiguous read, which is the only query that matters at volume. Message volume is enormous and append-only, so an LSM engine is the right fit.

Offline path. If the registry has no live connection for the recipient, the message is persisted and a push notification is queued through APNs or FCM. On reconnect the client sends its last known sequence number and pulls the gap.

Group messages are fan-out: one write to the conversation, then N deliveries. Groups above a few hundred members should switch to pull-on-open rather than push-to-all, for the same reason feeds do.