CodingNodes Space play · ←→ step · R restart

The problem

A chat system moves a short piece of text from one person to another, keeps a copy you can scroll back to, and tells you whether the other person is there right now. Everyone uses one, and yet the three jobs — deliver, persist, track presence — pull in different directions, so the design has to decide explicitly how they trade off.

The hardest constraint is that the recipient is a device, not a server: it may be asleep, offline, or on another network. So the system must know when a message can be pushed straight through and when it has to be held and handed over later.

Today you will build one: scope the problem, pick a transport that does not burn the battery, design the message server, model the data, track presence, and wire the delivery path end to end.

Requirements

Functional — what it must do

  • One-to-one direct messages between two users, with a running history you can open at any time and scroll back through.
  • A message sent while the recipient is online arrives in under about half a second; sent while offline, it is delivered on the recipient's next connection, in order.
  • Show who is online, and mark each message as sent, delivered, or read.
  • Group chat: one sender, many recipients, with the sender's copy and every recipient's copy staying in order and in sync.

Non-functional — how well it must do it

  • Latency: p99 delivery to an online recipient under 300 ms at the edge, most of it network.
  • Durability: no sent message is lost, whether the server or the recipient fails mid-flight.
  • Scale: tens of millions of simultaneous open connections, each a live session that must be kept cheap in memory.
  • Ordering: messages from a sender arrive in the order sent; a recipient's outbox drains first-in-first-out.

Scale — how much it must take

  • 10,000,000 users online at peak, sending about 50,000 messages per second in total; reads run roughly five times the write rate.

Assumptions — the numbers this design is sized for

A rate limit means nothing without a scale. These are the figures every later part relies on: how much traffic arrives, how much work the limiter has to do per second, and how much latency and memory it may spend doing it.

Online users
10,000,000
The number of live sessions we must hold open. Everything per-connection is multiplied by this.
Message rate
50,000 /s
Peak writes. At 500 bytes each that is roughly 25 MB of new text per second.
Read / write ratio
≈ 5 : 1
Opening a conversation, polling, and re-fetching history dominate; reads are about 250,000/s.
Avg message size
500 bytes
A sentence of text plus ids and metadata. Media is a separate, far larger path out of scope here.
Write bandwidth
≈ 2.2 TB / day
50,000/s × 500 B ≈ 25 MB/s, which is about 2.2 TB of new messages every day.
Connection memory
≈ 200 GB
Hold ~20 KB of session state per open connection × 10,000,000 = 200 GB, spread across the chat-server fleet.
History kept hot
last 100 msgs
The most recent ~100 messages per conversation are cached; the rest live in the sharded store.
Delivery budget
< 300 ms p99
For an online recipient, end to end. The server's own share should stay under a few milliseconds.

Takeaways

Part 1

Scope: who is talking to whom

A 'chat' system can be a phone text, an office room, or a game lobby. The design changes a lot between them, so pin down which one you are building.

  1. 1
    Three different chats

    A phone app like Messenger is mostly one-to-one. An office tool like Slack is mostly groups and channels. A game lobby like Discord wants many-to-many with very low latency. Each one stresses a different part of the design.

  2. 2
    Pick the hard one

    We scope to one-to-one with a running history and presence, the common core. If it must also do groups, the only real change is delivery: one message fans out to many recipients instead of one. Everything else — server, storage, presence — stays the same.

Part 2

Getting it across the wire

How does the recipient's phone learn a message is waiting? Polling burns battery; a held connection costs server memory. The choice is the whole story of a chat app.

  1. 1
    Short polling

    The naive idea: the client asks 'anything for me?' every few seconds. It is simple and stateless, but an idle client still wakes every interval, so 10,000,000 phones × a request every 5 seconds is a flood of empty round trips and dead battery.

  2. 2
    Long polling

    Better: the client asks, and the server holds the request open until a message arrives or a timeout hits, then the client immediately asks again. The phone sleeps until it has work, so empty polls disappear — at the cost of one held request per client.

  3. 3
    WebSockets

    The modern default: open one persistent, full-duplex connection and let the server push the moment a message is ready. No polling at all, lowest latency. The price is real server memory per open socket — 10,000,000 of them — which is why the chat fleet is sized around connection state, not CPU.

Part 3

The message server

A stateless fleet of chat servers sits in front of the data. Each one owns a slice of the live connections and a slice of the stores behind it.

  1. 1
    A stateless fleet

    Many identical chat servers sit behind a load balancer. A client's connection is pinned to one server, which routes that client's messages to the stores. 'Stateless' means no server is special: if one dies, its clients reconnect elsewhere and pick up where they left off.

  2. 2
    What each one owns

    Each chat server holds the live sockets of its assigned users, the hot cache of their last hundred messages, and a small outbox for anyone currently offline. It is the outbox — not the live socket — that makes delivery reliable when the recipient is away.

  3. 3
    Why it is stateless

    The server keeps no long-lived per-user record of its own: the source of truth is the shared message store, and the outbox is just a queue it can rebuild. That is what lets a dead server's clients be reattached to a live one without losing a single message.

Part 4

The data model

