Skip to content

Case Study: WhatsApp ​

"This end-to-end encryption protocol is designed to prevent third parties and WhatsApp from having plaintext access to messages or calls." — WhatsApp, WhatsApp Encryption Overview (technical white paper), version 10, October 30, 2026 (first published April 5, 2016)

Summary: WhatsApp is the reference case for "a very small team serving a very large number of always-connected phones": an Erlang/OTP server on FreeBSD that held 2 million TCP connections per box in 2012, about 150 chat servers for 147 million concurrent connections in 2014, and roughly 100 billion messages a day by 2020, while making every personal message end-to-end encrypted with the Signal Protocol. This page walks the system through the 4-step method and, subsystem by subsystem, separates what WhatsApp has published from what we infer. Focus: Erlang, OTP, BEAM and FreeBSD tuning for simultaneous connections; ejabberd and XMPP origins, FunXMPP (secondary); store-and-forward, offline queue, acknowledgement, sent/delivered/read receipts, retry and ordering; Signal Protocol (X3DH, Double Ratchet, identity key, signed prekey, one-time prekey), sender keys for group messaging and server-side fan-out; encrypted media in a CDN blob store; presence and typing indicator; multi-device with companion devices and client-fanout; key verification and key transparency; encrypted backup with an HSM-based Backup Key Vault; Mnesia, supervision tree, hot code loading; metadata-based spam detection; the migration into Facebook data centres. Learning goal: Explain each WhatsApp subsystem with its source, say which parts are published fact and which are inference, rebuild the core delivery and group-encryption mechanisms in Go and Laravel with tests, and reuse the ideas (per-device mailbox, receipts, client-fanout vs server fan-out, keys-in-message media) in your own chat or notification system.

This is a case study in the SD 10 group. It owns the WhatsApp-specific design and numbers; the generic mechanics live in sibling chapters and are linked, not re-taught: the method in The 4-Step Approach, the arithmetic in Back-of-the-Envelope Capacity Estimation, WebSockets and presence in Real-Time Communication, delivery semantics in Delivery Guarantees and Message Acknowledgment, crypto primitives in Cryptography Fundamentals and Cryptography in Practice, fan-out trade-offs in Feeds: Fan-Out on Write vs Read. A sibling chat case is Case Study: Discord.

How to read this case study

Every architecture claim below cites a WhatsApp or Meta source we fetched and read: the WhatsApp blog, Engineering at Meta posts, the WhatsApp security white papers, Meta's earnings transcript, or conference talks given by WhatsApp engineers (Rick Reed 2012 and 2014, Jamshid Mahdavi 2016, the 2017 @Scale talk). Signal's specifications are cited for the protocol itself. Anything we generalise or guess is marked inference. Two items rest on secondary sources and are labelled as such: the ejabberd origin and the FunXMPP name. The Go and Laravel code is our own teaching re-implementation, never WhatsApp's code.

Page map ​

If you are looking forGo to
The whole case in three tablesEverything in one minute
Why WhatsApp is worth studying, the core trade-offWhy it exists
Dated history: 2009 to 2026Where it comes from
Step 1: scope and requirementsScope
Step 2: the numbersEstimate
Step 3: Erlang/OTP, BEAM, FreeBSD, connection countsConnection layer
XMPP, ejabberd, FunXMPP, Noise PipesProtocol
Store-and-forward, offline queue, receipts, retries, orderingDelivery
Presence and typing indicatorsPresence
Media, media keys, CDN blobsMedia
Mnesia, partitions, meta-clusteringStorage and clustering
Step 4: Signal Protocol, X3DH, Double RatchetEnd-to-end encryption
Group messaging and sender keysGroups
Multi-device, companion devices, client-fanoutMulti-device
Security codes and key transparencyKey verification
Encrypted backups and the HSM vaultBackups
Supervision trees, hot code loading, "let it crash"Reliability
Spam and abuse detection on metadataAbuse
Moving into Facebook data centresMigration
Numbers, knobs, protocol constantsMechanics
CodeGo, Laravel
What to copy into your own systemWhat you can copy
Classic chat-system problemsSolving the classic problems
Which WhatsApp idea fits which productChoosing
From one process to many data centresIn architecture
Run it yourselfLab
Wrong beliefs, summary, quiz, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The subsystems and where each claim comes from.

SubsystemWhat WhatsApp publishedSourceWhat is inference
Connection layerErlang on FreeBSD; 2M+ TCP connections per server (2012); ~150 chat servers with ~1M phones each (2014)WhatsApp blog 2012; Rick Reed, Erlang Factory 2012/2014One Erlang process per connection
ProtocolClient-server channel uses Noise Pipes with Curve25519, AES-GCM, SHA256Encryption OverviewXMPP-derived binary framing (FunXMPP is a secondary-source name)
DeliveryOffline storage service; most messages picked up quickly; messages not stored after deliveryReed 2014; Meta multi-device post 2021Exact queue schema, TTL, dedup key
ReceiptsOne gray check sent, two gray delivered (phone or any linked device), two blue readWhatsApp Help CenterHow receipts travel internally
EncryptionSignal Protocol: identity key, signed prekey, one-time prekeys, hash ratchet + DH ratchetEncryption Overview; Signal specsnone on the protocol itself
GroupsSender Key sent pairwise, then one ciphertext with server-side fan-outEncryption OverviewGroup size limits per year
Multi-devicePer-device identity keys, client-fanout, up to four companion devicesMeta 2021; Encryption OverviewServer routing internals
MediaRandom AES-256 + HMAC keys, blob store, hash + pointer in the messageEncryption Overview; @Scale 2017Which CDN layers hold which objects
BackupsOptional E2EE backups; key in an HSM-based Backup Key Vault behind ChatDMeta 2021 backups postHSM vendor and quorum layout
Reliability"Never lose a message"; Erlang hot load with zero dropped connections; small teamMahdavi 2016; Reed 2014Supervision tree shapes
AbuseBehaviour and metadata signals, not content; 2M+ bans per month (2019)Stopping Abuse white paper 2019Model features beyond the examples
MigrationMedia service moved to Facebook data centres, edge POPs, offnet caches@Scale 2017 talk pageTimeline and order of other services

The 4-step walk in one table.

StepQuestionWhatsApp answerSection
1 ScopeWhat must the system do?1:1 and group text, media, receipts, presence, calls; private and reliable; phone-number identityScope
2 EstimateHow big?2014: 147M concurrent connections, 19B messages in and 40B out per day; 2020: ~100B messages/dayEstimate
3 High-level designWhich boxes?Long-lived connections to Erlang chat servers, partitioned back-end services, offline storage, mms servers, meta-clusters per DCConnection layer
4 DecisionsWhich hard choices?Signal E2EE by default, sender keys, client-fanout for devices, keys-in-message media, metadata-only abuse fightingE2EE

Scale numbers over time (every figure from a WhatsApp or Meta source).

DateNumberSource
October 2011Just over 1 billion messages in a single dayWhatsApp blog, "one billion messages"
January 2012Over 2 million TCP connections on one serverWhatsApp blog, "1 million is so 2011"
March 2012Peak 2.8M connections on one server; 571k packets/sReed, Erlang Factory 2012
March 2014465M monthly users; 147M concurrent connections; 19B in / 40B out messages per dayReed, Erlang Factory 2014
April 2016More than a billion users; E2EE on by default for everythingWhatsApp blog, "end-to-end encryption"
February 20191.5 billion monthly users; over 2 million accounts banned per monthStopping Abuse white paper
February 2020More than two billion usersWhatsApp blog, "Two Billion Users"
October 2020Roughly 100 billion messages exchanged every dayMeta (Facebook) Q3 2020 earnings call

Why it exists ​

WhatsApp is studied because it inverted the usual ratio of people to machines. In 2014 Rick Reed described the Erlang team as "Small (~10 on Erlang)" handling "development and ops", for 465 million monthly users. The interesting engineering is how they got there: by keeping one job per machine type, tuning the runtime and kernel until a single server held a million phones, and pushing as much work as possible to the clients (encryption, fan-out to devices, history sync).

The fundamental trade-off of a messenger:

Push work to the serverPush work to the client
Server sees plaintext, can index, search, filter contentServer sees ciphertext only; search, backup and abuse detection get harder
One send, server copies to N devicesClient encrypts N times (client-fanout)
Server owns history; any device can log in and read itHistory lives on devices; sync between them is its own protocol
Easier moderationModeration on metadata, reports and unencrypted surfaces
Cheaper clientsCheaper, simpler servers that store little

WhatsApp chose the right-hand column for personal messages, and the rest of the design follows from it.

Everyday picture, reused through the page. Think of a post office that only handles sealed envelopes. Clerks (chat servers) keep a counter open for each customer (a connection). If the addressee is not at their counter, the envelope goes into their pigeonhole (offline queue) until they come by; when they pick it up, the clerk throws away the copy and sends the sender a slip saying "delivered". The post office never opens envelopes; it can only notice that one customer is mailing a thousand envelopes a minute.

Three common misunderstandings, up front ​

  • "WhatsApp scaled because Erlang is magic." The 2012 talk says the opposite: "From 200k to 2M were all contention fixes", and "Most required BEAM patches". Erlang gave them a good concurrency model; the numbers came from measuring and patching.
  • "The server stores all your messages." Meta's 2021 post: "Messages are not stored on the server after they are delivered." The server stores undelivered messages, encrypted, and (since multi-device) an encrypted copy of application state.
  • "End-to-end encryption means WhatsApp knows nothing." It means WhatsApp cannot read content. It still routes by phone number and device, so it sees metadata, and the abuse white paper says it uses behaviour signals such as message frequency.

Where it comes from ​

The dated timeline, with the source of each row. Rows without a WhatsApp/Meta source are labelled.

DateEventSource
June 2009Jan Koum posts on the ejabberd mailing list about a fresh ejabberd installProcessOne blog, 2014 (secondary)
October 31, 20111 billion messages in one dayWhatsApp blog
Late 2011 / Jan 20121M then 2M+ TCP connections per serverWhatsApp blog, Jan 2012
March 30, 2012"Scaling to Millions of Simultaneous Connections" (FreeBSD 8.3, OTP R14B03)Rick Reed, Erlang Factory SF 2012
March 7, 2014"That's 'Billion' with a 'B'" (FreeBSD 9.2, Erlang R16B01, ~550 servers)Rick Reed, Erlang Factory SF 2014
2014Bought by FacebookMahdavi slides, 2016
March 10, 2016"An Erlang-Based Philosophy for Service Reliability" (FreeBSD 10, Erlang R16B)Jamshid Mahdavi, Erlang Factory SF 2016
April 5, 2016Signal Protocol rollout complete; E2EE on by default; white paper v1WhatsApp blog; Signal blog; white paper
October 30, 2017"Evolution of WhatsApp within Facebook's data centers" (media service migration)@Scale 2017 talk page
July 19, 2018 / Jan 21, 2019Forward limit test, then five chats at once for everyoneWhatsApp blog, "More changes to forwarding"
February 6, 2019"Stopping Abuse" white paperWhatsApp
February 12, 2020More than two billion usersWhatsApp blog
October 2020~100 billion messages per dayFacebook Q3 2020 earnings call
July 14, 2021Multi-device beta: per-device identity keys, client-fanoutEngineering at Meta
September 10, 2021End-to-end encrypted backups, HSM-based Backup Key VaultEngineering at Meta
April 13, 2023Key transparency with the Auditable Key DirectoryEngineering at Meta
October 30, 2026Encryption Overview version 10 (companion linking codes, Cloud API, invocation messages)White paper

The 2019 Code BEAM talk "How WhatsApp moved 1.5B users across data centers" is widely cited for the migration details (FreeBSD to Linux, bare metal to containers), but its page and slides returned HTTP 404 when we fetched them, so this page does not rely on it.

The concept catalogue ​

The catalogue follows the 4-step method from The 4-Step Approach: Step 1 and Step 2 first, then one block per subsystem of the high-level design, then one block per deep-dive decision.

WhatsApp servers, early 2014 (from Rick Reed, Erlang Factory 2014)Phones1 long-livedTCP connectionper device147M concurrentconnectionschat servers~150 servers~1M phones eachone Erlang processper connection (inference)FreeBSD 9.2Erlang R16B01 + patchesmessages, notifications,presenceoffline storageaccountprofilepushgroupmms (~250 servers)services: 2-32 partitions,pg2 addressing, primary/secondary pairs, Mnesiaislands of ~2 nodesDC1mainmmswandist links clusters:single-hop messagesDC2mainmmsmeta-clustering: limitsize of any one cluster~550 servers, over 11,000 cores; team of about 10 engineers on Erlang doing development and operationsLabels marked inference are not in the slides.

Step 1: scope and requirements Must-know ​

In plain words: a phone-number-based messenger for people who know each other: text, groups, media, voice and video, with receipts, and nobody in the middle able to read it.

Common misunderstanding: "WhatsApp is a social network with a chat tab." The abuse white paper is explicit: "Our service is not a broadcast platform." It reports that "Approximately 90% of the messages sent on WhatsApp are from one person to another, and the majority of groups have fewer than ten people." That shapes everything: fan-out is small, so per-message cost dominates, not per-follower cost.

Definition (functional and non-functional requirements as published):

RequirementEvidence
1:1 and group chats, images, video, voice, filesEncryption Overview, introduction
Phone-number identity, SMS or call verification codeStopping Abuse, "At Registration"
Sent / delivered / read statusWhatsApp Help Center
Works when the recipient is offlineX3DH design goal; offline storage in Reed 2014
Never lose a message; availability firstMahdavi 2016: "Rule #1: Never lose a message", "Rule #2: Availability trumps everything"
Content invisible to WhatsAppEncryption Overview
Phone plus up to four companion devicesMeta multi-device post, 2021

Timeline (what one requirement means end to end):

text
1  Alice types "landed" on a plane at 22:00, phone in airplane mode -> nothing leaves
2  22:40 phone reconnects, client sends ciphertext for bob:0 and bob:1
3  server ack -> Alice sees one gray check
4  Bob's phone is off; entries wait in the offline queue
5  07:10 Bob's laptop connects, drains, acks -> two gray checks for Alice
6  07:11 Bob opens the chat -> two blue checks

Real scenario: family chats across time zones; a doctor and patient; a small shop answering customers; election-time political forwarding (the reason for forward limits).

What it implies (inference): low fan-out, unpredictable connectivity, mostly small payloads plus large media, and a server that must hold state for offline devices but not for history.

Fix / how to use it: write your own scope table the same way, one requirement per row with the reason; see From Requirements to Architecture.

