Book a 30-min callBook a call

System design: a chat app with real-time messaging, presence and history

How to design a chat app: WebSocket gateways, pub/sub routing, sequence numbers per conversation, receipts, presence with TTLs, offline push and group fan-out.

Two phones linked to two gateway boxes, a pub/sub bar joining the gateways, and a chat service box writing into a database cylinder split into partitions.
Written by
BYD Tech
Published
Topic
Deep dives
Reading time
14 min read

Questions people ask

WebSockets or server-sent events for a chat app?

WebSockets are the usual choice, because traffic flows both ways and one connection can carry messages, receipts, typing and presence. Server-sent events for the downstream plus ordinary HTTP requests for sending also work, and browsers reconnect an event stream automatically. Either way, the protocol on top, with sequence numbers and resync after a reconnect, matters more than the transport.

How do you keep messages in order in a group chat?

Let the server assign a sequence number per conversation when it stores each message, in the same transaction as the insert, and have every client sort by it. Client timestamps are for display only. A gap in the sequence tells a client it missed something and should fetch it.

How does a chat app know a user is online?

The gateway holding the user’s connection refreshes a presence key with a short TTL on every heartbeat. A clean disconnect deletes the key; a crash lets it expire. Presence is approximate by design, and it is sent only to clients that are currently showing that user.

Can the server read end-to-end encrypted messages?

Not the content: it stores and forwards ciphertext, and the keys stay on users’ devices. It still sees metadata such as who talks to whom, when, and how large the messages are, unless the design takes extra steps to hide it. Push notifications for encrypted chats should carry no message text.

Should messages be stored once or copied to every inbox?

Store each message once, in its conversation. What gets copied is small: an inbox row per member that points at the conversation and its latest activity. Small groups update those rows on every send; very large groups skip that and compute unread state when a member opens the app.

Building something like this?