Skip to content
Visual explainer 4h to learn 6 steps

Chat system

Design real-time delivery, presence, ordering and message storage.

By Invicly Tech, , in System Design Deep Dive. About 11 minutes to read.

Topic 28 of 33

In short

A chat system delivers messages in real time over persistent WebSocket connections, stores history durably and tracks who is online. The hard parts are routing to the right connection server, ordering per conversation and offline delivery.

Explained simply

A chat system lets people send messages that arrive almost instantly, like WhatsApp or Slack. The phone keeps a long-lived connection open to a server, so the server can push a new message the moment it arrives instead of the phone asking again and again.

There are two main kinds of chat. One-to-one chat is between two people. Group chat sends each message to many members. Groups need extra care, because one message may need to reach hundreds of people, some online and some offline.

Messages must not get lost, must show up in the right order, and should not appear twice. The server saves each message before saying it was sent. When someone is offline, the app gets a push notification and downloads missed messages when it reconnects.

Chat also shows presence: whether a friend is online or when they were last seen. This is done with small heartbeat messages every few seconds. If the heartbeats stop, the person is marked offline after a short timeout.

Press Play on a diagram to walk through it one step at a time.

LayersHigh-level architecture
  1. 1
    Clients

    Keep a WebSocket open while active

  2. 2
    Chat gateway servers

    Hold connections, stateful per user

  3. 3
    Session registry

    Redis maps user to gateway server

  4. 4
    Message service and queue

    Assigns IDs, routes, fans out to groups

  5. 5
    Message store

    Cassandra partitioned by conversation ID

  6. 6
    Presence and push

    Heartbeats for online; APNs/FCM when offline

SequenceOne-to-one message delivery
Alice
Gateway A
Message svc
Gateway B
  1. 1send(msg, clientMsgId)
    Alice to Gateway A: send(msg, clientMsgId)
  2. 2Forward message
    Gateway A to Message svc: Forward message
  3. 3Assign seq ID, persist
    Message svc to Message svc: Assign seq ID, persist
  4. 4Ack stored
    Message svc to Gateway A: Ack stored
  5. 5Sent tick
    Gateway A to Alice: Sent tick
  6. 6Route to Bob's gateway
    Message svc to Gateway B: Route to Bob's gateway
  7. 7Delivered ack from Bob
    Gateway B to Message svc: Delivered ack from Bob
CompareWays to get new messages to a client
Short polling
  • Client asks every few seconds
  • Simple, works everywhere
  • Wasteful, slow to notice
Long polling
  • Server holds request until data
  • Better latency than polling
  • Reconnect after every message
WebSocket
  • One persistent two-way connection
  • Lowest latency, little overhead
  • Stateful servers need a registry
  • Standard choice for chat

In depth

Requirements and scale

Ask first: one-to-one only, or groups too? How big can a group get? Do we need read receipts, typing indicators, media, multiple devices per user, end-to-end encryption? Must history be kept forever? Each answer changes the design. A typical scope: one-to-one and groups up to a few hundred members, text plus media links, delivered and read receipts, history kept, several devices per user.

For scale, assume 50 million daily active users sending 40 messages each. That is 2 billion messages a day, about 23,000 per second on average and maybe 70,000 at peak. At around 100 bytes of text each, that is about 200 GB of new text per day, roughly 73 TB a year before replication. Connections matter as much as messages: if 10 million users are online at once and one server can hold about 100,000 to 500,000 idle WebSockets, you need tens to a hundred gateway servers.

  • Messages per second sizes the message service
  • Concurrent connections size the gateway fleet
  • Group size limits fan-out cost

Handling WebSocket connections

A WebSocket starts as an HTTP request with an Upgrade header, then stays open so both sides can send frames at any time. Gateway servers hold these connections. They are stateful: Bob's connection lives on exactly one server. So each gateway writes user ID to server ID into a session registry (often Redis) when a user connects, and removes it when the connection closes.

Load balancers in front of gateways must support long-lived connections, and you need idle timeouts longer than your heartbeat interval. When a gateway is restarted for a deploy, its clients disconnect and reconnect to another server, so clients should retry with exponential backoff plus random jitter. Without jitter, thousands of clients reconnect in the same second and overload the remaining servers (a thundering herd).

SequenceConnect, register and receive
Bob's phone
Gateway B
Session registry
Message svc
  1. 1WebSocket upgrade with auth token
    Bob's phone to Gateway B: WebSocket upgrade with auth token
  2. 2SET session:bob = gateway-B
    Gateway B to Session registry: SET session:bob = gateway-B
  3. 3Heartbeats keep session and presence fresh
    Bob's phone to Gateway B: Heartbeats keep session and presence fresh
  4. 4Where is bob?
    Message svc to Session registry: Where is bob?
  5. 5gateway-B
    Session registry to Message svc: gateway-B
  6. 6Deliver message
    Message svc to Gateway B: Deliver message
  7. 7Push frame to the phone
    Gateway B to Bob's phone: Push frame to the phone

Storing messages and keeping order

Chat data is write-heavy and is almost always read by conversation, newest first. That fits a wide-column store like Cassandra or ScyllaDB with conversation ID as the partition key and a sequence number as the clustering key, so one conversation's messages sit together on disk in order. Very active conversations can be split into time buckets (conversation ID plus month) so no partition grows without limit.

Wall clocks on different servers drift, so do not order by timestamp. Instead, give each message a per-conversation sequence number when it is stored. The client also sends a client message ID; if the network drops and the client resends, the server sees the same ID and does not store a duplicate. Clients track the last sequence they have, and on reconnect ask for everything after it. Gaps in sequence numbers tell a client it missed something.

  • Partition key: conversation ID
  • Clustering key: sequence number, descending
  • Client message ID makes retries idempotent
  • Sync with after_seq on reconnect