Step 2: estimate Must-know ​

In plain words: WhatsApp's own numbers tell you what one server had to do, which is the best estimation exercise a chat interview can offer.

Common misunderstanding: "100 billion messages a day means 100 billion writes to a database." With store-and-forward, most messages are delivered from memory or a write-back cache shortly after arrival; Reed 2014 notes "Most messages picked up very quickly" and the offline store uses a "write-back cache with variable sync delay".

Definition: a back-of-envelope estimate from published inputs; every derived number below is our arithmetic (inference), the inputs are cited.

text
Inputs (Reed 2014):   147M concurrent connections, ~150 chat servers
                      342K peak msgs in/sec, 712K out/sec
                      19B messages in, 40B out per day
1  147M / 150            ~ 1M connections per chat server (matches "~1M phones each")
2  40B out / 19B in      ~ 2.1 deliveries per message (groups and multiple recipients)
3  19B / 86,400 s        ~ 220K msgs/s average in; peak 342K -> peak/avg ~ 1.6
4  712K out/s / 150      ~ 4.7K deliveries/s per chat server at peak
Inputs (Meta Q3 2020): ~100B messages/day
5  100B / 86,400 s       ~ 1.16M msgs/s average (inference: same 1.6 ratio -> ~1.9M/s peak)

Real scenario: New Year's Eve and football matches. The 2012 talk lists "Growth, Earthquakes, and Soccer!" as the problem; the 2014 talk reports "2B pics downloaded (46k/s) (New Years Eve)" and "146Gb/s out (Christmas Eve)".

What each number constrains:

NumberConstrainsDesign answer
~1M connections per serverMemory per connection, kernel socket tables, schedulerBEAM and FreeBSD tuning (kern.ipc.maxsockets, net.inet.tcp.tcphashsize=524288)
230K peak logins/sec (2014)TLS-like handshake cost, session cachesFast Noise resume; Reed 2014 lowered an "Overgrown SSL session cache" timeout
~2 deliveries per messageFan-out costSmall groups; sender keys keep group encryption O(1) for the sender
Media spikes (146 Gb/s)Egress bandwidthSeparate mms servers, later edge POPs and offnet caches

Fix / how to use it: redo this arithmetic for your own product with Back-of-the-Envelope Capacity Estimation; keep the peak-to-average ratio explicit.

Step 3a: the Erlang/OTP + FreeBSD connection layer Must-know ​

In plain words: every phone keeps one long-lived TCP connection to a chat server. The chat servers are Erlang programs on FreeBSD, tuned until one machine could hold millions of those connections.

Common misunderstanding: "The million-connection number is a benchmark." It was production. The January 2012 blog post shows kern.ipc.numopensockets: 2277845 on a live box and says "we are now able to easily push our systems to over 2 million tcp connections!!" The 2012 talk adds that they "Peaked at 2.8M conns before we intervened".

Definition: Erlang is a language whose lightweight processes run on the BEAM virtual machine; OTP is its library of behaviours (gen_server, supervisors) and applications (Mnesia, pg2). WhatsApp's 2012 standard server was "Dual Westmere Hex-core (24 logical CPUs)", "100GB RAM, SSD", "FreeBSD 8.3", "OTP R14B03"; in 2014 it was 2x Ivy Bridge 10-core, 64-512 GB RAM, "FreeBSD 9.2", "Erlang R16B01 (+patches)".

text
Simultaneous connections per server (Reed 2012 slides, blog 2012)
1  initial             ~200k  "Cluster brittle in the face of failures/overloads"
2  first bottlenecks   ~425k
3  first fixes         1M
4  a month later       2M     (blog: 2,277,845 open sockets, 41.9% idle CPU)
5  Feb 2012 peak       2.8M   571k pkts/sec, >200k dist msgs/sec

Real scenario: a football final where a whole country sends "GOAL" in the same minute; a reconnect storm after a back-end router glitch (the 2014 talk describes the 2/22 outage, which ended in "Full stop & restart (first time in years)").

What made it work (all from Reed 2012/2014):

LayerChangeWhy
FreeBSDBackported TSC timecounter; gettimeofday(2) "much less expensive"Timestamps on every packet
FreeBSDBackported igb driver (MSI-X queue stalls); sysctl limitsNIC queues and socket tables
BEAM+swt low, allocator flags, real-time priority, +ssct 1Scheduler wake-ups, memory superpages
BEAMFixed timeofday lock, timer wheel, check_io allocationLock contention found with BEAM lock-counting
OTPGC throttling with long message queues; dist buffer 4k to 256kOverload behaviour, node-to-node throughput
Appos:timestamp over erlang:now; no monitors on cross-node calls; partitioned ETS and MnesiaRemove shared hot spots

Fix / how to use it: you rarely need one process per box at this density; the copyable lesson is the method: synthetic, tee'd and diverted production load, per-node metrics every second, and contention profiling before adding machines. See Scaling Strategies and Ports, Sockets & Connections for the OS side.

Step 3b: the wire protocol: XMPP roots, FunXMPP, Noise Pipes Important ​

In plain words: the app talks to the chat server over its own compact protocol inside an encrypted channel; message content inside it is a second, end-to-end encrypted layer.

Common misunderstanding: "WhatsApp speaks standard XMPP." There is no WhatsApp document saying so. A 2015 forensic study, reported by The Register (secondary source), describes "a binary-efficient encoded Extensible Messaging and Presence Protocol (XMPP)" named FunXMPP. The origin in ejabberd, the open-source Erlang XMPP server, is reported by ProcessOne (the ejabberd company, secondary), which points to Jan Koum's 2009 post on the ejabberd mailing list.

Definition: what WhatsApp itself publishes is the transport: client-server traffic is "layered within a separate encrypted channel using Noise Pipes with Curve25519, AES-GCM, and SHA256 from the Noise Protocol Framework". The white paper lists three properties: fast "connection setup and resume", metadata hidden from network observers, and no client authentication secrets stored on the server (clients authenticate with a Curve25519 key pair).

text
two layers, two different "ends"
1  phone <-- Noise Pipes (Curve25519, AES-GCM, SHA256) --> chat server     transport layer
2  phone <-- Signal Protocol ciphertext, opaque to server --> Bob's device  end-to-end layer
3  server can read: routing header (to, from device, type); cannot read: body

Real scenario: a user on a 2G network in a moving train: tiny framing and fast resume matter more than human-readable XML (inference about the motivation for binary encoding).

ClaimStatus
Noise Pipes transportPublished (Encryption Overview)
Server stores only public client authentication keysPublished
ejabberd as the starting pointSecondary (ProcessOne, 2014)
FunXMPP binary XMPPSecondary (2015 forensic paper via The Register)
Token dictionaries for common stringsSecondary, community reverse engineering; not used here

Fix / how to use it: for your own protocol, separate the transport (TLS 1.3 or Noise) from payload encryption, and keep the routing header minimal; see TCP & UDP and gRPC & Protocol Buffers for binary framing options.

Step 3c: store-and-forward, offline queue, acknowledgements and receipts Must-know ​

In plain words: the server holds a message only until the destination device takes it, then deletes it and tells the sender. One check means the server has it, two checks mean a device of the recipient has it, blue means the person read it.

Common misunderstanding: "Two checks means Bob read it" or "two checks means it reached Bob's phone." The Help Center defines two gray checks as delivered "to the recipient's phone or any of their linked devices", and two blue checks as "The recipient has read your message."

Definition: store-and-forward with a per-device offline queue and three acknowledgements: server ack (sent), device ack (delivered), read receipt (read). Published facts: there is an offline storage service ("Offline storage" in the 2014 system overview); "Most messages picked up very quickly"; offline storage had an "I/O bottleneck writing to mailboxes", solved with a write-back cache with variable sync delay that "Can absorb overloads"; and "Messages are not stored on the server after they are delivered" (Meta 2021). Retry dedup, per-chat sequence numbers and TTL are our model (inference); WhatsApp has not published its queue schema.

Store-and-forward with acknowledgements and receiptsAlice (sender)1 send: per-device ciphertexts2 server ack: one gray checkretry with sameclient msg id= same message5 delivered: two gray checks7 read: two blue checkschat serverdedup, per-chat sequence,device-list hash checkoffline queueone entry per device:bob:0 [m1] bob:1 [m1]deleted on device ackfirst recipient-device ackflips sent to deliveredstatus never moves backBob laptop (bob:1)3 connect, drain4 ack m1decrypts with itsown pairwise session6 user opens chatBob phone (bob:0)offline: its entrywaits until itconnects and acksCheck-mark meanings from the WhatsApp Help Center; queue structure is our teaching model (inference).
text
     Alice phone (alice:0)        chat server                        Bob laptop (bob:1)
1    send c-1 [bob:0, bob:1]  ->  dedup (alice:0, c-1): new
2                                 seq(chat)=41, enqueue bob:0, bob:1
3    <- ack m1  (one gray)
4    timeout, retry c-1       ->  dedup hit: return m1, store nothing
5                                                               <-   connect, drain [m1]
6                                 delete bob:1/m1, status=delivered <- ack m1
7    <- receipt delivered (two gray)
8                                 status=read                    <-   user opens chat
9    <- receipt read (two blue)
     bob:0 (phone) is still offline: its own entry for m1 waits until it acks

Real scenario: a lost ack on a flaky network (the client resends; the server must not deliver twice); a phone off for two weeks (entries wait); a laptop and phone both online (each gets its own copy; the first device ack flips the status).

What provides each guarantee:

GuaranteeMechanism (published or inference)Sibling chapter
At-least-once to each deviceEntry stays until device ack (inference from published "picked up" and "not stored after delivered")Delivery Guarantees
No duplicate on retryClient message id dedup (inference)Idempotent Consumers & the Inbox Pattern
Per-chat orderingOne queue per device drained in order; per-chat sequence (inference)Ordering & Partitioning
Overload absorptionWrite-back cache, variable sync delay (published)Backpressure & Flow Control
Out-of-order tolerance in cryptoMessage keys allow delayed, reordered or lost messages (published)E2EE

Fix / how to use it: the Go mailbox and Laravel Mailbox service implement exactly this table with tests: dedup on (from_device, client_msg_id), per-device FIFO, delete on ack, receipts that never move backwards.

Step 3d: presence and typing indicators Important ​

In plain words: "online", "last seen" and "typing..." are tiny, frequent, throwaway signals that travel over the same live connections as messages.

Common misunderstanding: "Presence is just another message." It has opposite properties: losing one is fine, delivering a stale one is wrong, and storing it is pointless (inference). WhatsApp's 2014 slides name the output types the chat servers produce as "Messages, Notifications, & Presence", and a presence cluster (prs101) appears with its own partitions in the throughput tables.

Definition: presence is the server's knowledge of which devices are connected; a typing indicator is a short-lived client event relayed to the chat peer. One published fact about the typing indicator is unexpected: the abuse white paper uses it as an anti-automation signal: "If an account continually sends messages without triggering the typing indicator, it can be a signal" of abuse.

text
1  bob:1 connects              -> presence partition marks bob online, notifies subscribed peers
2  bob starts typing           -> client event "composing" to alice, not stored
3  bob stops for a few seconds -> "paused" (or timeout on the receiver: inference)
4  connection drops            -> presence "last seen" timestamp updated

Real scenario: a spammer's script that sends 100 messages in 15 seconds with no typing events; a user who hides "last seen" (privacy setting; behaviour not detailed in the sources we read).

SignalStored?Loss acceptable?Where to read more
MessageUntil deliveredNoDelivery
ReceiptUntil deliveredMostly no (sender UI)Delivery
PresenceCurrent state only (inference)Yes, refresh soonReal-Time Communication
Typing indicatorNo (inference)YesLaravel Reverb client events below

Fix / how to use it: in Laravel, typing is a Reverb "client event" (whisper('typing', ...)) on a presence channel; see routes/channels.php in the Laravel section.

Step 3e: media, media keys and CDN blobs Must-know ​

In plain words: the photo is encrypted on the phone with a fresh random key and uploaded as an unreadable blob; the key travels inside the normal encrypted chat message.

Common misunderstanding: "End-to-end encrypted media cannot be served from a CDN." It can, because the CDN only serves opaque bytes. The 2017 @Scale talk page describes the WhatsApp media service "migrating to Facebook's data centers" and "serving data from Edge POPs and offnet caches (ISP level)".

Definition (Encryption Overview, "Transmitting Media and Other Attachments"): the sender generates "an ephemeral 32 byte AES256 key, and an ephemeral 32 byte HMAC-SHA256 key", encrypts with AES-CBC and a random IV, appends an HMAC, uploads to a blob store, and sends a message containing the keys, "a SHA256 hash of the encrypted blob, and a pointer to the blob in the blob store". Receivers verify the hash and MAC before decrypting.

Media: encrypted blob in storage, keys inside the E2E messageSender device1 random AES-256 key+ HMAC-SHA256 keyAES-CBC, random IV,append MACSHA-256 of the blob2 upload blobblob store / CDN edgeopaque bytes onlyno keys, no plaintext3 E2E messagechat serverkeys + hash + pointer,inside Signal ciphertext4 downloadEach recipient devicedecrypt messagefetch blob by pointerverify SHA-256verify MACdecrypt plaintextEdge POPs and ISP-level offnet caches: WhatsApp media talk, @Scale 2017. CDN placement details are inference.
text
1  sender: K_aes, K_mac <- random; blob = IV || AES-CBC(photo) || HMAC
2  sender: PUT blob -> blob store (mms servers in 2014; FB DCs + edge later)
3  sender: Signal message {K_aes, K_mac, SHA256(blob), url} -> each device
4  receiver: GET url -> verify SHA256 -> verify HMAC -> decrypt
5  forwarding the photo later can reuse the uploaded blob + keys (inference)

Real scenario: a viral New Year's picture: Reed 2014 reports "1 pic downloaded 32M times"; a CDN that swaps or corrupts an object (the hash check catches it); a 2 GB video over a weak link (resumable upload: not covered by our sources).

PropertyHow it is achieved
CDN cannot read mediaContent encrypted before upload; keys only in E2E message
Recipient detects a swapped objectSHA-256 of the blob is inside the authenticated message
Tamper detectionHMAC-SHA256 over the ciphertext
Cheap hot objectsEdge POPs and ISP offnet caches (@Scale 2017)
2014 split~250 mms servers next to ~150 chat servers (Reed 2014)

Fix / how to use it: our Go media package rebuilds this scheme; generic patterns are in Object Storage and CDNs.

Step 3f: storage and clustering: Mnesia, partitions, meta-clustering Important ​

