Design WhatsApp
hard 50 minBuild a messenger like WhatsApp: one-to-one and group chats, ticks, presence and several devices per person.
See it run
A messenger, one hop at a time: connecting, sending, waiting, ticks, retries, presence and groups.
Operations
Open the connection
An HTTPS request becomes a two-way connection, after the token is checked.
Step 1 of 8
Upgrade request
The phone sends an HTTPS request that asks to become a WebSocket, with its token. Why: it passes ordinary firewalls and balancers.
Step 1: Upgrade request
def connect(request): user, device = auth.check(request.token) # before keeping a socket socket = request.upgrade() # 101 Switching Protocols n = next_connection_number() registry.set(device, (MY_SERVER, n)) for entry in inbox.after(device, request.cursor): socket.push(entry) return socket- Latency
- once
- Load
- 100M open
- Per server
- 100,000
- Servers
- 1,250
Check the token first. Each open socket uses memory and a file descriptor.
In the real world
The same design whatsapp doing real jobs. Pick one and step through it.
100,000 phones lose their connection at once.
Step 1 of 4
Server 2 stops
inbox
121
Sockets close. Entry 121 is in the inbox, not yet delivered.
Step 1: Server 2 stops
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Acknowledging before storing
criticalA crash loses a message the sender believes is safe.
Wrongsession.reply("accepted")log.append(msg)Rightlog.append(msg) # 2 of 3 zonessession.reply("accepted")Claiming the ID before the work
criticalIf the server dies after the claim, the retry is told it was done.
Wrongif cache.set_if_absent(id): log.append(msg)Rightif not cache.seen(id): log.append(msg) cache.add(id)# the receiver drops any repeatOne topic per user
majorHundreds of millions of topics cannot be run.
Wrongtopic = f"offline_{user}"Rightlog.append(topic="inbox", key=user)Deleting each entry after its ack
majorEach delete leaves a marker that later reads must step over.
Wrongfor n in acked: inbox.delete(device, n)Rightinbox.move_cursor(device, last)inbox.delete_range(device, upto=last) # now and thenPresence to every contact
majorNearly all of those notices are never seen.
Wrongfor c in contacts(user): notify(c)Rightfor v in viewers(user): notify(v)
Interview tips
Start from the promise
- Say what one tick means.
- Commit before you reply.
- Clear after the ack.
Bring two numbers
- 700K sends a second at peak.
- 4.8M deliveries a second at peak.
- The gap is groups and devices.
Show a failure
- Lost ack: same ID.
- Dead server: lease and cursor.
- Lost push: inbox.
Know where to stop
- A million users need version 3.
- Huge rooms need another fan-out.
- Calls are a different system.