TExcelTAD
Home › System Design › Design a Chat System

Design a Chat System

Let's design a messaging app in the style of WhatsApp or Slack: one-to-one chats, small groups, online presence and message history on every device. The interesting problems are real-time delivery over long-lived connections, ordering, and offline delivery when a recipient isn't connected.

1. Requirements

Functional

  • 1:1 and group chats (up to 500 members), text messages up to 4 KB.
  • Messages arrive in real time when the recipient is online and are delivered later when they reconnect.
  • Sent / delivered / read receipts; online presence.
  • History is synced across a user's devices.

Non-functional

  • Delivery latency under ~200 ms between online users in the same region.
  • Messages are never lost and appear in the same order for everyone in a chat.
  • 100 million daily active users.

2. Estimates

python · try it yourself
dau = 100_000_000
messages_per_user = 40
avg_message_bytes = 200          # text + metadata
peak_factor = 3
concurrent_share = 0.25          # share of DAU connected at peak
connections_per_server = 100_000 # long-lived WebSocket connections one gateway can hold

msgs_per_s = dau * messages_per_user / 86_400
print(f"messages: {msgs_per_s:,.0f}/s avg, {msgs_per_s * peak_factor:,.0f}/s peak")
print(f"storage per day: {dau * messages_per_user * avg_message_bytes / 1e12:.1f} TB")
print(f"storage per year: {dau * messages_per_user * avg_message_bytes * 365 / 1e15:.2f} PB")
concurrent = dau * concurrent_share
print(f"concurrent connections at peak: {concurrent:,.0f} -> {concurrent / connections_per_server:,.0f} gateway servers")
messages: 46,296/s avg, 138,889/s peak
storage per day: 0.8 TB
storage per year: 0.29 PB
concurrent connections at peak: 25,000,000 -> 250 gateway servers

The write rate (about 140,000 messages/s at peak) and the 25 million open connections drive the design.

3. High-level design