In plain words: state is split into many small pieces, each owned by one node and one process, and clusters are kept small and linked rather than grown into one huge cluster.

Common misunderstanding: "Mnesia is a toy database." WhatsApp's 2014 slides show one of 16 partitions of the media metadata database holding about 1.1 billion records and 204 GB in disc_copies tables; the account table had 512 fragments.

Definition: Mnesia is OTP's distributed database. WhatsApp's published practices: "Mostly async_dirty" transactions; "Isolate records to 1 node/1 process via hashing"; multiple Mnesia "islands" of usually 2 nodes; services split into "2-32 partitions" with "pg2 addressing" and "Primary/secondary (usu. in pairs)"; and meta-clustering, where "wandist: dist-like transport over gen_tcp" links clusters across data centres with "All messages are single-hop".

text
1  request for account 4711       -> hash(4711) -> fragment 263 of 512
2  fragment 263 lives on island 7  -> node 7a primary, 7b secondary
3  write: async_dirty on 7a        -> replicated to 7b, no 2PC
4  service in DC2 needs it         -> wandist routes one hop to DC1 group via pg2 members

Real scenario: the 2014 slides' "Oops": after adding hosts throughput went down because ETS hash chains grew above 2K (target 7); fixed by seeding the hash ("Seed ets hash to break coincidence w/ phash2").

DecisionPublished reasonGeneric chapter
async_dirty instead of transactions"Avoid mnesia txn coupling"Replication Topologies
One owner process per recordRemoves lock contentionSharding at System Level
Small islands, many of them"Better schema ops completion", "Better load-time coordination"Bulkheads
Meta-clustering"Limit size of any single cluster"Capacity Planning & DR
Power-of-2 partitioningListed as a 2014 challengeSharding

Fix / how to use it: the SQL schema in the Laravel section keys every hot table by device or chat so it can be partitioned the same way; ID Generation at Scale covers message ids.

Step 4a: end-to-end encryption with the Signal Protocol Must-know ​

In plain words: each device publishes public keys to the server; a sender uses them to build a shared secret even if the recipient is offline, then every message gets a new key that is thrown away after use.

Common misunderstanding: "If my phone is stolen, all my old messages can be decrypted from the keys on it." The white paper: because keys are ephemeral, current keys "cannot be used to decrypt previously transmitted messages" (forward secrecy).

Definition: WhatsApp uses the Signal Protocol. Keys (white paper, "Terms"): Identity Key Pair, "A long-term Curve25519 key pair, generated at install time"; Signed Pre Key, medium-term, signed by the identity key and rotated periodically; One-Time Pre Keys, "A queue of Curve25519 key pairs for one time use". Session setup is X3DH: the initiator computes ECDH(I_init, S_recip) || ECDH(E_init, I_recip) || ECDH(E_init, S_recip) || ECDH(E_init, O_recip) and runs HKDF to get a root key and chain keys. Signal's X3DH spec states the goal: "X3DH is designed for asynchronous settings where one user ("Bob") is offline but has published some information to a server." Messages then use the Double Ratchet: Message Key = HMAC-SHA256(Chain Key, 0x01), Chain Key = HMAC-SHA256(Chain Key, 0x02) (hash ratchet), plus a new ECDH per round trip (DH ratchet). Messages are encrypted with "AES256 in CBC mode for encryption and HMAC-SHA256 for authentication", and the message key is 80 bytes (32 AES, 32 HMAC, 16 IV).

text
     Alice (initiator)                         server                      Bob (offline)
1                                                                    upload I_B, S_B+sig, [O_B1..O_Bn]
2    fetch Bob's bundle                ->     return I_B, S_B, O_B7; delete O_B7
3    verify sig(S_B) with I_B; gen E_A
4    master = 3 or 4 ECDHs -> HKDF -> root key, chain key
5    send msg #0 with header (I_A, E_A) ->    store for Bob
6                                                                    Bob online: same ECDHs -> same keys
7                                                                    delete O_B7; reply -> DH ratchet step
8    every later message: MK = HMAC(CK,0x01); CK = HMAC(CK,0x02)

Real scenario: the recipient's one-time prekeys run out (the white paper: "no One-Time Pre Key will be returned" and the final ECDH is omitted); a message arrives out of order ("messages can arrive delayed, out of order, or can be lost entirely without any problems"); a reinstall loses session state and forces new sessions.

KeyLifetimeWho stores the private partPurpose
Identity keyInstall lifetimeDeviceLong-term identity; security codes
Signed prekeyRotated periodicallyDeviceOffline session setup, signed by identity
One-time prekeyUsed once, deletedDevice; server deletes public half after handing it outExtra forward secrecy for setup
Root key / chain keyPer session, ratchetingDeviceDerive message keys
Message keyOne messageDevice, deleted after useEncrypt one message

Fix / how to use it: do not implement your own Signal Protocol for production; use libsignal. Our Go ratchet package rebuilds only the symmetric chain from the spec, for understanding. Primitive background: Cryptography Fundamentals.

Step 4b: group messaging with sender keys and server-side fan-out Must-know ​

In plain words: in a group, each member hands every other member device a personal "sender key" once, privately; after that, each message is encrypted once and the server copies the same ciphertext to everyone.

Common misunderstanding: "Group messages are encrypted separately for every member." Only the sender key distribution is pairwise. The white paper: the sender "transmits the single ciphertext message to the server, which does server-side fan-out to all group participants."

Definition (white paper, "Group Messages"): first message to a group: generate a random 32-byte Chain Key and a Curve25519 Signature Key pair, combine them into a Sender Key message, and encrypt it to each member with the pairwise sessions. Subsequent messages: derive a message key from the chain key and ratchet it, encrypt with AES-256-CBC, sign the ciphertext with the signature key, send once. "Whenever a group member leaves, all group participants clear their Sender Key and start over."

Client-fanout (1:1 chats, multi-device)senderencrypts N timesserverroutes Nbob:0 phonebob:1 laptopalice:1 ownone pairwise Signal session per device(X3DH setup, then Double Ratchet)cost: O(devices) encryptions and uploadsSender Keys (groups)senderencrypts onceserverfans out 1member Amember Bmember Csender key = chain key + signature key,sent once per member device, pairwisemember leaves: all clear sender keysSource: WhatsApp Encryption Overview (whitepaper), sections Initiating Session Setup, Exchanging Messages, Group Messages.
text
     Carol (sender)                      server                       Ann, Bob, Dan (member devices)
1    SK_c = (chain, sign key)
2    pairwise Signal msg {SK_c} x 3 -> fan out 3 different ciphertexts -> install SK_c
3    "dinner at 8?" : MK0 from chain; AES-CBC; sign -> 1 ciphertext
4                                   -> fan out the SAME bytes x 3    -> verify sig, derive MK0, decrypt
5    Dan leaves the group           -> everyone discards sender keys; next sender redistributes

Real scenario: a 200-person school group where pairwise encryption per message would cost 200 encryptions and uploads for every "ok"; a removed member who must not read later messages; Community Announcement Groups, where the white paper adds separate "Add-on Sender Keys" for reactions.

SchemeSender work per messageServer workForward secrecyUsed by WhatsApp for
Pairwise (client-fanout)N encryptions, N uploadsRoute NPer session double ratchet1:1 chats to multiple devices
Sender key1 encryption, 1 uploadFan out 1 to NHash ratchet only; reset on leaveGroups
Server-side plaintext fan-out1Fan out 1 to N, server readsNone from serverNot used for E2EE chats

Fix / how to use it: our Go SenderKey/Receiver show one ciphertext decrypting for every member, skipped keys for out-of-order messages, MaxSkip, and replay rejection. For non-encrypted fan-out trade-offs see Feeds: Fan-Out on Write vs Read.

Step 4c: multi-device, companion devices and client-fanout Must-know ​

In plain words: your laptop is no longer a mirror of your phone. Each device has its own keys, and senders encrypt a separate copy for each of your devices (and for their own other devices).

Common misunderstanding: "WhatsApp Web reads messages through the phone." That was the old design; Meta's 2021 post says companion devices used to "maintain a persistent secure connection with the phone and simply mirror its contents". The new design lets you use WhatsApp on your phone and "up to four other nonphone devices simultaneously".

Definition: "With multi-device, each device now has its own identity key." The server maps each account to its device identities; the white paper calls the send pattern client-fanout: "the WhatsApp client transmits a single message N number of times to N number of different devices." Companions are linked by QR code (or an 8-character code) and the primary signs them (Account Signature, Device Signature, Signed Device List). If the sender's device list is stale, "Sender Side Backfill" applies: the server compares "the hash of all the destination devices listed by the sender" with its records and, on mismatch, tells the sender to refresh and resend, only "within a short duration". Signed device lists expire after 35 days or less.

text
1  Alice sends to Bob; Alice's list for Bob = [bob:0]
2  server: hash([bob:0, alice:1]) != hash(server records [bob:0, bob:1, alice:1]) -> mismatch
3  server -> Alice: refresh device lists
4  Alice fetches bob:1 keys, verifies Account + Device signatures, builds session
5  Alice encrypts for bob:1 and resends only to the new device
6  later, Bob removes bob:1 -> phone uploads new Signed Device List; peers stop encrypting to it

Real scenario: a user's phone battery dies but the laptop keeps working; a new laptop linked a minute before a message arrives; a malicious server trying to add a "ghost device" (blocked because the primary must sign each companion and security codes cover all devices).

ConcernMechanismSource
Phone no longer requiredPer-device identity keys and sessionsMeta 2021
Ghost device by the serverAccount/Device signatures, signed device list, security codes over all devicesMeta 2021; white paper
Missed new deviceSender Side Backfill with device-list hashWhite paper
History on a new devicePrimary encrypts recent chats bundle; key sent E2E; key deleted after importMeta 2021
Contacts, archive, starsEncrypted app state stored on server, keys only on devicesMeta 2021
CallsPer-device SRTP master secrets sent by client-fanoutMeta 2021

Fix / how to use it: our mailbox Submit returns ErrStaleDeviceList on a hash mismatch, and the Laravel controller returns HTTP 409 stale_device_list, which is the server half of Sender Side Backfill.

Step 4d: key verification and key transparency Important ​

In plain words: E2EE is only as good as the public keys you fetched; security codes let two people compare keys, and key transparency lets the app check automatically that the server is not handing out fake ones.

Common misunderstanding: "If the key changes, someone is attacking me." Reinstalls and new phones change keys too; the setting that notifies you is a hint to verify, not proof of attack (inference).

Definition: the white paper: users verify by QR code or "comparing the 60-digit number"; each 30-digit half comes from iteratively hashing sorted identity keys and the user identifier with SHA-512 "5200 times". Signal's 2016 blog adds the reason for digits: localisation, and "Users compare 12 groups of 5 digits with each other." In 2023 Meta deployed key transparency: "The server (WhatsApp) maintains an append-only AKD of public keys mapped to user accounts", plus a public third-party audit record, using the open-source Auditable Key Directory.

text
1  Alice and Bob meet; Alice scans Bob's QR (version, ids, identity keys of all devices)
2  app compares against keys fetched from server -> "verified"
3  2023+: Alice's app also checks an AKD proof that Bob's key is in the append-only directory
4  auditors check that the directory only ever grew (no silent rewrite)

Real scenario: a journalist verifying a source in person; a business that linked Meta's Cloud API (the white paper says the verification screen shows this, and such chats are not considered end-to-end encrypted).

MethodUser effortProtects againstSource
60-digit code / QRManualServer-in-the-middle for that contactWhite paper
Security-code change noticeOpt-in settingUnnoticed key changeSignal blog 2016
Key transparency (AKD)NoneServer giving different keys to different peopleMeta 2023

Fix / how to use it: append-only, auditable logs are Merkle-tree structures; see Merkle Trees.

Step 4e: end-to-end encrypted backups and the HSM vault Important ​

In plain words: your chat backup in iCloud or Google Drive can be locked with a key that neither WhatsApp nor the cloud provider knows; if you want a password instead of a 64-digit key, the key sits in a tamper-resistant hardware vault that only releases it for the right password.

Common misunderstanding: "Backups were always end-to-end encrypted." Meta's 2021 post: before the feature, backups "are secured by the individual cloud-based storage services". E2EE backups are an opt-in added on September 10, 2021.

Definition: backups are "encrypted with a unique, randomly generated encryption key". The user keeps the 64-digit key or chooses a password; with a password the key goes to "a Backup Key Vault that is built based on a component called a hardware security module (HSM)". The vault enforces attempt limits and renders the key "permanently inaccessible after a limited number of unsuccessful attempts"; "WhatsApp will know only that a key exists in the HSM. It will not know the key itself." "WhatsApp's front-end service, ChatD, handles client connections and client-server authentication" and relays encrypted messages between client and vault. The vault is "geographically distributed across multiple data centers".

text
1  enable E2EE backup -> client generates backup key K
2  option A: user writes down 64-digit K           -> nothing stored by WhatsApp
3  option B: password P -> client and HSM vault exchange encrypted messages via ChatD -> vault stores K
4  restore: enter P -> vault verifies, counts attempts -> returns K -> client decrypts backup stream
5  too many wrong P -> vault makes K permanently inaccessible

Real scenario: a lost phone and a new install; a forgotten password after the attempt limit (the backup is gone by design); a data-centre outage during restore (the vault is multi-DC).

OptionWhere the key livesRecovery if forgottenBrute-force protection
Cloud provider defaultProvider-managedProvider accountProvider
E2EE + 64-digit keyUser onlyNone256-bit key space (inference)
E2EE + passwordHSM Backup Key VaultNone after limitHSM attempt limit

Fix / how to use it: generic backup design is in Backup, PITR & Disaster Recovery; key custody options in Cryptography in Practice.

Step 4f: reliability: supervision trees, hot code loading, "let it crash" Important ​

In plain words: keep each feature in its own silo, let a broken process die and restart, deploy new code into running servers without dropping connections, and alert the whole team loudly when something breaks.

Common misunderstanding: "Reliability at this scale needs heavy automation and redundancy everywhere." Mahdavi 2016 described the opposite philosophy: "All deploys are manual", "Friction by design", "Fix Fast" vs "Deep Redundancy", "Don't try to build most systems to be resilient to double faults". It worked because the code base was small ("20k LOC for media servers") and changes were small.

