In short
A chat app keeps a WebSocket open from every online device to a gateway. A new message goes to a chat service that checks membership, assigns the next sequence number for that conversation and stores the message, then fans it out through pub/sub to the gateways holding the other members’ connections. The stored history, partitioned by conversation and ordered by sequence, is the source of truth; real-time delivery is a fast path, and clients fill any gap by asking for everything after the last sequence they hold. Offline members get a push notification, and presence and typing are short-lived signals kept in memory with TTLs.
Key points
- Order messages by a sequence number per conversation, assigned by the server when it stores the message, never by client clocks.
- Give every message a client-generated id under a unique index, so a resend after a lost acknowledgment returns the original sequence number instead of a duplicate.
- Treat pub/sub as a fast path that can drop messages; the stored history is the truth, and clients catch up by asking for everything after their last sequence.
- Partition messages by conversation id and sort them by sequence, so opening a chat is one range read.
- Keep presence and typing out of the message log: heartbeats refresh a key with a TTL, and typing events are throttled, unsaved and allowed to drop.
- Fan out on write for small groups and on read for very large ones, and record receipts as read-up-to watermarks, not one flag per message per reader.
Requirements
| Requirement | What it means in practice |
|---|---|
| One-to-one and group chat | One model for both: a conversation with members. Groups add roles, invites and a size limit |
| Real-time delivery | A message reaches the open apps of online members at once, without polling |
| Ordering per conversation | Everyone in a conversation sees its messages in the same order |
| No loss, no duplicates | A message the server acknowledged is never lost; a resent message is stored once |
| Offline delivery | Messages wait for a device that is offline and arrive in order when it reconnects |
| Delivery and read receipts | Sent, delivered and read, per member, without a write per message per reader |
| History | Scroll back through a conversation on any device, page by page |
| Presence and typing | Online, last seen and “is typing”, all allowed to be approximate |
| Push for offline users | A notification on a phone whose app is closed, without duplicating the message pipeline |
Behind the list sits one split that drives the whole design. Messages, receipts and membership are durable: once acknowledged, they must survive any single failure. Presence and typing are ephemeral: they are useful for seconds, may be lost, and should never touch the main database. Most mistakes in chat systems come from treating one kind like the other.
The connection layer: WebSockets and gateways
Chat traffic flows both ways all the time, so the usual transport is a WebSocket. RFC 6455 opens it with an HTTP Upgrade request and then carries framed messages in both directions over one TCP connection. Server-sent events for the downstream plus ordinary HTTP requests for sending also work, and can be simpler behind some proxies; the trade-offs are in WebSockets vs server-sent events.
Connections end on gateway servers, a stateful tier whose only job is holding sockets: authenticate the upgrade, keep the connection alive, parse frames, and pass messages to and from the chat service. Keep business logic out of the gateways, so they can be redeployed by draining connections and a client can reconnect to any of them.
- Authenticate during the upgrade with a short-lived token, over TLS (
wss://). For browser clients, check theOriginheader; RFC 6455 describes it as the protection against cross-origin use of a WebSocket server by scripts on other sites. - Detect dead connections with heartbeats. RFC 6455 defines ping and pong control frames and notes a ping can serve as a keepalive, but the browser WebSocket API does not let page code send pings, so most apps also send a small application-level heartbeat.
- Reconnect with exponential backoff and jitter, so a gateway restart does not become a stampede of reconnects.
- Make reconnect a sync, not a fresh start: the client sends the last sequence number it holds for each recently active conversation, and the server returns what it missed.
Routing messages between gateways
Ana is connected to gateway 3 and Ben to gateway 7. When Ana sends, gateway 3 hands the message to the chat service, which stores it; then something has to get it to gateway 7. There are two common designs.
| Design | How it works | Trade-off |
|---|---|---|
| Pub/sub per user or conversation | Each gateway subscribes to channels for the users or open conversations it holds; the chat service publishes to them | Simple, and the broker does the fan-out; subscriptions churn with every connect and disconnect |
| Connection registry | A store maps each user id to the gateways holding that user’s connections; the chat service looks them up and sends to each gateway’s own channel | One subscription per gateway; the registry must expire entries when a gateway dies |
Either way, treat the real-time path as best effort. Redis Pub/Sub, a common choice, documents at-most-once delivery: a subscriber that is disconnected or failing when a message is published never gets it. That is acceptable only because the message was stored first, and the client will notice the gap in sequence numbers and fetch what it missed. If the broker itself must keep messages, use a log or a stream with at-least-once delivery and dedupe on the client. In a Redis cluster, sharded pub/sub keeps a channel’s messages within one shard instead of sending every message to every node.
Message IDs and ordering per conversation
Client clocks disagree, and two people can send in the same millisecond, so the order of a conversation is decided by the server. The simplest rule that works: each conversation has a counter, and storing a message assigns it the next value as its sequence number, in the same transaction as the insert. Clients sort by it, page by it and detect gaps with it. A client holding 41 that receives 43 knows 42 is missing and asks for it.
The second id comes from the client. Before sending, the app generates a random id, a UUID for example, shows the message as pending, and resends with the same id until it gets an acknowledgment. The server stores it under a unique index on conversation, sender and client id, so a resend after a lost acknowledgment returns the original sequence number instead of creating a second message. It is the idempotency-key pattern from idempotency and job queues, applied to a send button. The sketch below shows both ids in memory; the outputs in the comments are from running it.
class ConversationLog:
"""One sequence counter per conversation; retries are recognized by client id."""
def __init__(self):
self.last_seq = {} # conversation id -> last assigned sequence number
self.seen = {} # (conversation, sender, client message id) -> seq
self.messages = {} # conversation id -> list of (seq, sender, text)
def append(self, conv, sender, client_id, text):
key = (conv, sender, client_id)
if key in self.seen: # a resend: same answer, no new message
return self.seen[key], "duplicate"
seq = self.last_seq.get(conv, 0) + 1
self.last_seq[conv] = seq
self.seen[key] = seq
self.messages.setdefault(conv, []).append((seq, sender, text))
return seq, "stored"
def after(self, conv, seq): # what a reconnecting client missed
return [m for m in self.messages.get(conv, []) if m[0] > seq]
log = ConversationLog()
print(log.append("c1", "ana", "a-1", "hi")) # (1, 'stored')
print(log.append("c1", "ben", "b-1", "hey")) # (2, 'stored')
print(log.append("c1", "ana", "a-1", "hi")) # (1, 'duplicate')
print(log.append("c2", "ana", "a-2", "lunch?")) # (1, 'stored')
print(log.after("c1", 1)) # [(2, 'ben', 'hey')]In a relational database, the counter is a column on the conversation row: UPDATE conversations SET last_seq = last_seq + 1 WHERE id = :id RETURNING last_seq, then the insert, in one transaction. The row lock serializes sends within one conversation, which is the point, and it is also the limit: a very busy conversation is a single hot row. Routing each conversation to one owner node, chosen by consistent hashing over the conversation id, lets that node assign sequence numbers in memory and batch its writes; see consistent hashing and sharding. Ordering across conversations is not needed, and building it would cost far more than it is worth.
The message envelope, delivery states and offline push
Every frame on the socket carries a small envelope with a type, so one connection can carry messages, acknowledgments, receipts, typing and presence. Here is the exchange for one message, as JSON text.
client to server: send
{ "type": "message.send", "conversation_id": "c_81f2",
"client_msg_id": "4f9c2e1a-7b3d-4c55-9a0e-1d2f3b4c5d6e",
"body": { "kind": "text", "text": "Running late, start without me" },
"client_time": "2026-11-12T09:41:07Z" }
server to sender: stored, here is your place in the conversation
{ "type": "message.ack", "conversation_id": "c_81f2",
"client_msg_id": "4f9c2e1a-7b3d-4c55-9a0e-1d2f3b4c5d6e", "seq": 1042,
"server_time": "2026-11-12T09:41:07.312Z" }
server to the other members' devices
{ "type": "message.new", "conversation_id": "c_81f2", "seq": 1042,
"sender_id": "u_ana", "body": { "kind": "text", "text": "Running late, start without me" },
"server_time": "2026-11-12T09:41:07.312Z" }
recipient device to server: a receipt is a watermark, not a per-message flag
{ "type": "receipt", "conversation_id": "c_81f2", "status": "read", "up_to_seq": 1042 }| State | Set when | Shown as |
|---|---|---|
| Pending | The app has the message but no acknowledgment yet | A clock icon; resent on reconnect with the same client id |
| Sent | The server stored it and returned a sequence number | One check mark |
| Delivered | A recipient’s device received it and reported up to that sequence | Two check marks; in groups, tracked per member |
| Read | A recipient opened the conversation past that sequence | Colored check marks, or “Seen by 3” in a group |
Receipts are watermarks. A device reports “delivered up to 1042” and “read up to 1042”, and the server keeps two numbers per member per conversation, not a row per message per reader. The sender’s app compares each message’s sequence with the members’ watermarks. Receipts travel the same path as messages, can be coalesced, and only ever move forward.
When the chat service finds no live connection for a member, it queues a push notification. Collapse notifications per conversation, so ten messages update one notification instead of stacking ten; FCM’s collapse key does this, and its time to live drops a notification that is no longer worth showing. Respect mute settings, and treat the push as a hint: the app opens, connects and syncs from its last sequence, so the notification is never the only copy of a message. The pipeline behind it, with preferences, quiet hours and token cleanup, is in notification system design.
Storage: partition by conversation, sort by sequence
The dominant read is “the latest page of this conversation”, then “the page before that”. So store messages with the conversation id as the partition key and the sequence number as the sort key, and opening a chat is one range read from one place. In a wide-column store such as Apache Cassandra, the partition key keeps a conversation’s rows on the same set of replicas and the clustering column orders them within it. In PostgreSQL, a primary key of (conversation_id, seq), with hash partitioning by conversation id once the table is large, does the same.
| Table | Key | Holds |
|---|---|---|
messages | conversation id, seq | Sender, client id, type, body or attachment reference, server time, edit and delete markers |
conversations | conversation id | Type, title, last seq, time of the last message |
members | conversation id, user id | Role, joined at, delivered-up-to seq, read-up-to seq, muted |
user_conversations | user id, last activity | The inbox: one row per conversation the user belongs to, newest first |
devices | user id, device id | Push token, platform, last seen |
Very large or very old conversations make big partitions. Bucket them, for example with a partition key of conversation id plus month, so no partition grows without limit, and let the client page across buckets. Keep attachments out of the message table: upload them to object storage and store a reference, as in file upload system design. Model edits and deletes as new events that point at the original sequence, so every device converges on the same history.
Presence and typing indicators
Presence is ephemeral and approximate by design. Each gateway refreshes a key per connected user with a TTL on every heartbeat, for example a Redis SET with the EX option. On a clean disconnect, delete the key; if the gateway crashes, the key expires on its own and the user shows as offline a little later. Write last_seen to the database when a session ends, not on every heartbeat.
Do not broadcast presence to everyone who could see it. Send changes only to clients that are looking, such as the open conversation or the visible part of a contact list. Debounce flapping, since a phone moving between networks can disconnect and reconnect several times a minute, and let users hide their status.
Typing indicators are lighter still. The client sends typing when the user starts and at most every few seconds while they continue; the server relays it to the conversation’s online members and stores nothing. Receivers hide the indicator when no refresh arrives for a few seconds. It never gets a sequence number, never goes to offline members and never triggers a push. Losing one is harmless, which makes at-most-once pub/sub a good fit.
Large groups: fan-out on write or on read
For a one-to-one chat or a small group, fan-out on write is natural: storing a message also updates every member’s inbox row and pushes to every online member. In a group of thousands, or a broadcast channel, every message would mean thousands of inbox writes and receipts.
| Model | How it works | Good for | Cost |
|---|---|---|---|
| Fan-out on write | On send, update every member’s inbox and notify every member | One-to-one chats and small groups | Write work grows with group size on every message |
| Fan-out on read | Store the message once; a member’s app compares its read watermark with the conversation’s last seq when it loads | Large groups and channels | Reads do more work; unread counts are computed when asked for |
Most apps mix the two: fan-out on write below a size threshold, on read above it. Large groups change the product rules too: real-time delivery only to members who have the conversation open, unread badges computed lazily, read receipts aggregated or turned off, and notifications only for mentions. A busy large group also needs the single-owner sequencing described above, or its counter becomes the bottleneck.
Encryption, abuse and a capacity estimate
With end-to-end encryption, the server stores and forwards ciphertext it cannot read. The Signal Protocol’s published specifications are the usual reference. X3DH lets two parties agree on a shared secret while the recipient is offline, using an identity key, a signed prekey and one-time prekeys the recipient published to the server in advance. The Double Ratchet then derives new keys for every message, so earlier keys cannot be calculated from later ones, and keeps skipped message keys so messages that arrive out of order can still be decrypted. Signal has since published PQXDH, a post-quantum extension of X3DH. For the architecture, encryption moves work to the clients: every device has its own keys, groups need a way to share keys with every member’s devices, server-side search and moderation no longer see message text, and push notifications must carry no content. Use a vetted implementation rather than your own.
A chat system is a channel strangers can use to reach people, so abuse controls belong in the first version. Rate-limit sends per user and per conversation, limit what new accounts can do, such as messaging strangers or creating groups, and limit connection attempts per IP address at the gateway. Cap message and attachment sizes, let users block and report, and slow down accounts that collect reports. The algorithms are in rate limiter system design.
Finally, an estimate. The numbers below are illustrative assumptions chosen to show the method, not measurements of any real system.
- Assume 10 million daily active users sending 40 messages each: 400 million messages a day, about 4,600 a second on average. Assume peaks at 5 times the average: about 23,000 a second.
- Assume about 1 KB per stored message with metadata: 400 GB a day before replication, 1.2 TB a day with three replicas, roughly 440 TB a year. Compression and retention rules change this a lot.
- Assume 30% of daily users online at peak: 3 million open connections. If each gateway is sized for 100,000 connections, that is 30 gateways, plus headroom for a failed gateway and for deploys.
- Assume each message reaches 3 recipients on average: about 70,000 deliveries a second at peak, plus receipts, which roughly double the event count unless coalesced.
- Assume a heartbeat every 30 seconds per connection: 100,000 presence refreshes a second. That is why presence lives in memory with TTLs, and why gateways batch their refreshes.
Each line maps to a decision: the write rate sizes the message store, the connection count sizes the gateway tier, and the heartbeat rate is why presence never touches the main database.
BYD Tech builds web apps and their backends: the code lives in the client’s GitHub from day one, the founders are on the calls, and AI-assisted work is reviewed by an engineer.
Sources
Checked when this post was written.