text
 device A ==WebSocket==> [chat gateway 17] --> [chat service] --> [message store (Cassandra)]
                                                    |   \
                                     who is online? |    +--> [push notifications] (offline users)
                                                    v
                                     [session registry: user -> gateway (Redis)]
                                                    |
 device B <==WebSocket== [chat gateway 42] <-------+  (route to B's gateway)
  • Clients keep a WebSocket (or MQTT) connection to a chat gateway; HTTP polling would waste resources and add latency.
  • A session registry records which gateway each online device is connected to.
  • The chat service assigns an order to each message, stores it, then fans it out to recipients' gateways, or to push notifications for offline devices.

4. Ordering messages

Timestamps from phones can't be trusted (clocks are wrong), and server clocks differ slightly. Instead, each chat gets a per-chat sequence number, assigned by the chat service when the message is stored. Clients sort by it and use it to detect gaps.

python · try it yourself
from collections import defaultdict

class ChatService:
    def __init__(self):
        self.next_seq = defaultdict(int)
        self.store = defaultdict(list)            # chat id -> messages (the message table)

    def send(self, chat_id, sender, text, client_msg_id):
        for m in self.store[chat_id]:             # idempotent: retried sends are not duplicated
            if m["client_msg_id"] == client_msg_id:
                return m
        self.next_seq[chat_id] += 1
        msg = {"seq": self.next_seq[chat_id], "from": sender, "text": text, "client_msg_id": client_msg_id}
        self.store[chat_id].append(msg)
        return msg

    def history(self, chat_id, after_seq=0):
        return [m for m in self.store[chat_id] if m["seq"] > after_seq]

svc = ChatService()
svc.send("chat:ana-ben", "ana", "Lunch?", "a-1")
svc.send("chat:ana-ben", "ben", "Sure, 12:30", "b-1")
svc.send("chat:ana-ben", "ana", "Lunch?", "a-1")           # network retry of the same message
svc.send("chat:ana-ben", "ana", "See you", "a-2")
svc.send("chat:team", "carl", "Standup in 5", "c-1")

for m in svc.history("chat:ana-ben"):
    print(m["seq"], m["from"], m["text"])
print("ben's phone last saw seq 1, sync gives:", [m["text"] for m in svc.history("chat:ana-ben", after_seq=1)])
1 ana Lunch?
2 ben Sure, 12:30
3 ana See you
ben's phone last saw seq 1, sync gives: ['Sure, 12:30', 'See you']

The client-generated client_msg_id makes sending idempotent, so a retry after a timeout doesn't create a duplicate. Sync is just "give me everything after the last sequence number I have", per chat.

5. Delivery: online, offline, multiple devices

python · try it yourself
registry = {"ben:phone": "gw-42", "ben:laptop": "gw-07"}   # online devices
devices = {"ana": ["ana:phone"], "ben": ["ben:phone", "ben:laptop"], "carl": ["carl:phone"]}
outbox = []                                                # what the chat service sends out

def deliver(msg, members):
    for user in members:
        if user == msg["from"]:
            continue
        for device in devices[user]:
            gateway = registry.get(device)
            if gateway:
                outbox.append(f"{gateway}: push over WebSocket to {device}: seq {msg['seq']}")
            else:
                outbox.append(f"push-service: notify {device} (offline), will sync on reconnect")

deliver({"seq": 7, "from": "ana", "text": "Hi team"}, ["ana", "ben", "carl"])
for line in outbox:
    print(line)
gw-42: push over WebSocket to ben:phone: seq 7
gw-07: push over WebSocket to ben:laptop: seq 7
push-service: notify carl:phone (offline), will sync on reconnect

Offline devices aren't "queued" separately: the message is already in the store. When a device reconnects it asks for messages after its last known sequence number in each chat. Push notifications only wake it up.

6. Group fan-out cost

In a group, each message is delivered to every other member's devices. Fan-out grows with group size, which is why big channels (thousands of members) are often treated differently, with clients pulling recent messages instead of the server pushing each one.

python · try it yourself
msgs_per_s = 46_296 * 3                          # peak, from the estimate
share_in_groups = 0.3
devices_per_user = 1.5

for group_size in [2, 10, 100, 500]:
    pushes = msgs_per_s * (1 - share_in_groups) * 1 * devices_per_user \
           + msgs_per_s * share_in_groups * (group_size - 1) * devices_per_user
    print(f"avg group size {group_size:3}: {pushes:>13,.0f} device pushes/s")
avg group size   2:       208,332 device pushes/s
avg group size  10:       708,329 device pushes/s
avg group size 100:     6,333,293 device pushes/s
avg group size 500:    31,333,133 device pushes/s

7. Storage

Messages are written once, read mostly as "latest N in a chat", and kept forever: a natural fit for a wide-column store such as Cassandra or HBase.

text
messages: partition key = chat_id, clustering key = seq DESC
          columns: sender_id, body, client_msg_id, created_at

Very large or long-lived chats can be bucketed ((chat_id, month)) so no partition grows without bound. Media (images, voice notes) goes to object storage; the message only holds its URL.

Trade-offs

Decision Choice Why
Transport WebSocket to stateful gateways Real-time, server can push
Ordering Per-chat sequence numbers Clocks are unreliable; a total order per chat is enough
Exactly-once Client message ids + idempotent store Retries are inevitable on mobile networks
Offline Sync from the store + push notifications One source of truth; no per-device queues
Presence Heartbeats with a timeout, fanned out lazily Exact presence for millions of users is expensive

Note: End-to-end encryption (the Signal protocol) changes the design: servers only see ciphertext, so search and moderation must happen on the client, and each device has its own keys.

Test yourself

Why do chat systems use per-chat sequence numbers instead of client timestamps for ordering?

  1. Sequence numbers are smaller
  2. Device clocks are unreliable; a server-assigned sequence gives every member the same order
  3. Timestamps can't be stored in Cassandra
  4. To encrypt messages

How does a device that was offline get the messages it missed?

  1. From a per-device queue on the gateway
  2. It asks the store for messages after its last known sequence number in each chat
  3. Messages are lost while offline
  4. Other users resend them

What prevents a retried send from creating a duplicate message?

  1. WebSockets never retry
  2. A client-generated message id checked by the server
  3. Sequence numbers
  4. Push notifications