Definition: a supervision tree is OTP's structure where "A supervisor is responsible for starting, stopping, and monitoring its child processes" with restart strategies such as one_for_one (Erlang/OTP docs). Hot code loading: "The code of a module can exist in two variants in a system: current and old", so a module is replaced while processes keep running (Erlang/OTP docs). WhatsApp's published use: "Erlang hot load – zero dropped connections or requests" and "Lots of small / simple deploys" (Mahdavi 2016). WhatsApp has not published its supervision tree layout; any shape we draw is inference.

text
hot load of chat_router.beam on one chat server (inference, standard OTP behaviour)
1  load new code     -> module now has current (v2) and old (v1)
2  running processes keep executing v1 until their next fully qualified call
3  next call         -> v2; 1M connections stay open, no reconnect storm
4  later load v3     -> processes still on v1 are killed: write code that calls ?MODULE:loop()

Real scenario: a fix shipped during a football match without disconnecting a million phones; a malformed packet that crashes one connection process, which is restarted while its neighbours carry on (inference); a RAM failure (Mahdavi: "Ram, disks, nics are common").

PracticeWhatsApp sourceGeneric chapter
Never lose a message; availability firstMahdavi 2016SLOs
Silo architecture, failures isolated per featureMahdavi 2016Bulkheads
Backlog alerts (usually above 500k queued)Reed 2014Alerting That Works
1-second and 1-minute metrics to GraphiteReed 2014Observability
Decouple: async casts, timeouts, no monitorsReed 2014Timeouts, Retries & Jitter
Avoid head-of-line blocking: separate read/write and inter-node queuesReed 2014Cascading Failures

Fix / how to use it: you get most of this without Erlang: small services, process supervisors (systemd, Kubernetes restarts), rolling deploys with connection draining, and alerts on queue backlog rather than CPU.

Step 4g: spam and abuse detection without content access Must-know ​

In plain words: WhatsApp cannot read messages, so it judges accounts by how they behave: how fast they register, how fast they send, how many strangers they message, whether people report or block them.

Common misunderstanding: "End-to-end encryption makes abuse fighting impossible." The 2019 white paper reports: "We remove over two million accounts per month for bulk or automated behavior" and over 75% "without a recent user report". It says plainly: "we focus on the behavior of accounts and user-reported content."

Definition: detection at three stages: at registration (phone-number and network reputation, carrier, IP; "roughly 20% of account bans happened at registration time"), while messaging (rates such as "100 messages in 15 seconds", mass group creation, messaging non-contacts, missing typing indicators), and on negative feedback (reports and blocks, weighed by the reporter-reported relationship to resist mass false reports). Product limits support it: forwarding to "only five chats at once" since January 21, 2019, and limits on group creation.

text
1  register +1-555-0100 from a network recently used by banned accounts -> high risk score
2  5 minutes later: 100 messages in 15 s, no typing events             -> automatic ban
3  innocent case: new phone, messages 40 contacts "new number"          -> history says low risk, allowed
4  reported by recipients who never got a message from it              -> report weighted down (coordination check)

Real scenario: election-time political spam; click-bait phishing; a coordinated mass-report attack on an activist; a new user announcing their number change.

SignalStageContent needed?
Phone prefix, carrier, IP reputationRegistrationNo
Send rate, group creation rate, adds per minuteMessagingNo
Non-contact recipients ratioMessagingNo
Typing indicator absenceMessagingNo
User reports (reported messages are shared by the reporter)FeedbackOnly what the reporter sends
Profile photos (unencrypted) scanned for child exploitation imageryAnyUnencrypted surface only

Fix / how to use it: rate limits and behaviour scores are your first line; see Rate Limiting and Load Shedding.

Step 4h: post-acquisition migration into Facebook data centres Good to know ​

In plain words: after Facebook bought WhatsApp, the service moved from its own bare-metal setup onto Facebook's data centres and edge network, one service at a time, while staying online.

Common misunderstanding: "They rewrote WhatsApp on Facebook's stack." No WhatsApp source we read says so; the 2017 @Scale talk page describes the media service "migrating to Facebook's data centers" while maintaining "privacy and high service reliability", and Mahdavi 2016 called "Server migrations" "Good opportunities for rewriting / refactoring systems".

Definition: the published facts are limited: 2014 acquisition (Mahdavi); in 2016 WhatsApp still ran "Bare metal servers" with "FreeBSD 10" and "Erlang R16B" (Mahdavi); in October 2017 the media service was migrating to Facebook's data centres and planned to serve from "Edge POPs and offnet caches (ISP level)" (@Scale). Press reports in 2017 named IBM SoftLayer as the previous host; that is secondary and not used for any claim here. The migration order, the OS change and the method are inference (the Code BEAM 2019 slides that describe them were unreachable).