Four tables carry a chat system: people, conversations, messages, and the offline backlog. How they key decides how you shard.

  1. 1
    The four tables

    A user is a row with an id and a presence flag. A conversation is a row per pair (or group) of users. A message belongs to a conversation, has a sender, a body, a time, and a delivery state. An outbox row is a message queued for a recipient who is offline.

  2. 2
    Key messages by conversation

    Every message is stored under its conversation id. That is the unit people actually open: to read a chat you pull one conversation's rows, not a user's. It also means a conversation between two heavy users and one between two light users cost nothing different to look up.

  3. 3
    The outbox is the reliability anchor

    The outbox row is written in the same step as the message itself. If the recipient is online it is pushed immediately and the outbox entry cleared; if offline it simply waits, and is drained in order the next time the recipient connects. One write, two consumers, no message left behind.

Part 5

Presence: who is online

Knowing the recipient is online is what turns a slow 'store and forward' into a fast push. It is a service of its own, updated by heartbeats.

  1. 1
    A presence service

    A small service answers one question: is this user connected right now? The chat servers report their clients to it, and it holds a live map of user → online. When a message is routed, that lookup decides push-versus-outbox in a single millisecond.

  2. 2
    Heartbeats keep it honest

    A socket can die silently, so presence cannot be inferred from a connection existing. Each client sends a heartbeat; the presence service marks a user offline if the heartbeat stops for a couple of intervals. That grace window absorbs a dropped packet without falsely showing someone as gone.

  3. 3
    Scale presence by user hash

    The presence map is a key-value store sharded the same way as everything else: hash the user id and every heartbeat, lookup, and expiry lands on the same shard. No cross-shard traffic, and a user's presence is exactly as local as their messages.

Part 6

Delivery: online push, offline queue

The same message takes two different roads depending on the recipient's presence. Group chat is the same idea with more recipients on the receiving end.

  1. 1
    Online: straight through

    Alice sends a message. The router checks presence, sees Bob is online, and the server holding Bob's socket pushes it over his live connection. Total path is one hop to the store plus one push — well inside the 300 ms budget.

  2. 2
    Offline: into the outbox

    If Bob is away, the router writes the message to his outbox instead of pushing. The moment he reconnects, the server drains his outbox in order, so he receives it then — and in the correct sequence relative to everything else he missed.

  3. 3
    Group: fan out on write

    For a group message the router checks presence for every member. Online members get a push; offline members each get an outbox entry. Fanning out on write (not on read) is what keeps the recipient's device simple — it never has to ask 'was this for me?'

  4. 4
    Order is preserved

    Because the outbox is a first-in-first-out queue drained on connect, and because every message carries a sequence number the client sorts by, the recipient sees Alice's messages in the order she sent them — whether they arrived live, a minute late, or interleaved with a reconnect.

★ Finale

End to end

One message, both roads: Alice writes, the server stores it, presence decides, and Bob receives it live while his offline friend gets it queued. That is the whole system in one picture.

  1. 1
    The whole system

    Everything in one diagram. A client fleet talks over WebSockets to a stateless chat-server pool, which reads a presence service and writes to sharded message stores and per-user outboxes. The hot cache serves the last hundred messages of any conversation in a millisecond.

  2. 2
    Alice sends to Bob

    Alice's message arrives at the server that owns her socket. It is written to the message store under the conversation id, a sequence number is assigned, and the router asks presence: is Bob online?

  3. 3
    Bob is online — pushed

    Presence says yes. The server that owns Bob's socket pulls message 4821 and pushes it down his live WebSocket. He sees it, marks it read, and the read receipt travels back the same way. End to end, well under 300 ms.

  4. 4
    Carol is offline — queued

    The same message also went to Carol, who is in a group with them. Presence says offline, so it lands in her outbox. She is on the subway with no signal; nothing is lost, it is just waiting, in order, for her next connection.

  5. 5
    Carol reconnects — drained

    Carol's phone gets signal and opens a socket. The server sees her, checks presence, and drains her outbox first-in-first-out: message 4821 and everything else she missed arrive in order. Her read receipt confirms it. The system delivered both roads with the same write.

🌐 In the wild

In the wild

The same three pieces — a push transport, a store-and-forward outbox, and a presence service — are what real messaging products run on. Here is where each shows up.

  1. 1
    These products run this design

    Everything you just built is production messaging. The push-versus-outbox split, the presence service, and the per-conversation store are exactly the pieces the big chat products are built from. Let's match the diagram to the names.

  2. 2
    Messenger: fan-out at scale

    Facebook's own engineering write-up describes exactly the fan-out-on-write pattern you built: a message to a conversation is written once and fanned out to each recipient's inbox, with online users pushed and the rest queued. That is your delivery section, at planetary scale.

  3. 3
    Discord: ids you can sort

    Discord's messaging is famous for how it assigns ids. Rather than a database auto-increment, each message id is a snowflake — time, machine, and sequence packed into one big integer — so 'newer' is just 'larger' and no coordinator is needed to order a billion messages. That is your sequence-number idea, hardened for scale.

  4. 4
    Slack: an edge cache

    Slack wrote about 'Flannel', an edge cache that sits in front of its origin to make it scale. That is your hot-cache layer — the last hundred messages served from the edge instead of a round trip to the store — used to keep a huge read rate from stampeding the database.

  5. 5
    WhatsApp and WeChat: the two extremes

    WhatsApp's story is the transport and the trust: end-to-end encryption means the servers can queue and deliver your message without ever reading it. WeChat's story is the opposite pressure — one app that is also payment, a mini-app store, and a social graph. Both ride the same push/outbox skeleton you designed; they just lean on different parts of it.