All lessonsDay 13B-Building blocks2026-10-09

Day 13: Design a Chat System That Feels Instant

You open the same account on your phone and laptop at once. You send "where are you" and your friend sees it instantly while a green dot tells her you are online.

50M DAUDesign target for Messenger style app
max 100Group limit in scope for this lesson
<100k charsText limit per message
foreverHistory retention required
694k / sec60B per day / 86,400 derived rate
10 GB1M x 10K memory sketch for connections

Key points

  • The receiver side drives the protocol choice because the server must push without a client request.
  • One persistent connection per client makes the chat tier stateful and forces discovery and reconnection logic.
  • New messages are defined by a per device cursor compared against stored IDs.
O1Derive bytes of memory for 1M concurrent connections from the 10K per connection figure.
O2Break down the 1 on 1 send path into ID assignment, queue, store, and forward steps in order.
O3Argue when to copy one message per inbox and when to switch to fetch on demand.
01

Scale sketch: do the two divisions first


Two numbers set the shape of the whole design. Industry volume cited is 60 billion messages per day for Messenger and WhatsApp. The derived rate from that volume is 60,000,000,000 / 86,400 = about 694,000 per second. Memory sketch for connections is 1M x 10K = about 10GB. Drive both below.

Operable: move the sliders. Watch per second rate and memory move. The math is the design constraint.

60B / 86400
60B
1.0M
10K
Derived write rate
694,444 /s

messages per day divided by 86,400

Connection memory
10.0 GB

connections times KB each

Design target
50M DAU

text only, keep every message forever

Reading: at 60B per day you must absorb about 694k writes per second, and 1M sockets at 10K each already cost about 10GB before any business logic.

Stat cards as calculators. Change volume or connection count and the derived rate and memory update. This is why history needs a key value store and why one box cannot hold the chat tier.
02

Problem with concrete numbers


We design a Messenger style app for both mobile and web.

Numbered requirements:

  1. R1One on one chat with low delivery latency.
  2. R2Small group chat with max 100 people.
  3. R3Online presence indicator.
  4. R4Multiple device support. The same account can be logged in on phone and laptop at the same time.
  5. R5Push notifications when the recipient is offline or the app is not running.
  6. R6Scale and data rules. Support 50 million DAU. Support text only. Keep every message forever.

Scope notes from the chapter. End to end encryption is not required for now. Signup, login, and profile are standard request response work over HTTP.

Why this is hardSend is easy because the client starts the request. Receive is hard because the server must initiate delivery. History is huge and mostly cold. Only recent chats are read often, but search and jump to a message still need random access. Read to write ratio is about 1:1 for 1 on 1 chat.
Stat from chapterValue
Design target50 million DAU
Group limit in scopemax 100 people
Text limitless than 100,000 characters
History retentionforever
Industry volume cited60 billion messages per day for Messenger and WhatsApp
Derived rate from that volume60,000,000,000 / 86,400 = about 694,000 per second
Memory sketch for connections1M x 10K = about 10GB
03

Mental model: one post office with personal inboxes


Think of the chat service as a post office. Senders drop letters at the counter. Each recipient owns one message sync queue that acts as an inbox.

The post office does three jobs. It stamps each letter with an order number. It files a copy in storage. It drops a copy in each recipient inbox or rings the doorbell with a push if nobody is home.

Presence is a separate desk. That desk tracks who is in the building. Friends subscribe to change notices for people they care about.

Drive it: press Send one letter. Watch stamp, file, inbox drop, or push if offline.

idle
1 StampID generator assigns order number
2 Filecopy in key value store
3 Inboxcopy in message sync queue
4 Deliverforward or push
B inbox (sync queue)
empty
Key value file copy
empty

Press Send. One post, one key, one inbox, end to end.

One post tracked end to end. Stamp, file, inbox drop, then forward over WebSocket when online or push when offline.
04

Mechanism stepped through live


4.1 Sender and receiver need different thinking

Most client work starts with a client request. The sender can use plain HTTP POST to the chat service. The keep alive header helps because it reuses one TCP connection and reduces handshakes. Facebook used HTTP initially to send messages.

The receiver cannot use plain request response well. The server has news at unpredictable times. The chapter compares three receiver techniques.

Polling means the client asks "new messages" on a timer. The server answers NO most of the time. The cost is many empty answers.

Long polling means the client asks and the server holds the request open. The server answers only when news arrives or a timeout hits. Then the client immediately asks again.

WebSocket means the client starts as HTTP and then upgrades to a persistent bidirectional channel. After the handshake the server can push at any time. It uses port 80 or 443 so it usually passes firewalls.