text
generic incremental move, as we infer it (not WhatsApp's documented runbook)
1  pick one service (media first, per @Scale 2017)
2  run old and new sites hot-hot; route a slice of users (e.g. by phone prefix) to the new site
3  copy data, verify remotely, fix divergences
4  shift the slice; repeat; retire old hardware

Real scenario: moving a stateful service with billions of objects without downtime; keeping E2EE guarantees while changing every server underneath (they hold only ciphertext, which makes the move easier: inference).

AspectBefore (published)After (published)
HostingBare metal, FreeBSDFacebook data centres (media service, 2017)
Media delivery~250 mms servers (2014)Edge POPs, ISP offnet caches (2017 plan)
Team modelSmall team doing dev and opsCollaboration with Facebook infrastructure engineers

Fix / how to use it: the playbook for such moves is Strangler Fig: Safe System Migration.

Mechanics ​

Protocol constants from the white paper ​

ItemValue
CurveCurve25519 for identity, signed prekey, one-time prekeys, ephemeral keys
Message key size80 bytes: 32 AES-256, 32 HMAC-SHA256, 16 IV
Message cipherAES-256-CBC + HMAC-SHA256
Chain stepMK = HMAC-SHA256(CK, 0x01); CK' = HMAC-SHA256(CK, 0x02)
Root stepChain Key, Root Key = HKDF(Root Key, ECDH(eph_sender, eph_recipient))
Media keysEphemeral 32-byte AES-256 + 32-byte HMAC-SHA256, random IV
Security code60 digits = two 30-digit fingerprints; SHA-512 iterated 5200 times
Signed device list TTL35 days or less; 48 hours after in-chat consistency update
Account / Device / List signature prefixes0x0600 / 0x0601 / 0x0602 (Cloud API: 0x0605, 0x0606)
TransportNoise Pipes, Curve25519, AES-GCM, SHA256
Double Ratchet MAX_SKIPImplementation constant bounding skipped keys (Signal spec)

Runtime and kernel knobs WhatsApp published ​

KnobValue or noteSource
net.inet.tcp.tcphashsize524288Reed 2012
kern.ipc.maxsocketsraised ("Obvious limits")Reed 2012
+swt lowavoid scheduler perma-sleepReed 2012
+Mut 24allocator instance per schedulerReed 2012
+A 1024async thread count with lock countingReed 2012
dist receive buffer4k to 256k, configurableReed 2012
beam.smp flags in 2016-zdbbl 16384 -swt very_low -sbt tnnps -sbwt none -P 7200000Mahdavi 2016 pstree
Backlog alertusually above 500k queued messagesReed 2014

Errors and signals you will actually see (our implementation) ​

SignalMeaningAction
mailbox: destination device list is stale / HTTP 409 stale_device_listSender encrypted for an outdated device setRefetch device list, build sessions, resend to new devices
ratchet: message key already used or too oldReplay, or a key already consumedDrop; do not retry decrypt
ratchet: iteration beyond MaxSkipSender too far ahead or maliciousRequest a new sender key distribution
ratchet: bad sender signatureCiphertext not from the member that owns the keyDrop and log
media: integrity check failedCDN object swapped or corruptedRe-download; if repeated, mark media unavailable

Go ​

Our teaching re-implementations. They follow WhatsApp's and Signal's published descriptions; they are not WhatsApp's code and are not safe for real secrets.

Before ​

A relay that writes to the socket if it is open. The tests document the two production failures: an offline recipient never gets the message, and a retry after a lost ack delivers twice.

go
// Package before shows the "push it if the socket is open" relay that works in a
// demo and loses messages in production. Educational code, not WhatsApp's.
package before

import "sync"

// Relay forwards a message only to recipients that are connected right now.
type Relay struct {
	mu     sync.Mutex
	online map[string]chan string // device ID -> socket
	log    []string               // what the sender believes was sent
}

// NewRelay returns an empty relay.
func NewRelay() *Relay { return &Relay{online: map[string]chan string{}} }

// Connect registers a live socket for a device.
func (r *Relay) Connect(device string) chan string {
	r.mu.Lock()
	defer r.mu.Unlock()
	ch := make(chan string, 16)
	r.online[device] = ch
	return ch
}

// Disconnect drops the socket, for example when the phone loses signal.
func (r *Relay) Disconnect(device string) {
	r.mu.Lock()
	defer r.mu.Unlock()
	delete(r.online, device)
}

// Send writes to the socket if it exists. There is no ack, no store and no
// dedup: an offline recipient never sees the message, and a client retry after
// a timeout delivers it twice.
func (r *Relay) Send(to, body string) {
	r.mu.Lock()
	defer r.mu.Unlock()
	r.log = append(r.log, body)
	if ch, ok := r.online[to]; ok {
		ch <- body
	}
}
go
package before

import "testing"

func TestOfflineRecipientLosesMessage(t *testing.T) {
	r := NewRelay()
	r.Send("bob-phone", "are you there?") // Bob is offline
	ch := r.Connect("bob-phone")
	if len(ch) != 0 {
		t.Fatalf("naive relay unexpectedly stored a message")
	}
}

func TestRetryDuplicates(t *testing.T) {
	r := NewRelay()
	ch := r.Connect("bob-phone")
	r.Send("bob-phone", "pay me back 10")
	r.Send("bob-phone", "pay me back 10") // client retried after a lost ack
	if got := len(ch); got != 2 {
		t.Fatalf("want 2 copies (the bug), got %d", got)
	}
}

After: per-device mailbox with receipts ​

Client-fanout envelopes, a device-list hash check, retry dedup, per-chat sequence, delete on ack, and sent/delivered/read receipts that never move backwards.

go
// Package mailbox is a small store-and-forward server in the shape WhatsApp
// describes publicly: per-device offline queues, client-fanout envelopes, a
// device-list hash check ("Sender Side Backfill"), and sent/delivered/read
// receipts. It is an educational re-implementation, NOT WhatsApp's code; the
// TTL value, the dedup rule and the data structures are our own choices.
package mailbox

import (
	"crypto/sha256"
	"encoding/hex"
	"errors"
	"fmt"
	"slices"
	"strings"
	"sync"
	"time"
)

// DeviceID is "account:n"; n = 0 is the primary phone, n > 0 a companion device.
type DeviceID string

// Account returns the account part of a device ID.
func (d DeviceID) Account() string { a, _, _ := strings.Cut(string(d), ":"); return a }

// Kind tells a message apart from a receipt.
type Kind int

const (
	KindMessage Kind = iota
	KindDelivered
	KindRead
)

// Status is what the sender's UI shows: one check, two checks, two blue checks.
type Status int

const (
	Sent Status = iota + 1
	Delivered
	Read
)

func (s Status) String() string {
	return [...]string{"?", "sent", "delivered", "read"}[s]
}

// Envelope is one send from one device. To holds one ciphertext per destination
// device (client-fanout); the server never sees plaintext.
type Envelope struct {
	ClientMsgID string // chosen by the sending device, reused on retry
	From        DeviceID
	Chat        string
	Recipients  []string // accounts in the chat other than the sender
	To          map[DeviceID][]byte
}

// Delivery is one entry in a device's offline queue.
type Delivery struct {
	MsgID      string
	Seq        uint64 // per-chat sequence assigned by the server
	Chat       string
	From       DeviceID
	Kind       Kind
	Ciphertext []byte
	enqueued   time.Time
}

// ErrStaleDeviceList means the sender encrypted for a device set that differs
// from the server's records: fetch the list, build sessions, resend.
var ErrStaleDeviceList = errors.New("mailbox: destination device list is stale")

// Server holds offline queues in memory. A real deployment shards this by
// account and persists it; here one mutex keeps the invariants obvious.
type Server struct {
	mu      sync.Mutex
	now     func() time.Time
	ttl     time.Duration
	devices map[string][]DeviceID
	seen    map[string]string // From + ClientMsgID -> MsgID (retry dedup)
	chatSeq map[string]uint64
	queues  map[DeviceID][]Delivery
	status  map[string]Status
	origin  map[string]Delivery // MsgID -> metadata for receipts
	nextID  uint64
}

// New returns a server whose undelivered entries expire after ttl.
func New(ttl time.Duration, now func() time.Time) *Server {
	return &Server{
		now: now, ttl: ttl,
		devices: map[string][]DeviceID{}, seen: map[string]string{},
		chatSeq: map[string]uint64{}, queues: map[DeviceID][]Delivery{},
		status: map[string]Status{}, origin: map[string]Delivery{},
	}
}

// Register links a device to its account.
func (s *Server) Register(d DeviceID) {
	s.mu.Lock()
	defer s.mu.Unlock()
	if !slices.Contains(s.devices[d.Account()], d) {
		s.devices[d.Account()] = append(s.devices[d.Account()], d)
	}
}

// DeviceSetHash is the order-independent hash both sides compare.
func DeviceSetHash(devs []DeviceID) string {
	sorted := slices.Clone(devs)
	slices.Sort(sorted)
	h := sha256.New()
	for _, d := range sorted {
		h.Write([]byte(d))
		h.Write([]byte{0})
	}
	return hex.EncodeToString(h.Sum(nil))
}

// expected is every device of every recipient plus the sender's other devices.
func (s *Server) expected(e Envelope) []DeviceID {
	var out []DeviceID
	for _, a := range e.Recipients {
		out = append(out, s.devices[a]...)
	}
	for _, d := range s.devices[e.From.Account()] {
		if d != e.From {
			out = append(out, d)
		}
	}
	return out
}

// Submit stores the envelope for every destination device and returns the
// server message ID (the sender shows one check when it receives it).
// A retry with the same ClientMsgID returns the original ID and stores nothing.
func (s *Server) Submit(e Envelope) (string, error) {
	s.mu.Lock()
	defer s.mu.Unlock()
	key := string(e.From) + "/" + e.ClientMsgID
	if id, ok := s.seen[key]; ok {
		return id, nil
	}
	listed := make([]DeviceID, 0, len(e.To))
	for d := range e.To {
		listed = append(listed, d)
	}
	if DeviceSetHash(listed) != DeviceSetHash(s.expected(e)) {
		return "", ErrStaleDeviceList
	}
	s.nextID++
	id := fmt.Sprintf("m%d", s.nextID)
	s.chatSeq[e.Chat]++
	base := Delivery{MsgID: id, Seq: s.chatSeq[e.Chat], Chat: e.Chat, From: e.From, Kind: KindMessage, enqueued: s.now()}
	for _, d := range sortedKeys(e.To) {
		dl := base
		dl.Ciphertext = e.To[d]
		s.queues[d] = append(s.queues[d], dl)
	}
	s.seen[key] = id
	s.status[id] = Sent
	s.origin[id] = base
	return id, nil
}

// Pending returns the device's queue in arrival order, after dropping entries
// older than the TTL. Per-chat order holds because Seq grows under the lock.
func (s *Server) Pending(d DeviceID) []Delivery {
	s.mu.Lock()
	defer s.mu.Unlock()
	cutoff := s.now().Add(-s.ttl)
	q := s.queues[d][:0]
	for _, dl := range s.queues[d] {
		if dl.enqueued.After(cutoff) {
			q = append(q, dl)
		}
	}
	s.queues[d] = q
	return slices.Clone(q)
}

// Ack is the device's delivery acknowledgement. The entry leaves the queue
// (nothing stays on the server after delivery) and, for a message from another
// account, the sender's devices get a "delivered" receipt the first time any
// recipient device acks.
func (s *Server) Ack(d DeviceID, msgID string, kind Kind) {
	s.mu.Lock()
	defer s.mu.Unlock()
	s.queues[d] = slices.DeleteFunc(s.queues[d], func(x Delivery) bool {
		return x.MsgID == msgID && x.Kind == kind
	})
	o, ok := s.origin[msgID]
	if !ok || kind != KindMessage || d.Account() == o.From.Account() {
		return
	}
	if s.status[msgID] < Delivered {
		s.status[msgID] = Delivered
		s.receipt(o, KindDelivered)
	}
}

// MarkRead records that the user opened the chat on device d.
func (s *Server) MarkRead(d DeviceID, msgID string) {
	s.mu.Lock()
	defer s.mu.Unlock()
	o, ok := s.origin[msgID]
	if !ok || d.Account() == o.From.Account() || s.status[msgID] == Read {
		return
	}
	s.status[msgID] = Read
	s.receipt(o, KindRead)
}

func (s *Server) receipt(o Delivery, k Kind) {
	for _, d := range s.devices[o.From.Account()] {
		s.queues[d] = append(s.queues[d], Delivery{MsgID: o.MsgID, Seq: o.Seq, Chat: o.Chat, From: o.From, Kind: k, enqueued: s.now()})
	}
}

// StatusOf is the sender-side tick state.
func (s *Server) StatusOf(msgID string) Status {
	s.mu.Lock()
	defer s.mu.Unlock()
	return s.status[msgID]
}

func sortedKeys(m map[DeviceID][]byte) []DeviceID {
	out := make([]DeviceID, 0, len(m))
	for k := range m {
		out = append(out, k)
	}
	slices.Sort(out)
	return out
}
go
package mailbox

import (
	"errors"
	"testing"
	"time"
)

type clock struct{ t time.Time }

func (c *clock) now() time.Time { return c.t }

func setup() (*Server, *clock) {
	c := &clock{t: time.Date(2026, 1, 1, 12, 0, 0, 0, time.UTC)}
	s := New(30*24*time.Hour, c.now)
	for _, d := range []DeviceID{"alice:0", "alice:1", "bob:0", "bob:1"} {
		s.Register(d)
	}
	return s, c
}

func env(id string) Envelope {
	return Envelope{
		ClientMsgID: id, From: "alice:0", Chat: "alice-bob", Recipients: []string{"bob"},
		To: map[DeviceID][]byte{"bob:0": []byte("c0"), "bob:1": []byte("c1"), "alice:1": []byte("c2")},
	}
}

func TestStoreAndForwardThenDelete(t *testing.T) {
	s, _ := setup()
	id, err := s.Submit(env("k1"))
	if err != nil {
		t.Fatal(err)
	}
	if s.StatusOf(id) != Sent {
		t.Fatalf("want sent")
	}
	got := s.Pending("bob:0") // Bob was offline; he connects now
	if len(got) != 1 || string(got[0].Ciphertext) != "c0" {
		t.Fatalf("bob:0 queue = %+v", got)
	}
	s.Ack("bob:0", id, KindMessage)
	if n := len(s.Pending("bob:0")); n != 0 {
		t.Fatalf("message still stored after ack: %d", n)
	}
	if s.StatusOf(id) != Delivered {
		t.Fatalf("want delivered after first recipient device ack")
	}
	// bob:1 still has its own copy until it connects and acks.
	if n := len(s.Pending("bob:1")); n != 1 {
		t.Fatalf("companion copy missing")
	}
}

func TestRetryIsDeduplicated(t *testing.T) {
	s, _ := setup()
	a, _ := s.Submit(env("k1"))
	b, _ := s.Submit(env("k1")) // ack lost, client retried
	if a != b || len(s.Pending("bob:0")) != 1 {
		t.Fatalf("retry produced a duplicate: %s %s", a, b)
	}
}

func TestPerChatOrder(t *testing.T) {
	s, _ := setup()
	for _, k := range []string{"k1", "k2", "k3"} {
		if _, err := s.Submit(env(k)); err != nil {
			t.Fatal(err)
		}
	}
	q := s.Pending("bob:0")
	for i := 1; i < len(q); i++ {
		if q[i].Seq <= q[i-1].Seq {
			t.Fatalf("order broken: %v", q)
		}
	}
}

func TestReceiptsNeverGoBackwards(t *testing.T) {
	s, _ := setup()
	id, _ := s.Submit(env("k1"))
	s.Ack("bob:1", id, KindMessage)
	s.MarkRead("bob:1", id)
	s.Ack("bob:0", id, KindMessage) // late ack from the phone
	if s.StatusOf(id) != Read {
		t.Fatalf("status regressed to %v", s.StatusOf(id))
	}
	var kinds []Kind
	for _, d := range s.Pending("alice:0") {
		kinds = append(kinds, d.Kind)
	}
	if len(kinds) != 2 || kinds[0] != KindDelivered || kinds[1] != KindRead {
		t.Fatalf("receipts to sender = %v", kinds)
	}
}

func TestStaleDeviceListRejected(t *testing.T) {
	s, _ := setup()
	e := env("k1")
	delete(e.To, "bob:1") // sender does not know Bob's new laptop yet
	if _, err := s.Submit(e); !errors.Is(err, ErrStaleDeviceList) {
		t.Fatalf("want ErrStaleDeviceList, got %v", err)
	}
}

func TestUndeliveredEntriesExpire(t *testing.T) {
	s, c := setup()
	if _, err := s.Submit(env("k1")); err != nil {
		t.Fatal(err)
	}
	c.t = c.t.Add(31 * 24 * time.Hour)
	if n := len(s.Pending("bob:0")); n != 0 {
		t.Fatalf("want expiry, %d left", n)
	}
}

Example: the symmetric ratchet and sender keys ​

ChainKey.Next is the exact HMAC recipe from the white paper; Seal/Open follow the Signal spec's CBC+HMAC recommendation with an 80-byte HKDF output. SenderKey encrypts once and signs (Ed25519 here, XEdDSA in Signal); Receiver caches skipped keys up to MaxSkip and deletes used keys.

go
// Package ratchet re-implements, for teaching, the symmetric-key ratchet and
// the group "Sender Key" scheme as described in the WhatsApp Encryption
// Overview and the Signal Double Ratchet specification. It is NOT WhatsApp's
// or libsignal's code and must not protect real data: there is no X3DH, no
// DH ratchet, Ed25519 stands in for XEdDSA, and the HKDF info label is ours.
package ratchet

import (
	"bytes"
	"crypto/aes"
	"crypto/cipher"
	"crypto/hkdf"
	"crypto/hmac"
	"crypto/sha256"
	"errors"
)

// ChainKey is the 32-byte value that ratchets forward once per message.
type ChainKey [32]byte

// Next returns the message key for this step and the next chain key:
// MK = HMAC-SHA256(CK, 0x01), CK' = HMAC-SHA256(CK, 0x02).
func (ck ChainKey) Next() (mk [32]byte, next ChainKey) {
	m := hmac.New(sha256.New, ck[:])
	m.Write([]byte{0x01})
	copy(mk[:], m.Sum(nil))
	m = hmac.New(sha256.New, ck[:])
	m.Write([]byte{0x02})
	copy(next[:], m.Sum(nil))
	return mk, next
}

const info = "academy-casestudy-whatsapp-v1" // application-specific, ours

// expand turns a message key into the 80 bytes the spec recommends:
// 32-byte AES-256 key, 32-byte HMAC key, 16-byte IV.
func expand(mk [32]byte) (enc, auth, iv []byte, err error) {
	out, err := hkdf.Key(sha256.New, mk[:], make([]byte, 32), info, 80)
	if err != nil {
		return nil, nil, nil, err
	}
	return out[:32], out[32:64], out[64:80], nil
}

// ErrAuth means the ciphertext or its associated data was modified.
var ErrAuth = errors.New("ratchet: authentication failed")

// Seal is AES-256-CBC with PKCS#7 padding, then HMAC-SHA256 over ad||ciphertext,
// with the MAC appended.
func Seal(mk [32]byte, plaintext, ad []byte) ([]byte, error) {
	enc, auth, iv, err := expand(mk)
	if err != nil {
		return nil, err
	}
	block, err := aes.NewCipher(enc)
	if err != nil {
		return nil, err
	}
	pad := aes.BlockSize - len(plaintext)%aes.BlockSize
	buf := append(bytes.Clone(plaintext), bytes.Repeat([]byte{byte(pad)}, pad)...)
	cipher.NewCBCEncrypter(block, iv).CryptBlocks(buf, buf)
	m := hmac.New(sha256.New, auth)
	m.Write(ad)
	m.Write(buf)
	return m.Sum(buf), nil
}

// Open verifies the MAC before decrypting.
func Open(mk [32]byte, sealed, ad []byte) ([]byte, error) {
	enc, auth, iv, err := expand(mk)
	if err != nil {
		return nil, err
	}
	if len(sealed) < sha256.Size+aes.BlockSize {
		return nil, ErrAuth
	}
	ct, tag := sealed[:len(sealed)-sha256.Size], sealed[len(sealed)-sha256.Size:]
	m := hmac.New(sha256.New, auth)
	m.Write(ad)
	m.Write(ct)
	if !hmac.Equal(tag, m.Sum(nil)) || len(ct)%aes.BlockSize != 0 {
		return nil, ErrAuth
	}
	block, err := aes.NewCipher(enc)
	if err != nil {
		return nil, err
	}
	out := bytes.Clone(ct)
	cipher.NewCBCDecrypter(block, iv).CryptBlocks(out, out)
	pad := int(out[len(out)-1])
	if pad == 0 || pad > aes.BlockSize {
		return nil, ErrAuth
	}
	return out[:len(out)-pad], nil
}
go
package ratchet

import (
	"crypto/ed25519"
	"encoding/binary"
	"errors"
	"io"
)

// MaxSkip bounds how many message keys a receiver derives ahead, so a
// malicious sender cannot force unbounded work (Double Ratchet MAX_SKIP).
const MaxSkip = 2000

// Distribution is what a group member sends to every other member device
// over the pairwise sessions the first time it speaks in the group.
type Distribution struct {
	Iteration uint32
	Chain     ChainKey
	SignPub   ed25519.PublicKey
}

// GroupMessage is the single ciphertext the server fans out to all members.
type GroupMessage struct {
	Iteration  uint32
	Ciphertext []byte
	Signature  []byte
}

// SenderKey is the sending side: one chain plus one signing key per group.
type SenderKey struct {
	iter  uint32
	chain ChainKey
	priv  ed25519.PrivateKey
}

// NewSenderKey creates a fresh random chain and signature key.
func NewSenderKey(rand io.Reader) (*SenderKey, error) {
	var ck ChainKey
	if _, err := io.ReadFull(rand, ck[:]); err != nil {
		return nil, err
	}
	_, priv, err := ed25519.GenerateKey(rand)
	if err != nil {
		return nil, err
	}
	return &SenderKey{chain: ck, priv: priv}, nil
}

// Distribution returns the current state for new receivers.
func (s *SenderKey) Distribution() Distribution {
	return Distribution{Iteration: s.iter, Chain: s.chain, SignPub: s.priv.Public().(ed25519.PublicKey)}
}

func header(iter uint32) []byte { return binary.BigEndian.AppendUint32(nil, iter) }

// Encrypt derives the next message key, encrypts once and signs the result.
func (s *SenderKey) Encrypt(plaintext []byte) (GroupMessage, error) {
	mk, next := s.chain.Next()
	ct, err := Seal(mk, plaintext, header(s.iter))
	if err != nil {
		return GroupMessage{}, err
	}
	msg := GroupMessage{Iteration: s.iter, Ciphertext: ct}
	msg.Signature = ed25519.Sign(s.priv, append(header(s.iter), ct...))
	s.chain, s.iter = next, s.iter+1
	return msg, nil
}

// Errors a receiver can return.
var (
	ErrBadSignature = errors.New("ratchet: bad sender signature")
	ErrTooFarAhead  = errors.New("ratchet: iteration beyond MaxSkip")
	ErrDuplicate    = errors.New("ratchet: message key already used or too old")
)

// Receiver is one member device's copy of another member's sender key.
type Receiver struct {
	iter    uint32
	chain   ChainKey
	pub     ed25519.PublicKey
	skipped map[uint32][32]byte
}

// NewReceiver installs a distribution received over a pairwise session.
func NewReceiver(d Distribution) *Receiver {
	return &Receiver{iter: d.Iteration, chain: d.Chain, pub: d.SignPub, skipped: map[uint32][32]byte{}}
}

// Decrypt handles in-order, late, out-of-order and lost messages. A used key
// is deleted, so a replay fails and old keys cannot be recovered later.
func (r *Receiver) Decrypt(m GroupMessage) ([]byte, error) {
	if !ed25519.Verify(r.pub, append(header(m.Iteration), m.Ciphertext...), m.Signature) {
		return nil, ErrBadSignature
	}
	if m.Iteration < r.iter {
		mk, ok := r.skipped[m.Iteration]
		if !ok {
			return nil, ErrDuplicate
		}
		delete(r.skipped, m.Iteration)
		return Open(mk, m.Ciphertext, header(m.Iteration))
	}
	if m.Iteration-r.iter > MaxSkip {
		return nil, ErrTooFarAhead
	}
	for r.iter < m.Iteration {
		mk, next := r.chain.Next()
		r.skipped[r.iter] = mk
		r.chain, r.iter = next, r.iter+1
	}
	mk, next := r.chain.Next()
	pt, err := Open(mk, m.Ciphertext, header(m.Iteration))
	if err != nil {
		return nil, err
	}
	r.chain, r.iter = next, r.iter+1
	return pt, nil
}
go
package ratchet

import (
	"crypto/rand"
	"errors"
	"testing"
)

func group(t *testing.T) (*SenderKey, *Receiver) {
	t.Helper()
	sk, err := NewSenderKey(rand.Reader)
	if err != nil {
		t.Fatal(err)
	}
	return sk, NewReceiver(sk.Distribution())
}

func TestChainIsOneWay(t *testing.T) {
	var ck ChainKey
	mk1, ck2 := ck.Next()
	mk2, _ := ck2.Next()
	if mk1 == mk2 || [32]byte(ck2) == mk1 {
		t.Fatal("message keys must differ per step and from the chain key")
	}
}

func TestOneCiphertextManyReceivers(t *testing.T) {
	sk, _ := NewSenderKey(rand.Reader)
	var members []*Receiver
	for range 5 {
		members = append(members, NewReceiver(sk.Distribution()))
	}
	msg, _ := sk.Encrypt([]byte("dinner at 8?"))
	for i, m := range members {
		pt, err := m.Decrypt(msg) // the server fanned out the SAME bytes
		if err != nil || string(pt) != "dinner at 8?" {
			t.Fatalf("member %d: %v", i, err)
		}
	}
}

func TestOutOfOrderAndLoss(t *testing.T) {
	sk, r := group(t)
	m0, _ := sk.Encrypt([]byte("zero"))
	m1, _ := sk.Encrypt([]byte("one"))
	m2, _ := sk.Encrypt([]byte("two"))
	for _, m := range []GroupMessage{m2, m0} { // m1 lost, m0 late
		if _, err := r.Decrypt(m); err != nil {
			t.Fatalf("iteration %d: %v", m.Iteration, err)
		}
	}
	if _, ok := r.skipped[m1.Iteration]; !ok {
		t.Fatal("key for the lost message should still be cached")
	}
}

func TestReplayAndTamper(t *testing.T) {
	sk, r := group(t)
	m, _ := sk.Encrypt([]byte("hi"))
	if _, err := r.Decrypt(m); err != nil {
		t.Fatal(err)
	}
	if _, err := r.Decrypt(m); !errors.Is(err, ErrDuplicate) {
		t.Fatalf("replay: %v", err)
	}
	m2, _ := sk.Encrypt([]byte("hi again"))
	m2.Ciphertext[0] ^= 1
	if _, err := r.Decrypt(m2); !errors.Is(err, ErrBadSignature) {
		t.Fatalf("tamper: %v", err)
	}
}

func TestMaxSkip(t *testing.T) {
	sk, r := group(t)
	sk.iter = MaxSkip + 5
	m, _ := sk.Encrypt([]byte("far"))
	if _, err := r.Decrypt(m); !errors.Is(err, ErrTooFarAhead) {
		t.Fatalf("want ErrTooFarAhead, got %v", err)
	}
}

func TestMemberRemovalNeedsNewKey(t *testing.T) {
	old, removed := group(t)
	fresh, _ := NewSenderKey(rand.Reader) // everyone clears sender keys and starts over
	m, _ := fresh.Encrypt([]byte("after removal"))
	if _, err := removed.Decrypt(m); err == nil {
		t.Fatal("removed member decrypted a message under the new sender key")
	}
	_ = old
}

Example: encrypted media blobs ​

go
// Package media mirrors the published attachment scheme: encrypt with a fresh
// AES-256 key (CBC, random IV), append HMAC-SHA256, upload the blob, and send
// keys + SHA-256 of the blob + a pointer inside the normal E2E message.
// Educational re-implementation, not WhatsApp's code or wire format.
package media

import (
	"bytes"
	"crypto/aes"
	"crypto/cipher"
	"crypto/hmac"
	"crypto/sha256"
	"errors"
	"io"
)

// Ref travels inside the end-to-end encrypted message, never in the blob store.
type Ref struct {
	AESKey     [32]byte
	HMACKey    [32]byte
	BlobSHA256 [32]byte
	URL        string // pointer to the blob store / CDN object
}

// ErrIntegrity covers a wrong hash, a wrong MAC or bad padding.
var ErrIntegrity = errors.New("media: integrity check failed")

// Encrypt returns the opaque blob to upload and the reference to send.
// Blob layout (ours): IV(16) || AES-CBC ciphertext || HMAC(IV||ciphertext)(32).
func Encrypt(plain []byte, rand io.Reader, url string) ([]byte, Ref, error) {
	var ref Ref
	iv := make([]byte, aes.BlockSize)
	for _, b := range [][]byte{ref.AESKey[:], ref.HMACKey[:], iv} {
		if _, err := io.ReadFull(rand, b); err != nil {
			return nil, Ref{}, err
		}
	}
	block, err := aes.NewCipher(ref.AESKey[:])
	if err != nil {
		return nil, Ref{}, err
	}
	pad := aes.BlockSize - len(plain)%aes.BlockSize
	ct := append(bytes.Clone(plain), bytes.Repeat([]byte{byte(pad)}, pad)...)
	cipher.NewCBCEncrypter(block, iv).CryptBlocks(ct, ct)
	blob := append(iv, ct...)
	m := hmac.New(sha256.New, ref.HMACKey[:])
	m.Write(blob)
	blob = m.Sum(blob)
	ref.BlobSHA256 = sha256.Sum256(blob)
	ref.URL = url
	return blob, ref, nil
}

// Decrypt checks the blob hash, then the MAC, then decrypts.
func Decrypt(blob []byte, ref Ref) ([]byte, error) {
	if sha256.Sum256(blob) != ref.BlobSHA256 || len(blob) < 2*aes.BlockSize+sha256.Size {
		return nil, ErrIntegrity
	}
	body, tag := blob[:len(blob)-sha256.Size], blob[len(blob)-sha256.Size:]
	m := hmac.New(sha256.New, ref.HMACKey[:])
	m.Write(body)
	if !hmac.Equal(tag, m.Sum(nil)) {
		return nil, ErrIntegrity
	}
	iv, ct := body[:aes.BlockSize], bytes.Clone(body[aes.BlockSize:])
	if len(ct)%aes.BlockSize != 0 {
		return nil, ErrIntegrity
	}
	block, err := aes.NewCipher(ref.AESKey[:])
	if err != nil {
		return nil, err
	}
	cipher.NewCBCDecrypter(block, iv).CryptBlocks(ct, ct)
	pad := int(ct[len(ct)-1])
	if pad == 0 || pad > aes.BlockSize {
		return nil, ErrIntegrity
	}
	return ct[:len(ct)-pad], nil
}
go
package media

import (
	"bytes"
	"crypto/rand"
	"errors"
	"testing"
)

func TestRoundTripAndOpaqueBlob(t *testing.T) {
	photo := bytes.Repeat([]byte("JPEG"), 1000)
	blob, ref, err := Encrypt(photo, rand.Reader, "https://media.example.com/b/1")
	if err != nil {
		t.Fatal(err)
	}
	if bytes.Contains(blob, []byte("JPEGJPEG")) {
		t.Fatal("blob store would see plaintext")
	}
	got, err := Decrypt(blob, ref)
	if err != nil || !bytes.Equal(got, photo) {
		t.Fatalf("round trip failed: %v", err)
	}
}

func TestSwappedBlobRejected(t *testing.T) {
	blob, ref, _ := Encrypt([]byte("real"), rand.Reader, "u")
	other, _, _ := Encrypt([]byte("fake"), rand.Reader, "u")
	if _, err := Decrypt(other, ref); !errors.Is(err, ErrIntegrity) {
		t.Fatalf("CDN swapped the object: %v", err)
	}
	blob[20] ^= 1
	if _, err := Decrypt(blob, ref); !errors.Is(err, ErrIntegrity) {
		t.Fatalf("bit flip: %v", err)
	}
}

Demo program ​

go
// Command demo replays one chat through the teaching re-implementations:
// offline queue, retry dedup, stale device list, receipts, and a group
// message encrypted once with a sender key and fanned out by the server.
package main

import (
	"crypto/rand"
	"fmt"
	"time"

	"academy/case-study-whatsapp/mailbox"
	"academy/case-study-whatsapp/ratchet"
)

func main() {
	now := time.Date(2026, 1, 1, 12, 0, 0, 0, time.UTC)
	srv := mailbox.New(30*24*time.Hour, func() time.Time { return now })
	for _, d := range []mailbox.DeviceID{"alice:0", "bob:0", "bob:1"} {
		srv.Register(d)
	}

	stale := mailbox.Envelope{ClientMsgID: "c-1", From: "alice:0", Chat: "a-b", Recipients: []string{"bob"},
		To: map[mailbox.DeviceID][]byte{"bob:0": []byte("ct-phone")}}
	_, err := srv.Submit(stale)
	fmt.Println("1 submit for bob:0 only        ->", err)

	stale.To["bob:1"] = []byte("ct-laptop")
	id, _ := srv.Submit(stale)
	fmt.Println("2 resend for bob:0 + bob:1     ->", id, srv.StatusOf(id))
	again, _ := srv.Submit(stale)
	fmt.Println("3 client retry, same id        ->", again, "queue bob:0 =", len(srv.Pending("bob:0")))

	srv.Ack("bob:1", id, mailbox.KindMessage)
	fmt.Println("4 bob:1 online, acks           ->", srv.StatusOf(id), "queue bob:1 =", len(srv.Pending("bob:1")))
	srv.MarkRead("bob:1", id)
	fmt.Println("5 bob opens chat on laptop     ->", srv.StatusOf(id))
	for _, r := range srv.Pending("alice:0") {
		fmt.Printf("6 receipt queued for alice:0   -> kind=%d msg=%s\n", r.Kind, r.MsgID)
	}

	sk, _ := ratchet.NewSenderKey(rand.Reader)
	members := []*ratchet.Receiver{ratchet.NewReceiver(sk.Distribution()), ratchet.NewReceiver(sk.Distribution())}
	gm, _ := sk.Encrypt([]byte("group hello"))
	for i, m := range members {
		pt, err := m.Decrypt(gm)
		fmt.Printf("7 member %d decrypts iteration %d -> %q %v\n", i, gm.Iteration, pt, err)
	}
	_, err = members[0].Decrypt(gm)
	fmt.Println("8 replay of the same ciphertext ->", err)
}

The Go angle ​

  • Standard library only. crypto/hkdf (in the standard library since Go 1.24), crypto/hmac, crypto/aes, crypto/cipher, crypto/ed25519, crypto/sha256. No X25519 X3DH here; crypto/ecdh provides X25519 if you extend it.
  • Goroutine per connection is Go's equivalent of an Erlang process per connection; a goroutine starts with a few KB of stack, so a million idle connections is a memory-planning exercise, not an impossibility. Unlike BEAM, Go has no per-process heap and no hot code loading; you drain and restart instead.
  • Production libraries: the Signal Protocol reference is libsignal (Rust, with Java/Swift/TypeScript bindings); Go projects usually wrap it rather than reimplement it.
  • Determinism in tests: the mailbox takes an injected clock, so TTL behaviour is tested without sleeping.
  • Concurrency: one mutex makes the invariants readable; a real server shards the mailbox by device id so each shard has one owner, which is the same idea as WhatsApp's "Isolate records to 1 node/1 process via hashing".

Laravel ​

Before ​

One shared messages table polled by every client: plaintext on the server, duplicates on retry, rows forever, no per-device copies, no receipts.

php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

// Before: one shared messages table that every client polls. Plaintext on the
// server, no dedup on retry, rows kept forever, no receipts, no per-device copy.
class MessageController extends Controller
{
    public function store(Request $request): JsonResponse
    {
        $id = DB::table('messages')->insertGetId([
            'from_user' => $request->user()->id,
            'to_user' => $request->integer('to'),
            'body' => $request->string('body'),
            'created_at' => now(),
        ]);

        return response()->json(['id' => $id], 201);
    }

    public function index(Request $request): JsonResponse
    {
        // Every poll re-reads everything since the start of time.
        return response()->json(
            DB::table('messages')->where('to_user', $request->user()->id)->orderBy('id')->get()
        );
    }
}

After ​

1. Schema. Devices with public identity keys, a per-chat sequence row, submissions with a unique (from_device, client_msg_id) for retry dedup, and per-device mailbox entries holding opaque ciphertext. The same schema in plain PostgreSQL:

sql
CREATE TABLE devices (
  id           varchar(64) PRIMARY KEY,     -- 'account:n', n = 0 is the phone
  account      varchar(32) NOT NULL,
  identity_key bytea NOT NULL               -- public key only
);
CREATE TABLE submissions (
  id            bigserial PRIMARY KEY,
  from_device   varchar(64) NOT NULL,
  client_msg_id varchar(64) NOT NULL,
  chat_id       varchar(64) NOT NULL,
  seq           bigint NOT NULL,
  status        smallint NOT NULL DEFAULT 1, -- 1 sent, 2 delivered, 3 read
  UNIQUE (from_device, client_msg_id)
);
CREATE TABLE mailbox_entries (
  id            bigserial PRIMARY KEY,
  device_id     varchar(64) NOT NULL,
  submission_id bigint NOT NULL REFERENCES submissions(id) ON DELETE CASCADE,
  kind          smallint NOT NULL,           -- 0 message, 1 delivered, 2 read
  ciphertext    bytea,
  enqueued_at   timestamptz NOT NULL,
  UNIQUE (device_id, submission_id, kind)
);
CREATE INDEX ON mailbox_entries (device_id, id);   -- FIFO drain per device
-- drain:  SELECT ... FROM mailbox_entries WHERE device_id = $1 ORDER BY id;
-- ack:    DELETE FROM mailbox_entries WHERE device_id = $1 AND submission_id = $2 AND kind = 0;
-- sweep:  DELETE FROM mailbox_entries WHERE enqueued_at < now() - interval '30 days';
php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('devices', function (Blueprint $table) {
            $table->string('id', 64)->primary();          // "account:n", n = 0 is the phone
            $table->string('account', 32)->index();
            $table->binary('identity_key', length: 32);    // public key only
            $table->timestamps();
        });

        Schema::create('chat_sequences', function (Blueprint $table) {
            $table->string('chat_id', 64)->primary();
            $table->unsignedBigInteger('last_seq')->default(0);
        });

        Schema::create('submissions', function (Blueprint $table) {
            $table->id();
            $table->string('from_device', 64);
            $table->string('client_msg_id', 64);
            $table->string('chat_id', 64);
            $table->unsignedBigInteger('seq');
            $table->unsignedTinyInteger('status')->default(1); // 1 sent, 2 delivered, 3 read
            $table->timestamps();
            $table->unique(['from_device', 'client_msg_id']);  // retry dedup
        });

        Schema::create('mailbox_entries', function (Blueprint $table) {
            $table->id();
            $table->string('device_id', 64);
            $table->foreignId('submission_id')->constrained()->cascadeOnDelete();
            $table->unsignedTinyInteger('kind');               // 0 message, 1 delivered, 2 read
            $table->binary('ciphertext')->nullable();          // opaque per-device ciphertext
            $table->timestamp('enqueued_at')->index();         // TTL sweep
            $table->unique(['device_id', 'submission_id', 'kind']);
            $table->index(['device_id', 'id']);                // FIFO drain per device
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('mailbox_entries');
        Schema::dropIfExists('submissions');
        Schema::dropIfExists('chat_sequences');
        Schema::dropIfExists('devices');
    }
};

2. The mailbox service. DB::transaction plus lockForUpdate() on the chat's sequence row assigns per-chat order; insertOrIgnore keeps receipts idempotent; the device-list hash check mirrors Sender Side Backfill.

php
<?php

namespace App\Services;

use App\Events\MailboxEntryQueued;
use Illuminate\Support\Facades\DB;
use RuntimeException;

// Store-and-forward mailbox in the shape WhatsApp describes publicly
// (per-device queues, client-fanout, delete after delivery, receipts).
// Teaching code, not WhatsApp's implementation.
class Mailbox
{
    public const SENT = 1;
    public const DELIVERED = 2;
    public const READ = 3;

    /**
     * @param  array<string, string>  $ciphertexts  device id => ciphertext (client-fanout)
     * @param  list<string>  $recipients  accounts in the chat other than the sender
     */
    public function submit(string $fromDevice, string $clientMsgId, string $chatId, array $recipients, array $ciphertexts): int
    {
        $existing = DB::table('submissions')
            ->where(['from_device' => $fromDevice, 'client_msg_id' => $clientMsgId])
            ->value('id');
        if ($existing !== null) {
            return (int) $existing; // retry after a lost ack: same id, nothing new stored
        }

        $this->assertDeviceListFresh($fromDevice, $recipients, array_keys($ciphertexts));

        $id = DB::transaction(function () use ($fromDevice, $clientMsgId, $chatId, $ciphertexts) {
            DB::table('chat_sequences')->insertOrIgnore(['chat_id' => $chatId, 'last_seq' => 0]);
            $seq = DB::table('chat_sequences')->where('chat_id', $chatId)->lockForUpdate()->value('last_seq') + 1;
            DB::table('chat_sequences')->where('chat_id', $chatId)->update(['last_seq' => $seq]);

            $id = DB::table('submissions')->insertGetId([
                'from_device' => $fromDevice, 'client_msg_id' => $clientMsgId, 'chat_id' => $chatId,
                'seq' => $seq, 'status' => self::SENT, 'created_at' => now(), 'updated_at' => now(),
            ]);
            foreach ($ciphertexts as $device => $ciphertext) {
                DB::table('mailbox_entries')->insert([
                    'device_id' => $device, 'submission_id' => $id, 'kind' => 0,
                    'ciphertext' => $ciphertext, 'enqueued_at' => now(),
                ]);
            }

            return $id;
        });

        foreach (array_keys($ciphertexts) as $device) {
            MailboxEntryQueued::dispatch($device);
        }

        return $id;
    }

    /** Entries for one device, oldest first, after the TTL sweep. */
    public function pending(string $deviceId, int $ttlDays = 30): array
    {
        DB::table('mailbox_entries')->where('enqueued_at', '<', now()->subDays($ttlDays))->delete();

        return DB::table('mailbox_entries')
            ->join('submissions', 'submissions.id', '=', 'mailbox_entries.submission_id')
            ->where('mailbox_entries.device_id', $deviceId)
            ->orderBy('mailbox_entries.id')
            ->get(['submission_id', 'kind', 'ciphertext', 'chat_id', 'seq', 'from_device'])
            ->all();
    }

    /** Delivery ack: delete the entry, then emit "delivered" once per message. */
    public function ack(string $deviceId, int $submissionId, int $kind): void
    {
        DB::transaction(function () use ($deviceId, $submissionId, $kind) {
            DB::table('mailbox_entries')
                ->where(['device_id' => $deviceId, 'submission_id' => $submissionId, 'kind' => $kind])
                ->delete();
            if ($kind === 0) {
                $this->advance($deviceId, $submissionId, self::DELIVERED);
            }
        });
    }

    public function markRead(string $deviceId, int $submissionId): void
    {
        DB::transaction(fn () => $this->advance($deviceId, $submissionId, self::READ));
    }

    private function advance(string $deviceId, int $submissionId, int $to): void
    {
        $sub = DB::table('submissions')->where('id', $submissionId)->lockForUpdate()->first();
        if ($sub === null || $this->account($sub->from_device) === $this->account($deviceId) || $sub->status >= $to) {
            return; // receipts never move backwards
        }
        DB::table('submissions')->where('id', $submissionId)->update(['status' => $to, 'updated_at' => now()]);

        $senderDevices = DB::table('devices')->where('account', $this->account($sub->from_device))->pluck('id');
        foreach ($senderDevices as $device) {
            DB::table('mailbox_entries')->insertOrIgnore([
                'device_id' => $device, 'submission_id' => $submissionId,
                'kind' => $to === self::READ ? 2 : 1, 'ciphertext' => null, 'enqueued_at' => now(),
            ]);
        }
    }

    /** "Sender Side Backfill" in miniature: reject a send built for a stale device set. */
    private function assertDeviceListFresh(string $fromDevice, array $recipients, array $listed): void
    {
        $expected = DB::table('devices')
            ->whereIn('account', $recipients)
            ->orWhere(fn ($q) => $q->where('account', $this->account($fromDevice))->where('id', '!=', $fromDevice))
            ->pluck('id')->all();
        sort($expected);
        sort($listed);
        if (hash('sha256', implode("\0", $expected)) !== hash('sha256', implode("\0", $listed))) {
            throw new RuntimeException('stale device list');
        }
    }

    private function account(string $deviceId): string
    {
        return explode(':', $deviceId, 2)[0];
    }
}

3. Wake-up event over Reverb. ShouldBroadcastNow on a PrivateChannel('device.'.$id), with an empty payload: the WebSocket only says "drain your mailbox", so a lost frame never loses a message.

php
<?php

namespace App\Events;

use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
use Illuminate\Foundation\Events\Dispatchable;

// A wake-up hint pushed over Reverb to an online device. It carries no
// ciphertext: the device drains its mailbox over HTTP and acks each entry,
// so a lost WebSocket frame never loses a message.
class MailboxEntryQueued implements ShouldBroadcastNow
{
    use Dispatchable;

    public function __construct(public string $deviceId)
    {
    }

    public function broadcastOn(): PrivateChannel
    {
        return new PrivateChannel('device.'.$this->deviceId);
    }

    public function broadcastAs(): string
    {
        return 'mailbox.queued';
    }

    public function broadcastWith(): array
    {
        return [];
    }
}

4. Controller and routes. HTTP 409 tells the client its device list is stale.

php
<?php

namespace App\Http\Controllers;

use App\Services\Mailbox;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use RuntimeException;

class MailboxController extends Controller
{
    public function __construct(private Mailbox $mailbox)
    {
    }

    public function submit(Request $request): JsonResponse
    {
        $data = $request->validate([
            'client_msg_id' => ['required', 'string', 'max:64'],
            'chat_id' => ['required', 'string', 'max:64'],
            'recipients' => ['required', 'array'],
            'ciphertexts' => ['required', 'array'], // device id => base64 ciphertext
        ]);
        $device = (string) $request->header('X-Device-Id');

        try {
            $id = $this->mailbox->submit(
                $device, $data['client_msg_id'], $data['chat_id'], $data['recipients'],
                array_map('base64_decode', $data['ciphertexts']),
            );
        } catch (RuntimeException) {
            return response()->json(['error' => 'stale_device_list'], 409); // refetch devices, resend
        }

        return response()->json(['id' => $id, 'status' => 'sent'], 201);
    }

    public function pending(Request $request): JsonResponse
    {
        $entries = array_map(function ($e) {
            $e->ciphertext = $e->ciphertext === null ? null : base64_encode($e->ciphertext);

            return $e;
        }, $this->mailbox->pending((string) $request->header('X-Device-Id')));

        return response()->json($entries);
    }

    public function ack(Request $request, int $id): JsonResponse
    {
        $this->mailbox->ack((string) $request->header('X-Device-Id'), $id, $request->integer('kind'));

        return response()->json(null, 204);
    }

    public function read(Request $request, int $id): JsonResponse
    {
        $this->mailbox->markRead((string) $request->header('X-Device-Id'), $id);

        return response()->json(null, 204);
    }
}
php
<?php

use App\Http\Controllers\MailboxController;
use Illuminate\Support\Facades\Route;

// Device authentication (Sanctum token bound to X-Device-Id) is assumed.
Route::middleware(['auth:sanctum', 'throttle:api'])->group(function () {
    Route::post('/messages', [MailboxController::class, 'submit']);
    Route::get('/mailbox', [MailboxController::class, 'pending']);
    Route::post('/mailbox/{id}/ack', [MailboxController::class, 'ack']);
    Route::post('/messages/{id}/read', [MailboxController::class, 'read']);
});

5. Channels: device wake-ups, chat presence and typing.

php
<?php

use Illuminate\Support\Facades\Broadcast;

// Only the owner of a device may listen on its wake-up channel.
Broadcast::channel('device.{deviceId}', function ($user, string $deviceId) {
    return str_starts_with($deviceId, $user->account.':');
});

// Presence for one chat; typing indicators are client events sent with
// Echo's whisper('typing', ...) and never stored on the server.
Broadcast::channel('chat.{chatId}', function ($user, string $chatId) {
    return $user->chats()->whereKey($chatId)->exists()
        ? ['id' => $user->id, 'name' => $user->name]
        : false;
});

The Laravel angle ​

  • Reverb is Laravel's first-party WebSocket server (php artisan install:broadcasting installs it); private and presence channels are authorised in routes/channels.php with Broadcast::channel.
  • Typing indicators are client events: Laravel Echo's whisper sends them to other channel members without hitting your application code or database, which matches "never stored".
  • ShouldBroadcastNow broadcasts synchronously instead of through the queue; use it for tiny wake-up hints, and keep the authoritative data in the database.
  • Laravel is not the place for the cryptography: E2EE happens on clients (libsignal in the mobile app or a browser build); the server stores binary columns it cannot read.
  • Scale note (inference): a PHP-FPM request model cannot hold a million sockets per box; Reverb runs as a separate long-lived process and scales horizontally with Redis pub/sub, while the mailbox tables are partitioned by device_id.

What you can copy ​

WhatsApp subsystemThe reusable ideaGeneric chapter
Erlang chat serversOne cheap concurrent unit per connection; measure contention before adding hostsScaling Strategies
Long-lived connectionsWebSocket or raw TCP with resume; presence from connection stateReal-Time Communication
Offline storagePer-device mailbox, delete on ack, write-back cache for spikesMessage Acknowledgment
ReceiptsMonotonic status: sent, delivered, readDelivery Guarantees
Retry handlingClient-generated message id, server dedupAPI Idempotency
OrderingPer-chat sequence, per-device FIFOOrdering & Partitioning
Signal ProtocolPrekeys for offline setup, ratchets for forward secrecyCryptography in Practice
Sender keysEncrypt once, fan out by server, rekey on membership changeFeeds: Fan-Out
Client-fanoutPer-device copies when devices have their own keysFeeds: Fan-Out
Media keys in messageOpaque blobs in object storage and CDNObject Storage, CDNs
Key transparencyAppend-only, auditable directoryMerkle Trees
Backup Key VaultHSM with attempt limits for password-derived recoveryAuthentication
Partitioned Mnesia, islandsOne owner per key; small replica groupsSharding at System Level
Meta-clusteringLimit cluster size, link clusters with single-hop routingCapacity Planning & DR
Abuse on metadataRate and behaviour signals, report weightingRate Limiting
DC migrationIncremental, slice by sliceStrangler Fig

Solving the classic problems ​

"Deliver to a phone that is offline for days" ​

SolutionHowAdvantageCost / limitation
Per-device offline queueStore ciphertext per device until ackSimple, at-least-onceStorage for long-offline devices; needs TTL
Push notification wake-upAPNs/FCM nudges the app to connectFaster pickupPush is best effort; never the data path
Store forever as historyServer keeps all messagesAny device can read historyIncompatible with WhatsApp's "not stored after delivered" model

"The sender retried; do not show it twice" ​

SolutionHowAdvantageCost
Client message id + unique constraint(from_device, client_msg_id)Exact dedupDedup table retention
Content hash dedupHash bodyNo client changeWrong for legitimately repeated "ok"
Receiver-side dedupDevice ignores known idsDefence in depthNeeds stable ids end to end

"Group of 500 members: who encrypts what?" ​

SolutionSender costServer costSecurity note
Sender keys (WhatsApp)1 per message + N on first send / rekeyFan outRekey on every leave
Pairwise for every messageN per messageRoute NStrongest per-message ratchet, expensive
Server-side encryption1Fan outServer can read: not E2EE

"Messages arrive out of order or get lost" ​

LayerTechnique
TransportOne connection, FIFO per device queue
ServerPer-chat sequence assigned under a lock (our Laravel lockForUpdate)
CryptoSkipped message keys cached up to MAX_SKIP
UISort by sequence, show gaps as "waiting for this message" (inference)

"A new device appears mid-conversation" ​

Use the device-list hash on every send, reject with a specific error, let the client refresh and resend only to new devices, and bound the backfill window as the white paper does.

Choosing ​

Your productRecommendationExtra techniqueReason
Consumer 1:1 and small-group chatWhatsApp model: E2EE, per-device mailbox, sender keysKey transparencyPrivacy is the product
Team chat with search and complianceServer-readable history (Discord/Slack model)Encryption at rest, access logsSearch and eDiscovery need plaintext
Customer support chatServer-side history, E2EE optionalRetention policiesAgents share conversations
Notifications / alertsStore-and-forward with acks, no E2EEPush wake-upsDelivery, not secrecy
Very large broadcast channelsServer fan-out, not sender keys per subscriberCDN for mediaFan-out to millions, few writers
IoT command deliveryPer-device mailbox, TTLIdempotent commandsDevices are offline often

In architecture: from a single process to a distributed system ​

Monolith: one process, one database ​

A Laravel app with Reverb and PostgreSQL, using the mailbox schema above: messages are rows per device, ack deletes them, a Reverb private channel wakes the device. This handles a startup's first hundred thousand users if each device drains over HTTP and only wake-ups go over WebSockets (inference).

Modular monolith: boundaries without the network ​

Split modules the way WhatsApp's 2014 overview lists services: account, profile, push, group, offline storage, media. Each module owns its tables; the chat module calls the group module for membership but never reads its tables. This is the "Silo architecture" idea from Mahdavi 2016 inside one deployable.

Microservices: what crosses service boundaries ​

text
1  client -> chat edge (WebSocket/Noise) : submit {client_msg_id, per-device ciphertexts}
2  chat edge -> device registry          : device-list hash check (409 if stale)
3  chat edge -> mailbox service          : append per device (idempotent on client_msg_id)
4  mailbox -> chat edge of bob:1         : wake-up (pub/sub), bob:1 drains, acks
5  mailbox -> receipts                   : delivered -> sender's devices
6  media client -> media service         : PUT opaque blob; key never leaves the E2E message

No distributed transaction is needed because each step is idempotent and the sender retries with the same id (Delivery Guarantees).

Distributed data: replicas, caches, multi-region ​

WhatsApp's published answers: hash every record to one owner node, keep replica groups tiny (Mnesia islands of two), prefer async replication (async_dirty), and link data centres with single-hop meta-clustering rather than one global cluster. Where it breaks: a primary that acknowledged an entry and died before replicating it can lose that entry unless the sender retries until a device ack arrives (inference; the sender's UI shows one check until then).

