A messaging app delivers short messages between people in real time, to phones that are often offline and on poor networks. This chapter designs a text chat service for one-to-one and group conversations, with delivery receipts and delivery to phones that are switched off.
The functional requirements are these. A user sends a message to another user or to a group. The recipient gets it within a second if the app is open, and as soon as the app next connects if not. The sender sees whether the message was sent (the server has it), delivered (the recipient's phone has it) and read (the recipient opened it). Messages in one conversation appear in the same order for everyone. We leave out voice and video calls, status posts and media upload. Photos and files would travel through the blob store chapter's design, with only a link inside the message.
The non-functional requirements are about trust and speed. A message the server has acknowledged must never be lost, even if a server crashes a moment later. A message must not appear twice. Delivery to an online user should usually take well under a second, which is our own target and not a published figure. The service must keep working while individual servers fail, and it must cope with crores of phones holding a connection open at once. Finally, messages should be readable only by the people in the conversation, which the last lesson covers at a high level.
Estimating messages and connections
A chat service is unusual because it holds state on both sides: every online user keeps a connection open for hours. So the estimate counts two things, the message rate and the number of open connections. The assumptions are 20 crore daily users, each sending 40 messages a day, 1.3 recipients per message on average because most chats are one to one and a few are groups, and a busy hour that runs at three times the daily average. We assume 30 percent of daily users are connected at the busiest moment, and that one connection server can hold 1 lakh connections. That last figure is a guess to be checked by a load test, not a fact.
python
import sys
dau = 20 * 10**7# 20 crore daily users, an assumption
sent_per_user = 40# messages sent per user per day# most chats are one to one, some are groups
avg_recipients = 1.3
seconds_per_day = 86_400
peak_factor = 3# share of daily users connected at the busiest hour
online_share = 0.3
conns_per_server = 100_000 # an assumption to check by load test
msg_bytes = 200# text plus headers, no media
sent_day = dau * sent_per_user
send_rate = sent_day / seconds_per_day
peak_send = send_rate * peak_factor
deliveries = peak_send * avg_recipients
connections = dau * online_share
servers = connections / conns_per_server
mbps = deliveries * msg_bytes * 8 / 1e6
stored_gb = sent_day * msg_bytes * avg_recipients / 1e9
print(sys.version.split()[0])
print(f"messages sent per day : {sent_day / 1e7:,.0f} crore")
print(f"sends per second, avg : {send_rate:,.0f}")
print(f"sends per second, peak : {peak_send:,.0f}")
print(f"deliveries per second : {deliveries:,.0f}")
print(f"open connections : {connections / 1e7:,.0f} crore")
print(f"connection servers : {servers:,.0f}")
print(f"payload bandwidth, peak : {mbps:,.0f} Mbps")
print(f"inbox bytes added a day : {stored_gb:,.0f} GB")
Python 3.12.10. Every assumption is a named line at the top.
text
3.12.10
messages sent per day : 800 crore
sends per second, avg : 92,593
sends per second, peak : 277,778
deliveries per second : 361,111
open connections : 6 crore
connection servers : 600
payload bandwidth, peak : 578 Mbps
inbox bytes added a day : 2,080 GB
Output of the script.
What the numbers decide
The message rate is large but ordinary: about 92,593 sends a second on average and 2,77,778 at the peak, which becomes 3,61,111 deliveries a second once groups are counted. Each message is small, so the payload bandwidth is about 578 Mbps, which one server's network card could carry. Framing, encryption and retries add to it, but not by an order of magnitude. Messages alone would not make this a hard system.
The connections do. Six crore open connections need about 600 connection servers at the assumed 1 lakh each. A connection is a long-lived piece of state: the server holds a socket, a buffer and the user's identity in memory for as long as the phone stays online. That is unlike the request and response services in earlier chapters, where any server could answer any request. Here, to deliver a message to Ravi, the system must find the one machine that holds Ravi's socket.
Number
What it decides
2,77,778 sends a second at peak
A stateless chat service tier that scales by adding servers
6 crore open connections
A separate tier of about 600 connection servers that holds sockets
2,080 GB of inbox data a day
A durable inbox store, sharded by recipient, with deletion after delivery
578 Mbps of payload at peak
Bandwidth is not the constraint; connection count and memory are
The inbox figure counts one copy of every message for every recipient, at 200 bytes each. It tells us that storing messages for days is cheap, and that it is much cheaper to delete a message after it is delivered than to keep it. Whether to keep history longer is a product choice, not a technical limit.
Why is the number of open connections the key number for a chat service, not the message rate?
Each connection is state held in a server's memory for hours, so the connection count sets the size of the connection tier. The message rate is moderate and the messages are small.
The estimate used 1.3 recipients per message. What does this assumption cover, and what would raise it?
It averages one-to-one chats and groups. Larger or more active groups raise it, and the delivery rate grows in proportion.
Which number in the estimate would you test first with a load test?
The 1 lakh connections per server. It is a guess, and it sets the size of the whole connection tier.
Part 2 · Connections: WebSockets and connection servers
Why a phone needs a persistent connection
Ordinary HTTP works by request and response: the client asks, the server answers. For chat the server has to speak first, because Ravi's phone cannot know that a message has arrived. There are four ways to arrange that, and the choice sets how the whole connection tier looks.
Method
How it works
Cost
Polling
The app asks every few seconds whether there is anything new
Most requests return nothing; delay up to the interval
Long polling
The app asks, and the server holds the request open until a message arrives or a timeout passes
One request per message, and a reconnect after each
Server-sent events
One long HTTP response the server keeps writing to
One direction only; the app still needs a separate request to send
WebSocket
One connection that both sides use freely in either direction
A socket held open per user
A WebSocket, defined in RFC 6455, gives a two-way channel over a single TCP connection. It is the usual choice for chat because messages flow in both directions without a new request each time, and each message adds only a few bytes of framing. The price is the held connection, and with it the stateful tier we sized in the previous lesson.
The upgrade handshake and frames
A WebSocket starts as an ordinary HTTP/1.1 request. The client sends a GET with the headers Upgrade: websocket, Connection: Upgrade, a random Sec-WebSocket-Key and Sec-WebSocket-Version: 13. If the server agrees, it answers 101 Switching Protocols with a Sec-WebSocket-Accept header. That value is the key with a fixed text identifier appended, hashed with SHA-1 and encoded in base64, which shows the server understood a WebSocket request and did not answer with some other reply. After the 101 response the same TCP connection carries WebSocket frames, not HTTP.
Frames have a small set of types, called opcodes: text, binary, close, ping and pong, plus a continuation frame for a message sent in pieces. A client must mask every frame it sends to the server, a rule the RFC gives as protection against confusing intermediaries such as proxies; server frames are not masked. A ping is a frame that the other side must answer with a pong carrying the same data, so either end can check that the connection is alive, and a pong sent unprompted works as a one-way heartbeat.
A phone changes networks, goes through tunnels and loses signal without ever closing the socket cleanly. The server may keep believing a dead connection is alive for minutes. That is why heartbeats matter: if no ping, pong or message arrives within a timeout, the server closes its end and frees the slot.
A server and two clients
The script starts a small chat server with the websockets library, version 17.4. Each client sends a first frame naming its user, and the server keeps a dictionary from user id to open connection. A message names its recipient. If the recipient is connected, the server forwards the message and tells the sender it was sent. If not, it replies undelivered. A first frame that is not valid JSON, or a message missing its recipient, id or text, is refused instead of crashing the handler. Before the clients run, the script also opens a plain socket and writes the HTTP upgrade by hand, to show the 101 response and to recompute Sec-WebSocket-Accept from the key.
python
# uv run --python 3.12 --with websockets==17.4 ms2_ws.pyimport asyncio, base64, hashlib, json
from websockets.exceptions import ConnectionClosed
from websockets.asyncio.client import connect
from websockets.asyncio.server import serve
PORT = 55533# user id -> open connection
users = {}
Python 3.12.10 with websockets 17.4. Run: uv run --python 3.12 --with websockets==17.4 ms2_ws.py. Port 55533. Part 1 of 6; save all parts in one file, ms2_ws.py.
python
asyncdef handler(ws):
try:
# first frame names the user
user = json.loads(await ws.recv())["user"]
except ConnectionClosed:
# a socket that never said helloreturnexcept (ValueError, KeyError, TypeError):
await ws.close(1008, "first frame must name a user")
return
users[user] = ws
Continues ms2_ws.py (part 2 of 6), same file.
python
try:
asyncfor raw in ws:
try:
msg = json.loads(raw)
to, mid, text = msg["to"], msg["id"], msg["text"]
except (ValueError, KeyError, TypeError):
await ws.send(json.dumps({"type": "error"}))
continue
peer = users.get(to)
if peer isNone:
reply = {"type": "undelivered", "id": mid}
await ws.send(json.dumps(reply))
else:
out = {"type": "msg", "from": user,
"id": mid, "text": text}
await peer.send(json.dumps(out))
await ws.send(json.dumps({"type": "sent", "id": mid}))
finally:
# a late close must not remove a newer connectionif users.get(user) is ws:
del users[user]
Continues ms2_ws.py (part 3 of 6), same file.
python
asyncdef raw_handshake():
"""Open a socket by hand and show the HTTP upgrade."""
key = base64.b64encode(b"sixteen byte key").decode()
r, w = await asyncio.open_connection("127.0.0.1", PORT)
w.write((f"GET / HTTP/1.1\r\nHost: 127.0.0.1:{PORT}\r\n"
f"Upgrade: websocket\r\nConnection: Upgrade\r\n"
f"Sec-WebSocket-Key: {key}\r\n"
f"Sec-WebSocket-Version: 13\r\n\r\n").encode())
head = (await r.readuntil(b"\r\n\r\n")).decode().split("\r\n")
w.close()
guid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
sha = hashlib.sha1((key + guid).encode()).digest()
mine = base64.b64encode(sha).decode()
for line in head:
if line andnot line.startswith("Date"):
print(line)
accept = [h for h in head
if h.lower().startswith("sec-websocket-accept")][0]
print("my Accept matches:", accept.split(": ")[1] == mine)
waiter = await asha.ping()
print("ping answered in under a second:",
await asyncio.wait_for(waiter, 1) isnotNone)
asyncio.run(main())
Continues ms2_ws.py (part 6 of 6), same file.
text
HTTP/1.1101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: Ie+g9r+I6SGMbPuXkjkAvUhJdto=
Server: Python/3.12 websockets/17.4
my Accept matches: True
asha got : {"type": "sent", "id": "m1"}
ravi got : {"type": "msg", "from": "asha", "id": "m1", "text": "hello"}
asha got : {"type": "undelivered", "id": "m2"}
asha got : {"type": "error"}
kavya still registered: True
ping answered in under a second: True
Output of the script.
What the run shows
The first block is the server's reply to the hand-written request: 101 Switching Protocols, the Upgrade and Connection headers, and a Sec-WebSocket-Accept value. The line "my Accept matches: True" means a SHA-1 and base64 computed by us from the key and the fixed identifier gave the same string, so the handshake is no more than that. The Server line shows the library and its version.
Then the two clients chat. Asha sends m1 to Ravi, and she receives sent while Ravi receives the message with her name and the id. A message to Meena, who is not connected, comes back as undelivered. The ping is answered within the one-second limit the script sets.
Two lines of the output come from the guards in the handler. The bad frame gets an error reply and the connection stays open. And when Kavya's phone opens a second socket before the first closes, the first socket's late close does not remove her new entry, because the handler deletes the entry only if it still holds that socket. Without that check, a version of this script we tried dropped the new entry, so Kavya looked offline while connected. The same stale-close problem returns in the next lesson at the scale of many servers. The Date header is left out of the printed reply because it changes on every run.
Notice the weakness in this server. The users dictionary lives in one process, so it only knows people connected to this one server. With 600 connection servers, Asha and Ravi will usually sit on different ones, and a dictionary in one process cannot find the other. The next lesson adds a directory shared by all servers.
Why does a WebSocket begin as an HTTP request?
Proxies and firewalls already understand HTTP on ports 80 and 443. The upgrade lets the connection pass through them and then switches protocol with a 101 response.
What does a ping and pong exchange tell a connection server?
That the other end is still reachable. If neither a pong nor any message arrives within a timeout, the server closes the connection and frees its memory.
In the script, why does the message to Meena return undelivered?
Meena has no connection registered in the server's dictionary, so there is nowhere to push the message. A real service would store it in her inbox.
Part 3 · High-level design and a session directory
The parts and what each owns
With sockets held by a stateful tier, the rest of the design keeps its own state small. Each part has one job.
Part
Owns
State
Connection servers
Sockets, heartbeats, framing; they decode a message and pass it on
In memory, lost when the server dies
Session directory
Which connection server holds which user right now
A small key-value store with expiry
Chat service
Checks a message, asks the inbox shard to store it and number it, routes it
None; any instance can serve any request
Inbox store
Every undelivered message for every user, in order
Durable, sharded by recipient id
Push gateway
A wake-up notification for phones with no connection
None
Presence service
Who is online and when they were last seen
Short-lived, expires on its own
Phones reach the connection tier through a load balancer, but the job changes. The balancer chooses a server once, when the socket opens, and the choice then holds for hours, so a request-by-request rule cannot correct a bad one later. Least connections, covered in the load balancer chapter, suits this better than round robin: it sends each new socket to the server holding the fewest, so servers that have been up longest do not drift far above the rest. Two events need care. Before a deploy, the balancer stops sending new sockets to a server and its phones are asked to reconnect a few at a time. And if a server restarts and drops every socket at once, the phones must wait a random delay before reconnecting, or the other servers meet a stampede.
The important choice is that the inbox store is the source of truth. The connection servers and the directory are a fast path for messages to travel by, but they hold nothing that cannot be rebuilt. If a connection server crashes, its users reconnect elsewhere and ask the inbox for what they missed. That makes crashes an inconvenience for the user rather than a source of lost messages.
Finding the user's connection server
When Asha sends a message to Ravi, the chat service needs to know which of 600 connection servers has Ravi's socket. The session directory answers that: a map from user id to a server id. It is a key-value store of the kind built in the key-value store chapter, sharded across a few machines, with one write when a user connects and one lookup per message.
The directory must not hold a user who is gone, so each entry is a lease, as in the task scheduler chapter: a claim that expires unless it is renewed. The connection server renews the entries of its users on a heartbeat, and a renewal only counts if that server still owns the entry. If the server dies, its entries lapse by themselves within one lease period, and no one has to clean up. The lease length trades speed against load: a short lease clears dead servers quickly but means more renewal writes.
One more rule prevents a subtle bug. When a phone moves from Wi-Fi to mobile data it reconnects, perhaps to a different server, before the old connection has been noticed as dead. The old server may later say goodbye and delete the user's entry, and with it the new one. So a delete names the server it comes from, and the directory ignores it unless that server still owns the entry.
The directory in code
The script below models a directory with a fake clock, so that time can jump. It registers two users with a 30-second lease, renews one at t=20, looks both up at t=40, then moves Asha to a new server and sends a late goodbye and a late heartbeat from the old one.
python
class Clock:
def __init__(self):
self.now = 0.0class Directory:
"""user id -> (connection server, lease expiry)."""def __init__(self, clock, lease=30):
self.clock, self.lease, self.rows = clock, lease, {}
def register(self, user, server):
self.rows[user] = (server, self.clock.now + self.lease)
def lookup(self, user):
row = self.rows.get(user)
if row and row[1] > self.clock.now:
return row[0]
returnNonedef renew(self, user, server):
"""Heartbeat: extend the lease, but only for its owner."""
row = self.rows.get(user)
if row and row[0] == server and row[1] > self.clock.now:
self.rows[user] = (server, self.clock.now + self.lease)
returnTruereturnFalsedef unregister(self, user, server):
# ignore a stale goodbye
row = self.rows.get(user)
if row and row[0] == server:
del self.rows[user]
Python 3.12.10, standard library. The clock is a number we set by hand. Part 1 of 2; save all parts in one file, ms3_directory.py.
python
clock = Clock()
d = Directory(clock)
d.register("asha", "conn-1")
d.register("ravi", "conn-2")
print("t=0 asha is on", d.lookup("asha"))
clock.now = 20
d.renew("asha", "conn-1") # heartbeat renews the lease# conn-2 died at t=0 and never renewed
clock.now = 40
print("t=40 asha is on", d.lookup("asha"),
"| ravi is on", d.lookup("ravi"))
# asha's phone moves from wifi to mobile data: she reconnects to conn-3
d.register("asha", "conn-3")
# late close from the old connection
d.unregister("asha", "conn-1")
print("t=40 asha is on", d.lookup("asha"), "(old goodbye ignored)")
# a late heartbeat from the old server must not take her back
print("renew from conn-1:", d.renew("asha", "conn-1"))
print("t=40 asha is on", d.lookup("asha"))
d.unregister("nobody", None) # unknown user: no error
Continues ms3_directory.py (part 2 of 2), same file.
text
t=0 asha is on conn-1
t=40 asha is on conn-1 | ravi is on None
t=40 asha is on conn-3 (old goodbye ignored)
renew from conn-1: False
t=40 asha is on conn-3
Output of the script.
At t=40 Asha is still on conn-1 because her heartbeat at t=20 renewed the lease until t=50. Ravi's server conn-2 stopped renewing at t=0, so his entry expired at t=30 and the lookup returns None. When Asha is registered on conn-3 and the old conn-1 unregisters her late, the directory keeps conn-3, because the goodbye came from a server that no longer owns the entry. The late heartbeat from conn-1 is refused for the same reason: renew returns False. Had the heartbeat used register, as our first version did, it would have taken Asha back to conn-1, where she is no longer connected. A goodbye for a user the directory has never seen does nothing.
A lookup can still be wrong for a short time, for example right after a server fails and before the lease lapses. That is acceptable, because a wrong guess costs nothing but a detour. The connection server that receives a message for a user it does not hold answers that the user is not here, and the chat service falls back to the inbox and the push gateway. The message is already stored, so it is never lost.
Why is the inbox store, and not the session directory, the source of truth?
The directory only says where a connection is now and can be stale or lost. The inbox holds every undelivered message durably, so a crash or a wrong lookup loses nothing.
What happens to the directory entries of a connection server that crashes?
Nothing is done. Each entry is a lease that the server renewed on a heartbeat, so the entries expire on their own within one lease period.
Why does a delete from a connection server name the server?
A user can reconnect elsewhere before the old connection closes. A delete that names its server is ignored once another server owns the entry, so the old goodbye does not erase the new one.
Part 4 · Delivery, receipts and offline sync
Sequence numbers and idempotent sends
Three problems appear as soon as a message goes over a bad network. The sender may not know whether a send worked, so it retries and the recipient gets two copies. The recipient may be offline when the message is stored. And two messages may arrive in the wrong order. One small mechanism handles all three: ids and sequence numbers.
The sender's app creates a message id before it sends anything and sends the same id on every retry. The server remembers the ids it has stored, per sender, and when it sees an id again it returns the earlier result and stores nothing new. That is an idempotency key, as in the core concepts chapter. The server also gives each message a sequence number in the recipient's inbox, 1, 2, 3 and so on, assigned by the single shard that owns that inbox. Because one writer assigns the numbers, they give a total order for that recipient with no clock involved.
The recipient's phone remembers the highest sequence number it has received. A phone that sees a jump, say 4 after 2, knows it missed one and asks for it. A phone that sees a number it already holds throws the duplicate away. Delivery from the server to the phone is therefore at-least-once, as in the message queue chapter, and the sequence numbers turn that into effectively once for the user.
The inbox in code
The script models one chat server with the rules above. send is called by the sender's app, ack and read by the recipient's app, and connect is what a phone does when it comes online. We print the receipt state after each step.
python
class Server:
def __init__(self):
# user -> list of (seq, msg_id, sender, text)self.inbox = {}
# user -> last sequence number handed outself.last_seq = {}
# (sender, msg_id) -> seq, so retries are harmlessself.seen = {}
# (sender, msg_id) -> sent | delivered | readself.status = {}
# user -> highest seq the device confirmedself.acked = {}
# user -> device inbox list when connectedself.online = {}
Python 3.12.10, standard library. Part 1 of 4; save all parts in one file, ms4_delivery.py.
python
def send(self, sender, to, msg_id, text):
key = (sender, msg_id)
# client retried after a timeoutif key inself.seen:
returnself.seen[key]
box = self.inbox.setdefault(to, [])
# per-recipient sequence number
seq = self.last_seq.get(to, 0) + 1self.last_seq[to] = seq
box.append((seq, msg_id, sender, text))
self.seen[key] = seq
# one tick: the server has itself.status[key] = "sent"if to inself.online:
self.online[to].append((seq, msg_id, sender, text))
return seq
def ack(self, user, seq):
self.acked[user] = max(self.acked.get(user, 0), seq)
for (s, mid, sender, _t) inself.inbox.get(user, []):
if s <= seq andself.status[(sender, mid)] == "sent":
self.status[(sender, mid)] = "delivered"# two ticksdef read(self, user, seq):
# a read receipt also means deliveredself.ack(user, seq)
for (s, mid, sender, _t) inself.inbox.get(user, []):
if s <= seq:
self.status[(sender, mid)] = "read"# blue ticks
Continues ms4_delivery.py (part 2 of 4), same file.
python
def purge(self, user):
"""Delete what the device has confirmed."""
done = self.acked.get(user, 0)
box = self.inbox.get(user, [])
self.inbox[user] = [m for m in box if m[0] > done]
def connect(self, user, last_seq):
"""Return what comes after the device's last sequence."""self.online[user] = []
return [m for m inself.inbox.get(user, []) if m[0] > last_seq]
srv = Server()
print("send m1 ->", srv.send("asha", "ravi", "m1", "are you coming?"))
print("retry m1 ->", srv.send("asha", "ravi", "m1", "are you coming?"))
print("send m2 ->", srv.send("asha", "ravi", "m2", "bring the notes"))
print("status", srv.status)
missed = srv.connect("ravi", last_seq=0) # ravi opens the app
print("ravi syncs:", [(m[0], m[3]) for m in missed])
srv.ack("ravi", missed[-1][0])
print("after ack ", srv.status)
srv.read("ravi", 1)
print("after read", srv.status)
seq = srv.send("asha", "ravi", "m3", "ok?")
print("send m3 while ravi is connected ->", seq)
print("pushed live:", srv.online["ravi"])
Continues ms4_delivery.py (part 3 of 4), same file.
python
# the inbox is trimmed after acks, and numbers still never repeat
srv.purge("ravi")
print("inbox after purge:", [m[0] for m in srv.inbox["ravi"]])
print("send m4 after purge ->", srv.send("asha", "ravi", "m4", "bye"))
# a read receipt that overtakes the delivery ack still counts
late = Server()
late.send("asha", "ravi", "m1", "hi")
late.read("ravi", 1)
print("read before ack:", late.status)
Continues ms4_delivery.py (part 4 of 4), same file.
text
send m1 -> 1
retry m1 -> 1
send m2 -> 2
status {('asha', 'm1'): 'sent', ('asha', 'm2'): 'sent'}
ravi syncs: [(1, 'are you coming?'), (2, 'bring the notes')]
after ack {('asha', 'm1'): 'delivered', ('asha', 'm2'): 'delivered'}
after read {('asha', 'm1'): 'read', ('asha', 'm2'): 'delivered'}
send m3 while ravi is connected -> 3
pushed live: [(3, 'm3', 'asha', 'ok?')]
inbox after purge: [3]
send m4 after purge -> 4
read before ack: {('asha', 'm1'): 'read'}
Output of the script.
Sending m1 returns sequence 1, and sending m1 again returns 1 and stores nothing new, so the retry was harmless. Ravi connects with last_seq=0 and receives messages 1 and 2 in order. Acknowledging up to 2 moves both to delivered, and read on 1 moves only the first. A message sent while Ravi is connected is stored as sequence 3 and also pushed live.
The last lines of the script cover two cases we first got wrong. Numbers come from a counter, not from the length of the inbox: our first version used the length, and after the inbox was trimmed the next message would have been given sequence 1 again. After purge removes what Ravi has confirmed, only 3 is left and the next message is 4. And a read receipt can overtake the delivery acknowledgement, since they are separate small messages, so read counts as an acknowledgement too; a message never shows read without having been delivered.
Receipts as a state machine
The ticks a sender sees are a small state machine for each message. A message begins as sending on the sender's phone. If the server stores it, the state becomes sent, one tick. If the phone gets no answer, the send times out and the message becomes failed, with a retry button that goes back to sending. When the recipient's device acknowledges the sequence number the state becomes delivered, and when the chat is opened it becomes read. Each step is itself a small message travelling the other way, and each is idempotent, so a repeat changes nothing.
Animated sceneA message's receipt states0:19
Watch for a failed send going back to sending
Read it as steps
A message moves from sending to sent, delivered and read, and a failed send can retry.
The scene runs one message through the states, including the retry. A state machine makes the allowed moves explicit: a message cannot go from sent straight to read without the delivered step, and a message that is read has nowhere to go.
When the recipient is offline
If Ravi has no connection, the directory returns nothing and the chat service stores the message in his inbox, then asks the push gateway to send a wake-up notification. The notification carries no message, only the news that something is waiting, so it can pass through the phone vendor's push service without exposing content. When Ravi's app opens, it connects, tells the server its last sequence number, and the server sends everything after it. This is offline sync.
Animated sceneOne message online, one offline0:23
Watch for the second message waiting while Ravi is offline
Read it as steps
Ravi's phone acknowledges a live message, then syncs a stored one after reconnecting.
In the scene the inbox plays the part of a durable queue. The live push is an optimisation: if it fails, the sync still finds the message.
A phone retries a send three times because it saw no answer. How does the server avoid storing three copies?
The app sends the same message id each time. The server has stored that id for the sender, returns the first result for each retry, and stores nothing new.
The phone receives sequence 4 right after sequence 2. What should it do?
It missed number 3, so it asks the server for messages after 2. Sequence numbers from a single writer make a gap visible.
Why does the push notification contain no message text?
It goes through a third party's push service. A content-free wake-up avoids exposing the message, and the app fetches the real message from the server over its own connection.
Part 5 · Groups
Fan-out for a group message
A group message is one send with many recipients. The microblog chapter weighed fan-out on write against fan-out on read. For chat the answer is fan-out on write. The message is copied into every member's inbox when it is sent, so each member's phone syncs from its own inbox with the same logic as a one-to-one chat, including sequence numbers, receipts and offline sync. Groups then cost the delivery path nothing new.
Writes are multiplied by the group size. With a limit of 1,024 members, which is our own assumption, a message produces up to 1,023 inbox writes. That is acceptable, because a message is small and a group has a limit. A broadcast channel with millions of followers is a different product, and for it fan-out on read is better: members pull from one shared log instead of receiving a copy each.
Order within a group matters, because replies make no sense out of order. The group is owned by one shard that assigns each message a group sequence number, and every member's inbox stores that number. Everyone then sees the same order, at the cost of making that shard the single writer for the group.
Reaching many connection servers
After the copies are stored, the live push must reach each member who is online. The group's members are spread over many connection servers. A naive loop sends one internal message per member. A better one groups the members by the connection server that holds them and sends one internal message per server, carrying the list of users on that server. The server then writes to each of its local sockets.
The script below puts six members of a group on two connection servers, with one member offline, and counts the messages that cross between servers in both styles. It then repeats the count for a group of 1,024 members spread over 50 servers.
python
from collections import defaultdict
members = {"trip": ["asha", "ravi", "meena", "john", "kavya", "dev"]}
home = {"asha": "conn-1", "ravi": "conn-1", "meena": "conn-1",
"john": "conn-2", "kavya": "conn-2"} # dev is offline# user -> messages stored
inbox = defaultdict(list)
# messages sent between servers
hops = []
Python 3.12.10, standard library. Part 1 of 3; save all parts in one file, ms5_groups.py.
python
def post_to_group(sender, group, text, batch):
"""Store once per member, then push to servers with connections."""if sender notin members.get(group, []):
raise PermissionError(f"{sender} is not in {group}")
targets = [m for m in members[group] if m != sender]
for m in targets:
inbox[m].append((sender, text)) # fan-out on write
by_server = defaultdict(list)
for m in targets:
# offline members just have an inboxif m in home:
by_server[home[m]].append(m)
sender_server = home[sender]
for server, users in by_server.items():
if server == sender_server:
# local push, no hop between serverscontinueif batch:
# one hop carries the member list
hops.append((server, users))
else:
# one hop per member
hops.extend((server, [u]) for u in users)
return by_server
Continues ms5_groups.py (part 2 of 3), same file.
python
by_server = post_to_group("asha", "trip", "train at 6", batch=True)
for server, users in by_server.items():
print("servers touched:", server, users)
print("hops between servers, batched :", len(hops))
hops.clear()
post_to_group("asha", "trip", "platform 4", batch=False)
print("hops between servers, per member:", len(hops))
for user, msgs in sorted(inbox.items()):
print("inbox", user, len(msgs))
# A large group: 1,024 members spread over 50 servers
members["fest"] = [f"u{i}"for i in range(1024)]
home.update({f"u{i}": f"conn-{i % 50}"for i in range(1024)})
hops.clear()
post_to_group("u0", "fest", "welcome", batch=True)
batched = len(hops)
hops.clear()
post_to_group("u0", "fest", "welcome", batch=False)
print(f"group of 1,024 on 50 servers: batched {batched} hops,",
f"per member {len(hops)}")
try:
post_to_group("outsider", "trip", "hi", batch=True)
except PermissionError as e:
print("rejected:", e)
Continues ms5_groups.py (part 3 of 3), same file.
text
servers touched: conn-1 ['ravi', 'meena']
servers touched: conn-2 ['john', 'kavya']
hops between servers, batched : 1
hops between servers, per member: 2
inbox dev 2
inbox john 2
inbox kavya 2
inbox meena 2
inbox ravi 2
group of 1,024 on 50 servers: batched 49 hops, per member 1003
rejected: outsider is not in trip
Output of the script.
Reading the counts
Asha's server conn-1 also holds Ravi and Meena, so they are reached without leaving that server. John and Kavya are on conn-2. The batched style sent one internal message, with John and Kavya in it. The per-member style sent two. Dev is offline and has no server, so his copy is only stored in his inbox, which is the right place for it: when he connects he syncs it. Every member except Asha has two messages in the inbox because the script posted twice, once in each style.
With 1,024 members on 50 servers, the batched style needs 49 internal messages, one for every server except the sender's own. The per-member style needs 1,003, one for each member not on the sender's server. The ratio grows with the group size and with the number of members that share a server. Every one of the 1,023 inboxes is still written in both cases, so the batching saves network hops but not storage.
Two more details complete the picture. Membership changes are versioned: each group message is delivered to the members as they were when it was sent, so someone added later does not receive earlier messages, and someone removed stops receiving new ones. And receipts for groups are aggregated: the sender sees delivered once the server has an acknowledgement from every member, and the detail by person is kept in the group message's own record, readable on request.
The fan-out in a picture
Animated sceneA group message across two servers0:22
Watch for one hop to each other server, not one per member
Read it as steps
The group message is stored per member and sent once to each other connection server.
The scene shows the two jobs apart. Storing a copy for each member makes the message durable, and the push is only a way of delivering it sooner. A member who is offline still has the copy waiting in the inbox.
Why use fan-out on write for a group of up to 1,024 members?
Each member then syncs from their own inbox with the same logic as a one-to-one chat, and the cost, at most 1,023 small writes per message, is acceptable for a bounded group.
The script counted 49 hops batched and 1,003 per member. What is batching saving?
Network messages between servers. Members on the same server share one internal message. Inbox writes are the same in both styles.
How does every member of a group see messages in the same order?
One shard owns the group and assigns a group sequence number to each message. Every member's inbox stores that number, so the order is the same for all of them.
Part 6 · Encryption, presence, storage and failures
Encryption at a high level
In end-to-end encryption the phones hold the keys and the server relays messages it cannot read. The Signal project publishes its protocol specifications at signal.org/docs. They name four pieces worth knowing. X3DH and PQXDH, an extension of it that adds post-quantum protection, let two parties agree on a shared secret even when one is offline: the X3DH specification is written for asynchronous settings, and the offline user publishes keys to a server in advance. The Double Ratchet then gives every message a new key, so a stolen key exposes little. Sesame manages sessions when a user has several devices. We do not implement any of this. We only design for it.
Encryption changes the design in ways that are easy to miss. The server cannot search message text, scan it for abuse, or build a preview. A group message must reach every member's devices in a form each can decrypt, which affects how many bytes the fan-out carries. Backups made on a server must hold only ciphertext. And not everything in a product is encrypted the same way: a WhatsApp help page, for example, lists chats that are not end-to-end encrypted, such as payments and some business chats run through other services. A design should say, per feature, who can read what.
Presence
Presence is the "online" and "last seen" indicator. It is cheap to compute and costly to publish. A phone sends a heartbeat every few seconds while the app is open. The presence service stores the time of the latest one, and a user counts as online if the time is within a timeout, a lease by another name. After that the user shows as last seen at that time.
python
class Presence:
def __init__(self, ttl=15):
self.ttl, self.last = ttl, {}
def heartbeat(self, user, now):
# a delayed older heartbeat must not move the time backself.last[user] = max(now, self.last.get(user, now))
def status(self, user, now):
t = self.last.get(user)
if t isNone:
return"unknown"if now - t <= self.ttl:
return"online"return f"last seen {now - t:.0f} s ago"
p = Presence(ttl=15)
# phone sends a heartbeat every 5 sfor t in (0, 5, 10):
p.heartbeat("asha", t)
p.heartbeat("asha", 4) # arrives late
print("last heartbeat kept:", p.last["asha"])
for t in (12, 30, 70):
print(f"t={t:3} asha:", p.status("asha", t))
print("never seen:", p.status("kavya", 0))
Python 3.12.10, standard library. Part 1 of 2; save all parts in one file, ms6_presence.py.
python
# cost: push a change only to contacts who have her chat open right now
contacts, viewing = 300, 4
changes_per_hour = 20# she goes online and offline
print("push to all contacts:", contacts * changes_per_hour,
"updates per hour")
print("push to viewers only :", viewing * changes_per_hour,
"updates per hour")
Continues ms6_presence.py (part 2 of 2), same file.
text
last heartbeat kept: 10
t= 12 asha: online
t= 30 asha: last seen 20 s ago
t= 70 asha: last seen 60 s ago
never seen: unknown
push to all contacts: 6000 updates per hour
push to viewers only : 80 updates per hour
Output of the script.
The heartbeats came at 0, 5 and 10 seconds with a 15-second timeout. At t=12 Asha is online. A heartbeat that arrives late, stamped 4 after the one at 10, is ignored, so a delayed packet cannot make her look offline earlier than she was. At t=30 her last heartbeat is 20 seconds old, so she shows as last seen 20 seconds ago, and a user the service has never heard from is unknown. The last two lines are the cost. If Asha has 300 contacts and changes state 20 times an hour, telling every contact makes 6,000 updates an hour. Telling only the few who currently have her chat open makes 80. Presence is delivered to viewers, never broadcast to everyone.
Storage and failures
The inbox store is sharded by recipient id, so one shard holds a user's whole inbox and assigns its sequence numbers. Recent messages sit in a fast store, and once a device has acknowledged a message the server may delete it. Then storage holds only what is still undelivered. The 2,080 GB a day computed earlier would pile up only if history were kept. Whether to keep a server-side history is a product decision that also affects encryption and backups.
Failure
What happens
Why nothing is lost
A connection server crashes
Its users reconnect to other servers, with random delay to avoid a stampede
The inbox holds every unacknowledged message
A directory entry is stale
A message is routed to a server that no longer holds the user
That server answers not here; the message is already stored
The push gateway is down
Phones are not woken
Messages wait; they sync when the app next opens
A phone loses signal mid-send
No answer reaches the sender
The retry carries the same message id, so no duplicate
An inbox shard fails
Sends to its users fail until a replica takes over
The sender keeps the message as failed and retries
The recurring answer is the one from the design lesson: the inbox is durable, and everything faster than the inbox is rebuildable. The trade-offs we accepted are visible too. Fan-out on write makes groups simple and writes heavy. A single writer per inbox gives order and creates a hot spot. Strict end-to-end encryption removes server-side search. A design that states these costs is more credible than one that claims there are none.
Why is presence published only to users who have the chat open?
Broadcasting every change to all contacts multiplies updates, 6,000 an hour for one user in the example. Sending it only to current viewers cut that to 80.
What can the server not do once messages are end-to-end encrypted?
It cannot read, search or scan message text. It can relay and store ciphertext, and it sees metadata such as who sent to whom and when.
A connection server dies with 1 lakh users connected. What keeps their messages safe?
The messages are in the inbox store, not in the server's memory. The users reconnect to other servers and sync everything after their last sequence number.