Groups, presence and delivery guarantees

For small groups, the message service stores the message once, then looks up each member in the session registry and forwards it to their gateways. Offline members get a push notification through APNs (Apple) or FCM (Google). For very large groups or channels, fan-out to every member on every message is expensive, so clients may fetch new messages when they open the channel instead.

Presence is a cheap but chatty feature. Clients send heartbeats; a missing heartbeat for, say, 60 seconds marks the user offline. Send presence changes only to contacts who are currently viewing that person, not to everyone, or a single popular user can generate huge traffic.

Most chat systems give at-least-once delivery: the server retries until the device acks, and the client drops duplicates using message IDs. Combined, the user sees each message exactly once.

Learn it in 6 short steps

About 40m each. Track them with a timer in your plan.

  1. 1
    Clarify one-to-one and group requirements~40m
  2. 2
    Estimate message volume~40m
  3. 3
    Design WebSocket connection handling~40m
  4. 4
    Model and store messages~40m
  5. 5
    Track presence and message ordering~40m
  6. 6
    Discuss delivery guarantees and trade-offs~40m

Key points

  • Gateways are stateful, so a registry tracks which server holds each user.
  • Order messages per conversation with a sequence number, not wall clocks.
  • Persist before acknowledging so messages survive crashes.
  • Offline users get a push notification and sync missed messages on reconnect.
  • Client message IDs let the server drop duplicate sends.

Key terms

Tap a card to flip it. 0/5 known

Examples

text
Scale: 50M DAU * 40 messages = 2B messages/day
  ≈ 23,000 msg/s average, ~70,000 peak
  100 bytes * 2B = 200 GB/day

messages (
  conversation_id  PARTITION KEY,
  seq_id           CLUSTERING KEY DESC,
  sender_id, body, created_at
)
Sync: GET /conversations/{id}/messages?after_seq=1042

Estimate and a conversation-partitioned message table.

Bob is offline when Alice writes

Step 1: Alice's app sends the message with a client message ID over her WebSocket. Step 2: the message service assigns sequence 1043 in that conversation, stores it, and acks Alice, who sees one tick. Step 3: the registry has no live session for Bob, so the service sends a push notification through FCM or APNs. Step 4: Bob opens the app, connects, and asks for messages after the last sequence he has. Step 5: his app acks 1043 and Alice sees the delivered tick.

text
Bob reconnects:
  GET /v1/conversations/c42/messages?after_seq=1042
  -> [{ seq: 1043, sender: alice, body: "Lunch?" }]
  WS send { type: "ack", conv: "c42", seq: 1043 }
Server -> Alice: { type: "delivered", conv: "c42", seq: 1043 }

A resend after a network drop

Alice sends a message in a tunnel. The server stores it, but the ack never reaches her. Her app times out and resends with the same client message ID. Step 1: the server checks a recent-IDs table (or a unique index on conversation plus client message ID). Step 2: it finds the existing message and returns the original sequence number instead of storing a second copy. Step 3: Alice sees one message, Bob sees one message. Without the client ID, Bob would see the text twice.

sql
-- one way to enforce it in a relational store
CREATE TABLE messages (
  conversation_id bigint,
  seq            bigint,
  client_msg_id  uuid,
  sender_id      bigint,
  body           text,
  PRIMARY KEY (conversation_id, seq),
  UNIQUE (conversation_id, client_msg_id)
);

Quick reference

  • WebSocket = HTTP Upgrade, then a persistent two-way connection
  • Session registry maps user ID to the gateway holding their socket
  • Order by per-conversation sequence number, not server clocks
  • Persist first, then ack the sender
  • Client message IDs turn at-least-once delivery into no duplicates
  • Offline users: push via APNs or FCM, then sync after_seq on reconnect
  • Reconnect with exponential backoff plus jitter to avoid a thundering herd
  • Partition messages by conversation ID; bucket by time for huge chats

Common mistakes

  • Ordering by server timestamps that drift across machines.
  • Treating gateway servers as stateless and losing routing info.
  • Broadcasting presence changes to every contact in huge groups.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Why do chat gateways need a session registry?

Question 2

2What is the safest way to order messages in one conversation?

Question 3

3A client resends a message after a timeout. How does the server avoid storing it twice?

Question 4

4Why add random jitter to client reconnect delays?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Estimate messages per second and daily storage for 20 million DAU sending 50 messages a day at 150 bytes each.

  2. Exercise 2medium

    Design the message table for a wide-column store so that loading the latest 50 messages of a chat is one fast read, even for chats with millions of messages.

  3. Exercise 3hard

    A gateway server crashes with 200,000 users connected. Walk through what happens to connections, the registry and in-flight messages.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Why not use plain HTTP requests for chat?
You can, with polling, but it adds delay and wastes requests. WebSockets keep one connection open so the server can push messages the moment they arrive.
Is exactly-once delivery possible?
Not over an unreliable network on its own. Systems use at-least-once delivery with retries and remove duplicates on the client using message IDs, which looks exactly-once to the user.
Which database is good for chat messages?
Wide-column stores such as Cassandra or ScyllaDB are common because they handle heavy writes and read one conversation in order. A sharded relational database can also work at smaller scale.
How does end-to-end encryption change the design?
The server can no longer read or search message bodies; it only stores and forwards encrypted blobs. Key exchange (for example the Signal protocol) and multi-device key handling become part of the design.
ShareXLinkedInWhatsApp