Scaling path: 1x, 10x, 100x ​

LoadWhat changesWhatsApp parallel
1x (10k concurrent)One app server, one database, Reverbejabberd on a few machines (secondary)
10x (100k)Separate connection tier; mailbox partitioned by device2012: 200k to 2M connections per server by fixing contention
100x (1M+)Many connection servers, partitioned services, media on separate servers and CDN2014: ~150 chat + ~250 mms servers, meta-clusters per DC
1000xMultiple regions, edge media caches, automated abuse systems2017+: Facebook data centres, edge POPs, ML abuse detection

Lab ​

Single-process Go programs and tests were run on the author's machine; the Laravel part is "expected, not run".

Experiment 1: run the tests.

bash
cd docs/snippets/system-design/case-study-whatsapp/go
go test ./...
# ok  academy/case-study-whatsapp/before
# ok  academy/case-study-whatsapp/mailbox
# ok  academy/case-study-whatsapp/media
# ok  academy/case-study-whatsapp/ratchet

Experiment 2: replay one chat with the demo (run).

bash
go run ./cmd/demo
1 submit for bob:0 only        -> mailbox: destination device list is stale
2 resend for bob:0 + bob:1     -> m1 sent
3 client retry, same id        -> m1 queue bob:0 = 1
4 bob:1 online, acks           -> delivered queue bob:1 = 0
5 bob opens chat on laptop     -> read
6 receipt queued for alice:0   -> kind=1 msg=m1
6 receipt queued for alice:0   -> kind=2 msg=m1
7 member 0 decrypts iteration 0 -> "group hello" <nil>
7 member 1 decrypts iteration 0 -> "group hello" <nil>
8 replay of the same ciphertext -> ratchet: message key already used or too old

