To design WhatsApp is to build a chat system where a message typed on one phone appears on another within a fraction of a second, even when the network is poor, the recipient is offline, or the chat has 500 members. A good answer explains the long-lived connection each phone keeps, how a message is accepted, numbered and stored before anything else, how it is delivered and acknowledged without loss or repeats, how every member sees the same order, how a phone or laptop catches up after being away, how group messages and presence status are kept cheap, and what happens when a gateway crashes and every phone returns at once.
This lesson designs PingMe, a chat app for a college hostel network where mobile data is weak and phones drop off several times an hour. Six runnable programs in Java, with Python and C++ versions, test the decisions interviewers probe most: delivery guarantees, message ordering, catching up after being offline, group storage, presence, and reconnect storms. All sizes, rates and timings are assumptions chosen to make comparisons clear, not benchmarks of a product.
Key takeaways
Sending once lost 9,904 of 100,000 messages on a network that drops 10 packets in 100. Retrying until an acknowledgement arrived lost none, but 10,022 messages were shown twice. A message id made by the sender and a receiver that shows each id once removed every repeat, at the price of 23,481 extra packets.
Ordering by arrival gave two members different orders in 11,116 of 20,000 chats. Ordering by the phone clock of the sender (off by up to 2 seconds) put 14,454 of 87,840 replies above their question. A number given by the server for each message in a chat gave 0 and 0.
A queue that deletes a message after the first device confirms it left 780,993 messages that never reached the laptop. A log with a last-seen number per device delivered all of them, in 1,561,986 messages instead of 81,561,986 when the whole chat was sent again.
A copy of every group message for every member used 2,828.6 MB and wrote 499 rows for one message in the largest group. A shared log with one small state row per member used 52.7 MB and wrote 1 row.
Telling every contact about every connect and disconnect made 63,332,138 pushes an hour. Waiting 30 seconds before announcing cut it to 18,914,062. Telling only contacts who had the chat open cut it to 379,978.
When 20,000 phones reconnected at once to a login service that accepts 1,000 a second, backoff with no randomness took 896 seconds. Backoff with a random wait took 78 seconds and wasted 57,932 attempts instead of 190,000.
1. Clarifying Requirements
Functional requirements
Send and receive text messages in one-to-one chats and in groups of up to 500 members.
Show sent, delivered and read status for each message.
Show whether a contact is online, and when they were last seen.
Keep history, and let a user read it on a phone and on linked devices such as a laptop.
Notify offline users with a push notification.
Non-functional requirements
Low latency: under 100 ms from send to an open screen when both people are online.
No lost messages once the server has said sent, and no repeated messages on a screen.
The same order of messages for every member of a chat.
High availability. Losing one gateway must cost seconds, not messages.
Presence can be late and approximate. Messages cannot.
Ask about message size, group size, media, how long history is kept and whether the content is end-to-end encrypted. Leave out voice and video calls, stories, payments and message search, and say that you left them out. Mention encryption and media briefly and keep the core on text.
2. Back-of-the-Envelope Estimation
Messages: 2 million users sending 40 messages a day is 80 million messages a day, 926 a second on average and about 5,000 at the peak.
Deliveries: one message goes to 1 to 499 other people, about 3 on average, so about 15,000 deliveries a second at the peak.
Storage: at 300 bytes a message that is 24 GB a day and 8.8 TB a year, before replication.
Connections: if 10 in 100 users are connected at a time that is 200,000 open sockets. A gateway that holds 50,000 needs at least 4, and more for headroom.
Writes are steady, and the open connections are the scarce resource.
The rates are modest for a database. The hard parts are the number of live connections, keeping order, and not losing or repeating messages across failures.
3. Core APIs and Protocol
Chat uses one long-lived connection per device, usually a WebSocket or a similar protocol, because the server must push messages without being asked. A small HTTP API handles things that are not real time, such as login and fetching history.
send {chat_id, message_id, text}over the socket. Themessage_idis made by the phone (for example a random 128-bit id), so a retry carries the same id. The server repliesack {message_id, seq}, whereseqis the number the server gave it in that chat.deliver {chat_id, seq, sender, text}pushed to each recipient device, answered byack {chat_id, seq}.read {chat_id, up_to_seq}from a device that has opened the chat. One event covers every message up to that number.sync {chat_id, after_seq}when a device connects. The server returns the messages after that number, in batches.presence {user_id, state}andGET /v1/users/{id}/last_seen.
4. High-Level Design
A phone connects to one of many chat gateways, which only hold sockets and check who the user is. A message service accepts a message, gives it the next number in its chat, writes it to a log, and only then says sent. A delivery service looks up which gateways hold sockets for the recipients, pushes the message there, and sends a push notification (through Firebase or Apple's service) to the devices that are not connected. A session registry in a fast store maps each user and device to the gateway that holds its socket.
Sockets on gateways, order and storage in the message service, push in the delivery service.
A message is stored and numbered before it is delivered.
The order of the steps matters. Writing to the log before delivering means a crash after the write loses nothing, because the recipient can fetch the message with sync. Delivering before writing would show a message that then vanishes. The sent tick is the proof that the write happened.
Receipts follow the same log. A delivered tick is an acknowledgement from the device. A read tick is a read position, one number that covers every earlier message, so opening a chat with 200 unread messages sends one small event, not 200.
Three ticks come from three events, and read covers a range.
5. Delivering Reliably
Networks drop packets, and a phone can lose the acknowledgement even when the message arrived. The sender then cannot tell the two cases apart. Three designs are common: send once, resend until acknowledged, and resend with an id that lets the receiver ignore repeats.
The first program sends 100,000 messages. Each packet is lost 10 times in 100 and so is each acknowledgement. The sender tries at most 5 times. It compares sending once, retrying with every copy shown, and retrying with a message id so that each id is shown once. "Sender unsure" counts messages that arrived but whose acknowledgement never reached the sender.
Output
100000 messages, 10% of packets and 10% of acknowledgements lost, up to 5 tries.
how the app sends never shown extra sender packets extra
arrived twice+ copies unsure sent packets
send once 9904 0 0 9008 100000 0
retry, show every copy 0 10022 11121 21 123481 23481
retry + message id, show once 0 0 0 21 123481 23481
Send once: 9,904 messages never arrived, which is 9.9%. The sender could not know, and for 9,008 messages that did arrive it never received an acknowledgement either.
Retry and show every copy: nothing was lost, and 10,022 messages were shown twice with 11,121 extra copies on screens. Every lost acknowledgement turned into a visible repeat.
Retry with a message id, show once: nothing lost and nothing repeated. The 23,481 extra packets (23.5% more traffic) are the cost.
In 21 cases the message arrived and all 5 acknowledgements were lost. The phone must keep the clock icon and ask again, and the next
syncwill settle it.
Retry for safety, and use an id so a retry is harmless.
This is at-least-once delivery with idempotent handling, which gives the effect of exactly once. The server also checks the id when a message is accepted, so a retried send does not create a second row in the log. Store recent ids with the chat, in the same write as the message, so the check and the write cannot disagree.
6. Keeping the Same Order for Everyone
Members of a chat must see messages in one order, and a reply should never appear above the question it answers. There are three obvious ways to order a chat: by arrival at each phone, by the timestamp from the phone of the sender, and by a number the server gives each message in that chat.
The second program builds 20,000 chats of 5 students and 12 messages each. About 4 in 10 messages are replies, typed after the question reached the replier. Network delays are 20 to 400 ms, and phone clocks differ by up to 2 seconds. It counts replies shown above their question, and chats in which two members would see different orders.
Output
20000 chats x 12 messages, 4 in 10 are replies, phone clocks off by up to 2 seconds.
how the screen is ordered replies replies shown above chats where two members
their question see different orders
as they arrive at the phone 87840 1 11116
phone clock of the sender 87840 14454 0
server number per chat 87840 0 0
Order of arrival: a reply was above its question only once in 87,840 replies, because a reply is sent after the question was received. But in 11,116 of 20,000 chats (55.6%) two members saw different orders, because their network delays differ.
Clock of the sender: everybody sees the same order, and it is wrong: 14,454 of 87,840 replies (16.5%) were above their question, because a phone with a clock 2 seconds fast looks like it sent everything earlier.
Server number per chat: 0 replies above their question and 0 chats with different orders. The server saw the question before the reply could exist, so the reply always gets a higher number.
One agreed number per chat gives one order for everyone.
Dry run. Ana and Ravi write at nearly the same moment. Ana's message reaches the server at 10:00:00.120 and Ravi's at 10:00:00.145, so the server numbers them 41 and 42. Ana's phone clock is 2 seconds slow and stamped hers 09:59:58.1, and Ravi's phone stamped his 10:00:00.1. Sorting by stamp gives Ana then Ravi, the same as the numbers. Now give Ana a clock that is 2 seconds fast: her stamp becomes 10:00:02.1 and sorting by stamp puts Ravi first, while the numbers still say 41 then 42. Everyone who sorts by number sees Ana then Ravi.
The number is an agreed order, not the real sending time, and nothing else in a distributed system is. To keep the numbering simple and fast, number inside one chat, not across all chats: each chat is owned by one shard of the message service, and that shard increments a counter. A global counter would be a bottleneck and is not needed, because messages in different chats are never compared.
7. Offline Users and Multiple Devices
A user has a phone and a laptop. Both can be offline, and each connects at a different time. The server must give each device exactly what it missed, no more and no less. Three designs: send the whole chat again, keep a queue and delete messages once a device confirms them, or keep a log and let each device ask for everything after the last number it has.
The third program has 20,000 users, each with a phone and a laptop, and a chat with 2,000 older messages. Most users missed a few messages (5 in 10 missed 0 to 3, 4 in 10 missed 4 to 50, and 1 in 10 missed 51 to 500). The phone connects first, then the laptop. A round trip carries at most 100 messages.
Output
20000 users, 2 devices each, 2000 old messages per chat, 100 messages per round trip.
how the server catches up messages sent never reach laptop round trips
send the whole chat again 81561986 0 843940
queue, delete after first ack 780993 780993 44435
log + last number per device 1561986 0 48870
Send the whole chat again: nothing is missed, but 81,561,986 messages and 843,940 round trips were used. That is 52 times the messages of the best design.
Queue, delete after the first confirmation: only 780,993 messages and 44,435 round trips, and all 780,993 messages that the laptop was owed never reached it. A queue serves one reader.
Log and a last number per device: 1,561,986 messages, exactly what each device missed, in 48,870 round trips.
A log with a position per device serves any number of devices.
Keep the messages for the chat in a log ordered by the chat number, and keep a position for each device. A queue is the right tool when each message has one consumer. Here every device is a consumer of every message. Messages are deleted from the log only when the user deletes them, or when every device has passed them and retention allows. This is the same idea as the consumer offsets in Design Message Queue.
8. Group Chats
A group of 500 members makes one message into 499 deliveries. The delivery is unavoidable, but the storage is a choice: write a copy into each member's inbox, or store the message once in the log of the group and let members read it from there.
The fourth program has 3,000 groups. Six in 10 have 3 to 20 members, 3 in 10 have 21 to 100, and 1 in 10 have 101 to 500 (the largest has 499). Each group gets 50 messages. A message row is 324 bytes and a per-member row (read position, deleted messages) is 24 bytes. It compares a copy for every member, a shared log with one state row per member, and copies for groups up to 20 with a shared log above that.
Output
3000 groups x 50 messages, largest group 499 members.
how a group message is stored rows stored MB stored rows written by one message in the largest group
copy for every member 8730400 2828.6 499
shared log + member state 324608 52.7 1
copies up to 20, log above 1247797 358.1 1
A copy for every member: 8,730,400 rows and 2,828.6 MB. One message in the largest group writes 499 rows.
Shared log with a state row per member: 324,608 rows and 52.7 MB, which is 54 times less. One message writes 1 row.
Copies up to 20 members, log above: 1,247,797 rows and 358.1 MB. Because most groups are small, the copies still cost 6.8 times what the log does.
Store a group message once, and keep per-member state small.
Per-member copies make "delete for me" and unread counts trivial, which is why some designs keep them for small chats. With a shared log those become small rows in the member state: a set of hidden message numbers and a read position. Delivery work is the same either way: look up the gateways of the members, push in batches, and use push notifications for the rest. A very large group should not make one slow member slow everyone, so deliver to each member from its own queue.
9. Presence
Online and last-seen status feels simple and is expensive, because every change would be sent to every contact. On a weak network a phone drops and returns many times an hour, and contacts do not need to know about each blip. Presence is allowed to be late and approximate, so it can be thinned out aggressively.
The fifth program has 10,000 users with 20 to 300 contacts each. A phone drops 8 to 32 times an hour, 7 in 10 of those drops are over within 30 seconds, and 2 in 100 contacts have this user's chat open at a moment. It compares telling every contact at once, waiting 30 seconds before announcing, and waiting 30 seconds and telling only the contacts who have the chat open (a contact who opens a chat asks for the status once, 10 times an hour for each user).
Output
10000 users, one hour of weak connections.
how status changes are shared pushes in an hour per second lookups when a chat opens
tell every contact at once 63332138 17592 0
wait 30 s, tell every contact 18914062 5253 0
wait 30 s, tell open chats only 379978 105 100000
Tell every contact at once: 63,332,138 pushes an hour, 17,592 a second for only 10,000 users.
Wait 30 seconds first: 18,914,062 pushes an hour, 5,253 a second, which is 70% fewer, because short drops are never announced.
Wait 30 seconds, tell only open chats: 379,978 pushes an hour, 105 a second, which is 99.4% fewer. It adds 100,000 lookups when chats are opened, which are cheap reads from a fast store.
Debounce presence and send it only to people who are looking.
Keep presence in an in-memory store with an expiry (a heartbeat refreshes it), and write "last seen" to durable storage only when the user goes away for good. Many apps also let users hide last seen, which is one more reason the lookup on opening a chat is better than a broadcast.
10. Gateway Failure and Reconnect Storms
A gateway holding 50,000 sockets will crash sometimes. Every phone on it notices within seconds and tries to reconnect, all at the same moment. If the login service and the other gateways cannot take that burst, the phones fail and retry, and the storm repeats. How the phone retries decides how long the outage lasts.
The sixth program has 20,000 phones that all reconnect at second 0. The login service completes 1,000 handshakes a second, and any attempt over that fails. It compares retrying every second, doubling the wait after each failure (1, 2, 4 up to 64 seconds) with no randomness, and doubling with a random wait chosen up to that limit.
Output
20000 phones reconnect at once, the login service accepts 1000 handshakes a second.
how the phone retries seconds until busiest attempts wasted
all connected second in total attempts
retry every second 20 20000 210000 190000
backoff 1, 2, 4 ... s 896 20000 210000 190000
backoff with random wait 78 20000 77932 57932
Retry every second: everyone was connected after 20 seconds, but 190,000 attempts were wasted (210,000 for 20,000 phones) and 19,000 attempts hit the service in the second second.
Doubling, no randomness: still 190,000 wasted attempts and 896 seconds, nearly 15 minutes. All the failed phones wait the same time, so they come back together, in waves, and each wave gets only 1,000 through.
Doubling with a random wait: 78 seconds, 77,932 attempts and 57,932 wasted, 70% fewer than the others. The random wait spreads the returning phones across the interval.
Backoff needs randomness, or the retries stay in step.
The first second is the same for all three, because all 20,000 phones really do arrive at once, so the design must also protect the service: a limit on handshakes, a queue or token for reconnecting users, and spare gateway capacity so that one crash does not move more load than the others can take. The server can also tell phones how long to wait in its error reply, which beats guessing. See Design a Rate Limiter for the limit itself.
The session registry must not become a single point of failure. Store it in a replicated fast store, set a short expiry on each entry so that entries for dead gateways disappear, and let the delivery service treat a missing entry as "offline, send a push". See Single Point of Failure.
11. Encryption, Media and Security
With end-to-end encryption the phones hold the keys and the server stores ciphertext. That changes what the server can do: it cannot search or moderate the text, so it can only route, number, store and rate limit. The metadata (who talks to whom, when, how often) remains visible to it, and many designs reduce that too.
For media, the phone uploads the file to a blob store and sends a small message holding a pointer and a key. The message path stays small and fast, and large files use a different path with resumable uploads and a CDN. See Design Object Storage. A new linked device needs the keys moved to it, and history sync must be encrypted as well, so adding a device is a security event that deserves a confirmation on the first device.
The server still routes and orders, and it cannot read.
12. Choosing the Design
Start from the connection and follow the message.
| Concern | Choice | Watch for |
|---|---|---|
| Sockets | Sockets on gateways, a session registry with expiry | A registry that is a single point of failure |
| Delivery | Id from the phone, retries, deduplicated writes | Repeats on a lost acknowledgement |
| Order | A server number per chat | Phone clocks and arrival order |
| Sync | A log with a position per device, in batches | Queues that delete after one reader |
| Groups | One stored copy and small member state | A copy per member in big groups |
| Presence | Debounce, then tell open chats only | Broadcasting every blip |
| Failure | Backoff with random waits, spare capacity | Retries that stay in step |
13. Trade-offs to Mention
Retries and ids give no lost or repeated messages and cost extra traffic and a store of recent ids.
A server number gives one order and needs one owner for each chat, which limits how a very hot chat can be spread out.
A log serves many devices and must be kept, trimmed and secured.
A shared group log saves space and moves per-member features into small state rows.
Thin presence saves traffic and shows slightly stale status.
Random backoff recovers sooner and makes the time for one phone less predictable.
14. Common Mistakes
Delivering before writing to the log.
Retrying without a message id, so every lost acknowledgement becomes a repeat.
Ordering by the phone clock or by arrival time.
Deleting a message from a queue after one device confirms it, when the user has several devices.
Writing a copy for each member of a 500-member group.
Broadcasting every presence change to every contact.
Backoff without randomness, and a reconnect path with no limit.
15. Interview Questions
How does a message get from one phone to another? Through a socket to a gateway, stored and numbered by the message service, pushed to the sockets of the recipients, and sent as a push notification to the others.
How do you avoid lost and repeated messages? Id from the sender, retries until acknowledged, a deduplicated store and a receiver that shows an id once.
How do you order messages? With a number from the server for each chat, never by the clock of a phone.
How does a laptop catch up? It sends the last number it has and gets the messages after it.
How do you store group messages? Once, in a group log, with small state per member.
How do you show online status cheaply? Heartbeats with expiry, a wait before announcing, and updates only to open chats.
What happens when a gateway dies? The phones reconnect with random backoff, and the registry entries expire.
16. Practice Problems
A phone loses its connection after sending 3 messages and never gets any acknowledgement. What does it do on reconnect? Answer: it sends the same 3 messages with the same ids, and the server stores each id once and replies with the numbers it already gave.
Two members send at once. Can their numbers depend on who pressed send first? Answer: no, they depend on which message the server accepted first, and that is the order everyone sees.
A user adds a third device. What must the server do? Answer: nothing special for the messages, since the device starts with no position and asks for history in batches, but the keys must be moved to it safely.
You expect 1 million reconnects after an outage and a service that accepts 5,000 a second. What is the least time? Answer: 200 seconds, so spread the retries over at least that long, with random waits.
Summary
One socket per device, gateways that only hold connections, and a registry of who is where.
Write to a log with a chat number first, then deliver and acknowledge.
Retry with a sender id and show each id once.
Order by the number of the server, not by clocks.
Catch up from a log with a position per device.
Store group messages once, and keep presence thin and delayed.
Reconnect with random backoff, and protect the login path.
Conclusion
WhatsApp looks like passing text from one phone to another, and the interesting questions are in the gaps: the lost acknowledgement that becomes a repeat, the clock that puts a reply above its question, the laptop that never gets what the phone already confirmed, the group message copied 499 times, the status change sent to everyone, and the crash after which every phone returns at the same second. In an interview, state the numbers (messages a second, open sockets, group size), then show how each choice follows from them.
Previous topic: Design Pastebin.
References and further reading
RFC 6455 (the WebSocket protocol), and the documentation of the Signal protocol for how end-to-end encrypted messaging with several devices works.
Papers and posts on exactly-once and at-least-once delivery with idempotent consumers, and the consumer offset model of a commit log.
Amazon Web Services architecture blog on exponential backoff and jitter, which compares no jitter, full jitter and equal jitter.
Firebase Cloud Messaging and Apple Push Notification service documentation, for how a message reaches a phone that is not connected.
Design Message Queue, Design Object Storage, Design a Rate Limiter and Consistent Hashing on this site, for the pieces used here.