The chapter choice is WebSocket for both sending and receiving. That simplifies client and server code. The price is that the server must manage many persistent connections.

Operable lab: pick a protocol, set how chatty the friend is, then press Run 10 seconds. Dots count requests. Red is waste, green is useful.

polling selected
2
client to server time
Requests sent
0

each ask costs work

Useful deliveries
0

answers with news

Empty answers
0

NO most of the time

Try it: with 2 messages in 10 seconds, polling asks every second and wastes about 8 answers. WebSocket asks once and pushes twice.

Same 10 seconds, three protocols. Polling cost grows with client count, not message count. Long polling reduces empties but still times out for quiet users. WebSocket holds one idle connection.

4.2 High level pieces

Stateless services handle login, signup, profile, and group management behind a load balancer. Any server can handle any request.

Stateful service is the chat tier. Each client holds a persistent WebSocket to one chat server. A client stays on that server while it is healthy.

Service discovery recommends a chat server by location and capacity. The chapter names Apache Zookeeper for this job.

Presence servers own online status and speak WebSocket to clients.

Notification servers send push notifications.

Key value store keeps chat history. An offline user reads history after reconnecting.

API servers handle the non realtime work.

Login with discovery works in four steps. User A logs in. The load balancer sends the request to API servers. After auth, service discovery picks the best chat server and returns its address. User A opens a WebSocket to that server. In the example, User A gets Chat server 2.

Failure case includedIf a chat server with hundreds of thousands of connections goes offline, clients lose their sockets. Discovery provides a new chat server for fresh connections. That fixes liveness but breaks (1) briefly until reconnect and resync complete.

4.3 1 on 1 flow

Assume User A is on Chat server 1. User B is on Chat server 2.

Stepper: press Next or Play. One message "where are you" travels the six numbered steps. Toggle presence to see the branch.

press Next to start
User Aserver 1 ID genstamp ID Sync queueinbox + KV Server 2B holder User Bpush if off id=847 "where are you" queued + stored forward: B online delivered over socket 1 send - 2 ID - 3 queue - 4 store - 5 branch - 6 forward HTTP send would land anywhere. Long polling socket may live elsewhere. That mismatch is why WebSocket plus shared queue wins. User A: server 11 send ID generator2 stamp Queue + KV3 queue, 4 store Server 25 branch User B6 forward or push
  1. User A sends a chat message to Chat server 1.
  2. Chat server 1 obtains a message ID from the ID generator.
  3. Chat server 1 sends the message to the message sync queue.
  4. The message is stored in the key value store.
  5. Branch on presence. 5a. If User B is online, forward to Chat server 2 where User B is connected. 5b. If User B is offline, ask push notification servers to send a push.
  6. Chat server 2 forwards the message to User B over the persistent WebSocket.
Ordered path is ID assignment, queue, store, then forward. Use the B online toggle to see step 5 switch between forward and push.
Failure case includedHTTP servers are usually stateless with round robin balancing. The server that accepts the send may not hold the long polling connection for the receiver. That mismatch is a core reason long polling alone is fragile here. It breaks (1) under load balancing unless you add stickiness or a shared queue.

4.4 Sync across multiple devices

Each device keeps a cur_max_message_id. That is the largest ID it has seen.

A stored message is new for that device when two conditions hold. Recipient ID equals the logged in user ID. Stored message ID is larger than cur_max_message_id.

Example from the chapter. Phone has cur_max_message_id = 653. Laptop has cur_max_message_id = 842. Each device asks the key value store for IDs above its own cursor. The phone gets more backlog than the laptop. No cross device coordination is needed beyond the cursor.

If a device loses connection, it replays from its cursor on return. That preserves (4) and (6).

Operable: drag each cursor, then press Sync now. New arrivals 844, 845, 846 appear. See who fetches what.

653
842
Phone
cursor 653
Laptop
cursor 842

Press Sync now to replay from each cursor.

Two conditions define new: recipient matches and stored ID is larger than cursor. Reusing the laptop cursor on the phone would skip 654 and 843 and break (4).

4.5 Small group flow

Assume User A, B, and C share one group. User A sends one group message to Chat server 1.

The server copies the message to each recipient inbox. One copy lands in B inbox. One copy lands in C inbox.

On receive, each member only checks its own inbox. That keeps sync simple. Copy cost is small when the group is capped at 100. It breaks (2) if you keep this design for 100,000 members because one send creates 100,000 copies.

Calculator: move group size. Copy cost stays calm to 100, then explodes. Switch mode to see the fix.

3
Copies per send
2

