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.
Key points
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.
messages per day divided by 86,400
connections times KB each
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.
We design a Messenger style app for both mobile and web.
Numbered requirements:
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.
| Stat from chapter | Value |
|---|---|
| Design target | 50 million DAU |
| Group limit in scope | max 100 people |
| Text limit | less than 100,000 characters |
| History retention | forever |
| Industry volume cited | 60 billion messages per day for Messenger and WhatsApp |
| Derived rate from that volume | 60,000,000,000 / 86,400 = about 694,000 per second |
| Memory sketch for connections | 1M x 10K = about 10GB |
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.
Press Send. One post, one key, one inbox, end to end.
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.
each ask costs work
answers with news
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.
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.
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.
ID generator.WebSocket.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.
Press Sync now to replay from each cursor.
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.
one per recipient inbox
each member checks self
small vs huge group
Now: 3 members needs 2 copies. Simple and cheap.
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:
| Column | Type | Note |
|---|---|---|
| message_id | bigint | primary key, defines order |
| message_from | bigint | sender |
| message_to | bigint | recipient |
| content | text | under 100,000 characters per (6) |
| created_at | timestamp | cannot define order alone because two messages can share a timestamp |
Group message table:
| Column | Type | Note |
|---|---|---|
| channel_id | bigint | partition key, channel means group |
| message_id | bigint | sort key within channel |
| user_id | bigint | sender |
| content | text | text only |
| created_at | timestamp | wall 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.
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.
Idle. Beats refresh last_active_at. Silence past 30 seconds flips to offline.
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.
# 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
m["message_id"] > cur_max_message_id is the replay rule that lets phone and laptop diverge safely.now - last > timeout is the flap guard that prevents blinking presence in tunnels.timeout_s=30 and 5 second beats are illustrative values taken from the chapter example to show the logic, not production tuning.| System or tool named in chapter | Use | WHY per chapter |
|---|---|---|
| Facebook initial sender path | HTTP for send | Simple request response is enough when the client starts the work and keep alive reuses connections |
| Zookeeper | Service discovery | Registers chat servers and picks best server by location and capacity |
| Snowflake style generator | Global message ID | Gives unique time sortable IDs when NoSQL lacks auto_increment |
| Local sequence | Per channel message ID | Order only matters inside one thread, so local is easier than global |
| Facebook Messenger storage | HBase key value store | Scales horizontally and reads recent history with low latency |
| Discord storage | Cassandra key value store | Same reason, proven for billions of messages |
| WeChat group approach | Per inbox copy, group capped at 500 cited | Copy per recipient is cheap when groups are small and sync stays simple |
| Slack edge cache | Geographically distributed cache for users and channels | Improves load time, listed as extra credit direction |
Follow ups with short answers.
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.