Experiment 3: see the naive relay fail. go test ./before -run Offline -v passes because the test asserts the bug: the offline recipient's channel is empty after connect.

Experiment 4: out-of-order and lost group messages. go test ./ratchet -run OutOfOrder -v: message 2 decrypts before message 0, message 1 is lost, and its key stays cached in skipped.

Experiment 5: Laravel mailbox (expected, not run).

bash
php artisan migrate
curl -s -X POST localhost:8000/api/messages -H 'Authorization: Bearer TOKEN' -H 'X-Device-Id: alice:0' \
  -H 'Content-Type: application/json' \
  -d '{"client_msg_id":"c-1","chat_id":"a-b","recipients":["bob"],"ciphertexts":{"bob:0":"Y3Qw"}}'
# expected, not run: {"error":"stale_device_list"}   (bob:1 is registered)
# resend with "bob:1":"Y3Qx" added -> {"id":1,"status":"sent"}
# same request again                -> {"id":1,"status":"sent"} and still one entry per device
curl -s localhost:8000/api/mailbox -H 'X-Device-Id: bob:1' -H 'Authorization: Bearer TOKEN'
# expected, not run: [{"submission_id":1,"kind":0,"ciphertext":"Y3Qx","chat_id":"a-b","seq":1,"from_device":"alice:0"}]