one per recipient inbox

Sync rule
own inbox

each member checks self

Verdict
OK

small vs huge group

Now: 3 members needs 2 copies. Simple and cheap.

Keep per inbox copy for small groups up to 100. For huge groups store once per channel and let members fetch on entry. You protect send cost but lose instant fanout.

4.6 Storage model

Generic data like profile and friends list stays in relational tables with replication and sharding.

Chat history goes to a key value store for horizontal scale and low latency. Relational indexes struggle with the long tail of old messages. Random reads get expensive as indexes grow.

Message table for 1 on 1 chat:

ColumnTypeNote
message_idbigintprimary key, defines order
message_frombigintsender
message_tobigintrecipient
contenttextunder 100,000 characters per (6)
created_attimestampcannot define order alone because two messages can share a timestamp

Group message table:

ColumnTypeNote
channel_idbigintpartition key, channel means group
message_idbigintsort key within channel
user_idbigintsender
contenttexttext only
created_attimestampwall time

Composite primary key is (channel_id, message_id). All group queries operate in a channel, so that partition key keeps reads local.

Message ID must be unique and sortable by time. New rows need higher IDs than old rows. Three options are named. MySQL auto_increment works but NoSQL stores usually lack it. A global 64 bit generator like Snowflake works across groups. A local generator works per channel because order only matters inside one 1 on 1 thread or one group. Local is easier to build.

4.7 Online presence

Presence servers store status and last_active_at in the key value store.

Login. After the WebSocket to realtime service is built, save {status: online, last_active_at: timestamp}. The dot turns green. This serves (3).

Logout. The client logs out through API servers. Set status to offline in the store. This serves (3) on clean exit.

Disconnection. Do not flip to offline on every socket drop. Tunnels and mobile networks flap too often. That would make the dot blink and breaks (3) as user experience.

Fix with heartbeat. An online client sends a heartbeat every 5 seconds in the example. If the server sees a heartbeat within x seconds, the user stays online. Otherwise mark offline. The example uses x = 30 seconds as an illustrative threshold to show the logic. After three heartbeats the client goes silent. No heartbeat arrives in 30 seconds. The server flips status to offline.

Fanout for status. Presence uses a publish subscribe model. Each friend pair has a channel. When User A changes status, presence publishes to channel A-B, channel A-C, and channel A-D. Users B, C, and D subscribe to their own channel and learn the change over WebSocket.

This is fine for small friend sets. WeChat uses a similar approach with a 500 member cap cited in the chapter. For a 100,000 member group, one change creates 100,000 events. That breaks (3) by cost and delay. The chapter fix is to fetch status only on entering a group or on manual refresh of the friend list.

Player: press Play heartbeats. Three beats at 5 second spacing, then silence. Watch the 30 second grace window hold the green dot before it flips.

timeout 30s, beat 5s
offline: no beats yet

Idle. Beats refresh last_active_at. Silence past 30 seconds flips to offline.

Heartbeat with grace window trades truth for calm UI. Presence lags reality by up to the window so tunnels do not make the dot blink.
05

Weakness stated honestly, fix and its price


1. Empty polling

Weakness
  • Polling wastes work on empty answers. Long polling still reconnects after timeouts for quiet users. It also cannot tell disconnect from silence and it fights stateless balancing.
Fix plus price
  • Use persistent WebSocket for both directions. Price. The chat tier becomes stateful. You must run discovery, track capacity, and handle reconnect storms.

2. Single box temptation

Weakness
  • One server can in theory hold 1M connections at 10K each in about 10GB. That invites a single box design.
Fix plus price
  • Split realtime, presence, API, notification, and storage across many servers. Price. More moving parts and more failure modes. Single point of failure is removed but operations get heavier.

3. Relational history tail

Weakness
  • Relational storage handles profiles well but not chat history scale and random access over a forever tail.
Fix plus price
  • Use a key value store for messages with message_id ordering. Price. You must solve ID generation yourself with Snowflake style global IDs or per channel local IDs.

4. Copy explosion

Weakness
  • Per inbox copy simplifies (2) and (4) for groups up to 100. The same copy explodes for huge groups.
Fix plus price
  • Keep per inbox copy for small groups. Switch large groups to fetch on demand. Price. Large group members may see stale presence or delayed history until they open the group or refresh.

5. Blinking presence

Weakness
  • Instant presence flaps on bad networks.
Fix plus price
  • Heartbeat with a grace window such as 5 second beats and 30 second timeout as illustrative values from the chapter. Price. Presence lags reality by up to the window. You trade truth for calm UI.
06

