System DesignAdvanced22 min

Case study: real-time chat

Combine persistent connections, ordering, fan-out and offline delivery in one design.

See it on the map

Clients hold a persistent connection, usually a WebSocket, to a gateway server. The gateway is stateful because it knows which user is connected where, so a presence or routing store maps user to gateway, and messages for a user are forwarded to the right node.

Ordering matters within a conversation, not globally. Assign each message a per-conversation sequence number and shard conversations by id, so one partition owns the order. Clients use the sequence to detect gaps and ask for missing messages.

Fan-out for a small group is a loop over members. For huge channels, write once and let readers pull. Always persist before acknowledging, queue pushes for offline users and send a push notification, and make send idempotent with a client-generated message id so retries do not duplicate messages.

Key points

  • Gateways are stateful, so you need a user-to-gateway routing map.
  • Order per conversation with a sequence number, not a global clock.
  • Client message ids make sends idempotent across reconnects.
  • Small groups push, huge channels pull.

Answer these out loud

  1. 1A gateway node dies with 100,000 connected users. Describe what clients do and what the system does.
  2. 2How do read receipts and typing indicators differ in durability needs from the messages themselves?

Use this from an agent

Any MCP client, including Grok, can read this lesson. See how to connect.

REST
curl https://engineeros-delta.vercel.app/api/v1/topics/case-realtime-chat