Experiment 6: read the primary numbers yourself. Open Reed's 2014 slides, page "Numbers", and redo the estimate arithmetic for 342K msgs/s in and 712K out.

Common misconceptions ​

BeliefReality
Erlang alone made one server hold 2M connectionsThe 2012 talk: contention fixes, most "required BEAM patches", plus FreeBSD backports
WhatsApp stores your chat history on its servers"Messages are not stored on the server after they are delivered" (Meta 2021); encrypted app state is stored
Two gray checks mean the person saw itDelivered to the phone or any linked device; blue means read
Group messages are encrypted once per memberSender key distribution is pairwise; each message is one ciphertext with server fan-out
Web and desktop read through your phoneSince 2021, companions have their own identity keys and receive client-fanout copies
E2EE media cannot use a CDNBlobs are opaque; keys and hash travel in the E2E message
Backups were always E2EEOpt-in since 2021; before that the cloud provider secured them
E2EE means WhatsApp cannot fight spamIt uses registration, behaviour and report signals; 2M+ bans per month in 2019
WhatsApp is plain XMPPNo WhatsApp source says so; FunXMPP is a secondary-source description
A huge team ran itAbout 10 engineers on Erlang in 2014, doing development and operations
Hot code loading is a party trickWhatsApp: "Erlang hot load – zero dropped connections or requests"
One-time prekeys are mandatoryWithout one, the final ECDH is omitted and setup still works

Cheat sheet ​

TopicRemember
Stack 2012 / 2014 / 2016FreeBSD 8.3 + OTP R14B03 / FreeBSD 9.2 + R16B01 / FreeBSD 10 + R16B
Connections2M+ per server (2012), 2.8M peak; ~1M phones per chat server (2014)
Scale147M concurrent, 19B in / 40B out per day (2014); ~100B/day (2020)
Team~10 on Erlang (2014)
DeliveryStore until device ack, then delete; offline storage with write-back cache
Receipts1 gray sent, 2 gray delivered (any linked device), 2 blue read
TransportNoise Pipes, Curve25519, AES-GCM, SHA256
Session setupX3DH: identity key, signed prekey, one-time prekey, ephemeral key
Message keysMK = HMAC(CK,0x01), CK = HMAC(CK,0x02); 80-byte key; AES-CBC + HMAC
GroupsSender key pairwise once, then 1 ciphertext, server-side fan-out; reset on leave
Multi-devicePer-device identity keys, client-fanout, up to 4 companions, Sender Side Backfill
MediaRandom AES + HMAC keys, encrypted blob, hash + pointer in message
BackupsOpt-in E2EE; 64-digit key or password with HSM Backup Key Vault behind ChatD
Verification60-digit code / QR; key transparency with AKD (2023)
AbuseRegistration, messaging behaviour, reports; no content

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — Why did WhatsApp's per-server connection count go from 200k to 2M without a new language or new hardware? Important ​

Answer

Answer: Contention fixes: Reed 2012 says "From 200k to 2M were all contention fixes", most of them BEAM patches, plus FreeBSD backports (timecounter, igb driver) and app changes such as partitioning workloads. See Connection layer.

2 — What exactly do two gray check marks promise the sender? Must-know ​

Answer

Answer: That the message reached the recipient's phone or any of their linked devices (WhatsApp Help Center). Not that it was read; that is the blue state. See Delivery.

3 — How can Alice start an encrypted session with Bob while Bob is offline? Important ​

Answer

Answer: X3DH: Bob previously uploaded his identity key, signed prekey and one-time prekeys. Alice fetches them, computes three or four ECDHs with an ephemeral key, derives root and chain keys, and sends her first message with the setup header. See E2EE.

4 — Why does a 200-member group not cost 200 encryptions per message? Important ​

Answer

Answer: Sender keys: each member distributes its sender key once over pairwise sessions; each message is then encrypted once and the server fans out the single ciphertext. See Groups.

5 — What happens when a member leaves a group, and why? Important ​

Answer

Answer: All participants clear their sender keys and start over, so the departed member, who knows the old chain keys, cannot read new messages. See Groups and the Go test TestMemberRemovalNeedsNewKey.

6 — What is client-fanout and when does WhatsApp use it? Good to know ​

Answer

Answer: The sending client encrypts and transmits a message N times, once per destination device with that device's pairwise session, including the sender's own other devices. Used for one-to-one chats and multi-device. See Multi-device.

7 — How does the server help when the sender forgot one of the recipient's new devices? Good to know ​

Answer

Answer: Sender Side Backfill: the server compares the hash of the listed destination devices with its records; on mismatch it tells the sender to refresh device lists, verify new devices, and resend to them, within a short window. See Multi-device.

8 — Why can a CDN serve WhatsApp media without breaking end-to-end encryption? Must-know ​

Answer

Answer: The blob is encrypted on the sender's device; the AES and HMAC keys, the SHA-256 of the blob and the pointer travel inside the E2E message. The CDN sees only opaque bytes and a swapped object fails the hash check. See Media.

9 — With a password-protected E2EE backup, what does WhatsApp know? Important ​

Answer

Answer: That a key exists in the HSM-based Backup Key Vault, not the key itself; the vault verifies the password and makes the key permanently inaccessible after too many failed attempts. See Backups.

10 — Name three abuse signals that need no message content. Important ​

Answer

Answer: Registration reputation (phone prefix, network, carrier), send rate and group creation rate (for example 100 messages in 15 seconds), and missing typing indicators; plus weighted user reports. See Abuse.

11 — Which statements on this page about the data-centre migration are published, and which are inference? Must-know ​

Answer

Answer: Published: the 2014 acquisition, bare-metal FreeBSD in 2016, and the media service migrating to Facebook data centres with edge POPs and offnet caches (2017). Inference: the migration method, its order beyond media, and the OS change. See Migration.

Glossary ​

TermMeaning
WhatsAppPhone-number-based messenger, owned by Facebook/Meta since 2014
ErlangConcurrent functional language with lightweight processes; WhatsApp's server language
OTPOpen Telecom Platform: Erlang's libraries and behaviours (gen_server, supervisor, Mnesia, pg2)
BEAMThe Erlang virtual machine; WhatsApp patched it heavily
FreeBSDUnix-like OS WhatsApp ran on bare metal (8.3, 9.2, 10)
ejabberdOpen-source Erlang XMPP server; WhatsApp's reported starting point (secondary)
XMPPExtensible Messaging and Presence Protocol, XML-based IM standard
FunXMPPName used by a 2015 forensic study for WhatsApp's binary XMPP-like encoding (secondary)
Noise PipesNoise Protocol Framework handshake pattern WhatsApp uses for client-server transport
Simultaneous connectionsConcurrent open client connections; per-server connections is the same per box
Store-and-forwardServer keeps a message until the next hop takes it, then forwards and deletes
Offline queuePer-device storage of undelivered messages (WhatsApp: offline storage service)
AcknowledgementConfirmation from server (sent) or device (delivered)
Read receiptSignal that the recipient opened the message; two blue checks
RetryResending after a timeout; safe only with dedup on a client message id
OrderingPer-chat order; our model uses a per-chat sequence and per-device FIFO
End-to-end encryptionOnly sender and recipient devices hold the keys; WhatsApp cannot read content
Signal ProtocolX3DH + Double Ratchet (+ sender keys) protocol designed by Open Whisper Systems
X3DHExtended Triple Diffie-Hellman: asynchronous session setup from published prekeys
Double RatchetHash ratchet per message plus DH ratchet per round trip; forward secrecy
Identity keyLong-term Curve25519 key pair per device
PrekeySigned prekey (medium term) and one-time prekeys (single use) published to the server
Sender keyPer-member group chain key + signature key, distributed pairwise
Group messagingMessages to a group; one ciphertext per message with sender keys
Fan-outCopying one message to many recipients; server-side for groups, client-side for devices
Client-fanoutClient encrypts and sends once per destination device
Encrypted mediaAttachment encrypted with random keys before upload
Media keyThe AES-256 and HMAC-SHA256 keys for one attachment, carried in the message
CDN blobOpaque encrypted object served from a blob store or edge cache
PresenceOnline / last-seen state derived from connections
Typing indicatorEphemeral "composing" event; also an anti-automation signal
Multi-devicePhone plus up to four companion devices, each with its own keys
Companion deviceA device linked to the account by the primary phone (web, desktop)
Sender Side BackfillServer-detected device-list mismatch, sender resends to missed devices
Encrypted backupOpt-in E2EE backup with a 64-digit key or a password-protected HSM key
HSMHardware security module; holds backup keys and enforces attempt limits
ChatDWhatsApp's front-end service handling client connections and authentication
Supervision treeOTP hierarchy where supervisors restart failed child processes
Hot code loadingReplacing a running module's code; old and current versions coexist
MnesiaOTP's distributed database; WhatsApp used async_dirty, fragments, islands
pg2 / wandistProcess groups for addressing; WhatsApp's dist-like transport between clusters
Key transparencyAppend-only, auditable public-key directory (WhatsApp AKD, 2023)
Spam detectionFinding bulk or automated accounts, here from behaviour
MetadataWho, when, how often, from where: visible to the server even with E2EE
AbuseBulk, automated or harmful use; banned via registration, messaging and report signals
ScaleUsers, connections and messages per day over time
Messages per day1B (2011), 19B in / 40B out (2014), ~100B (2020)
Data centre migrationMoving WhatsApp services into Facebook data centres after 2014
InferenceA claim we derived; not stated in a WhatsApp or Meta source

References ​

WhatsApp and Meta (primary):

Talks by WhatsApp engineers (primary):

Protocol specifications:

Secondary (labelled where used):

Framework docs used for the Laravel code:

Built by Morteza Negahi