Code: cursor sync plus heartbeat


This runnable Python demo models two chapter ideas. Devices sync by cur_max_message_id. Presence stays online only with recent heartbeat.

Run with python3 chat_demo.py. Values for beats and timeout are illustrative and mirror the 5 second and 30 second example in the chapter.

Show code
# chat_demo.py
import time

# KV store as list of dicts. Sorted by message_id.
# message_id is unique and time sortable per chapter.
KV = [
    {"message_id": 651, "to": "A", "text": "hi"},
    {"message_id": 654, "to": "A", "text": "are you there"},
    {"message_id": 843, "to": "A", "text": "meeting at 3"},
]

def get_new_messages(user_id, cur_max_message_id):
    # Lines that matter: two chapter conditions.
    # 1. recipient matches logged in user.
    # 2. stored ID is larger than device cursor.
    result = []
    for m in KV:
        if m["to"] == user_id and m["message_id"] > cur_max_message_id:
            result.append(m)
    return result

class Presence:
    def __init__(self, timeout_s):
        self.timeout_s = timeout_s
        self.last_heartbeat = {}
        self.status = {}

    def heartbeat(self, user_id, now):
        # Lines that matter: heartbeat refreshes last_active_at.
        self.last_heartbeat[user_id] = now
        self.status[user_id] = "online"

    def check(self, user_id, now):
        # Lines that matter: offline only after silence past x.
        last = self.last_heartbeat.get(user_id, 0)
        if now - last > self.timeout_s:
            self.status[user_id] = "offline"
        return self.status[user_id]

if __name__ == "__main__":
    # Multi device sync from Figure 12-13 values.
    phone_cursor = 653
    laptop_cursor = 842
    print("phone gets:", get_new_messages("A", phone_cursor))
    print("laptop gets:", get_new_messages("A", laptop_cursor))

    # Heartbeat logic from Figure 12-18.
    p = Presence(timeout_s=30)  # illustrative, matches chapter example
    t0 = 1000
    for i in range(3):
        p.heartbeat("A", t0 + i * 5)  # illustrative 5s beat
        print(f"beat {i+1} status:", p.check("A", t0 + i * 5))
    # Silence for 31 seconds.
    print("after silence status:", p.check("A", t0 + 10 + 31))

Output

phone gets: 654 are you there, 843 meeting at 3
laptop gets: 843 meeting at 3
beat 1 status: online, beat 2 status: online, beat 3 status: online
after silence status: offline
07

Field guide: who uses what and why


System or tool named in chapterUseWHY per chapter
Facebook initial sender pathHTTP for sendSimple request response is enough when the client starts the work and keep alive reuses connections
ZookeeperService discoveryRegisters chat servers and picks best server by location and capacity
Snowflake style generatorGlobal message IDGives unique time sortable IDs when NoSQL lacks auto_increment
Local sequencePer channel message IDOrder only matters inside one thread, so local is easier than global
Facebook Messenger storageHBase key value storeScales horizontally and reads recent history with low latency
Discord storageCassandra key value storeSame reason, proven for billions of messages
WeChat group approachPer inbox copy, group capped at 500 citedCopy per recipient is cheap when groups are small and sync stays simple
Slack edge cacheGeographically distributed cache for users and channelsImproves load time, listed as extra credit direction
08

Interview ears and judgment quiz


Follow ups with short answers.

Judgment quiz

Q1Predict. Phone cursor is 653 and laptop cursor is 842. Three new messages for User A arrive with IDs 844, 845, 846. What does each device fetch next.

Phone fetches 654, 843, 844, 845, 846. Laptop fetches 844, 845, 846. Reusing the laptop cursor on the phone would skip 654 and 843 and break (4).

Q2Compare. A quiet user sends one message per day. Compare long polling versus WebSocket for (1) and server cost.

Long polling still opens and times out repeatedly with no news. WebSocket holds one idle connection and pushes once. Long polling costs more setups for the same single delivery.

Q3Choose under tradeoff. You must support a 100,000 member announcement group with presence. Per inbox copy and per friend fanout both explode. What do you choose and what breaks.

Keep per inbox copy and instant fanout only for (2) up to 100. For the huge group, store once per channel and let members fetch history and presence on entry or refresh. You protect send cost but sacrifice instant presence for (3) in that large group.

Sources: System Design Interview, Chapter 12 Design A Chat System. Figures 12-13 cursor sync, 12-18 heartbeat, plus cited systems: Facebook Messenger on HBase, Discord on Cassandra, Zookeeper discovery, Snowflake IDs, WeChat 500 member cap, Slack edge cache.