Architecture and End-to-End Data Flow
Trace the complete end-to-end journey of an encrypted message through Layer 4 balancers, Erlang BEAM edge gateways, distributed session directories, and the deterministic tick state machine.
In 30 seconds: When Alice sends a message to Bob, the packet passes through Layer 4 BGP load balancers straight to an Erlang edge gateway without TLS termination at the proxy. A distributed session registry maps Bob's phone number to his active gateway node, forwarding the encrypted payload directly across the server backbone to Bob's open socket. Every message transitions through a deterministic state machine, ensuring sub-second delivery and zero server storage upon completion.
01The Hook: Alice Sends msg-401
Alice sits in a coffee shop in London. She opens WhatsApp, types "Are you free for coffee?", and taps Send. A tiny clock icon flickers on her screen for a few milliseconds, replaced almost immediately by a crisp, single grey tick. Three thousand miles away in New York, Bob is walking down Fifth Avenue with his phone in his pocket. Within 200 milliseconds, Bob's phone vibrates. A notification appears on his lock screen. On Alice's screen in London, that single grey tick doubles: two grey ticks now sit beside her message.
How did the server cluster know where Bob was among 500 million simultaneously open connections? Why did the proxy layer not decrypt the traffic? What happened inside the operating system to deliver this payload across the Atlantic faster than the blink of a human eye?
In this lesson, we trace the full lifecycle of Alice's message (msg-401) step by step through every layer of the infrastructure.
02The Journey of a Message: Five Critical Hops
To understand how real-time messaging operates at scale, we trace msg-401 across five distinct infrastructure hops:
[ Alice: Client ] --(Hop 1)--> [ L4 Load Balancer ] --(Hop 2)--> [ Gateway Node 42 ]
|
(Hop 3)
v
[ Bob: Client ] <--(Hop 5)-- [ Gateway Node 88 ] <--(Hop 4)-- [ Session Registry ]Hop 1: The Client Socket and Edge Ingress
Alice's phone does not establish a new HTTP connection to send msg-401. Instead, her device already maintains an open, long-lived TLS 1.3 socket to WhatsApp's global edge network.
When Alice presses Send:
- Local SQLite Persistence: Alice's phone immediately writes
msg-401to its local on-device SQLite database with an internal status ofPENDING. Her user interface renders the small clock icon. - Payload Framing: The client application constructs a compact binary packet. The packet contains routing metadata (Sender:
+1-555-0101, Recipient:+1-555-0102, MessageId:msg-401, Timestamp:1714560000) followed by the encrypted message body. The text "Are you free for coffee?" is encrypted using the Signal Protocol on the phone itself. - Socket Flush: The client writes the serialized binary frame into the operating system TCP send buffer.
Hop 2: Layer 4 vs Layer 7 Load Balancing
The TCP packet reaches WhatsApp's Point of Presence (PoP) via BGP Anycast routing. The packet lands on a fleet of Layer 4 load balancers (such as Linux IPVS or Maglev).
In many modern web architectures, engineers place a Layer 7 reverse proxy (like NGINX or Envoy) in front of application backends. Layer 7 proxies terminate TLS, inspect the HTTP headers, decrypt the URL path, and route requests. For WhatsApp, a Layer 7 proxy would introduce severe bottlenecks:
- Cryptographic Memory and CPU Overhead: Terminating 500 million TLS sessions on intermediary proxy tiers consumes massive amounts of RAM and CPU cycles.
- Connection Multiplication: A Layer 7 proxy maintains two separate TCP connections for every single client (Client-to-Proxy and Proxy-to-Backend), doubling the total socket count across the data center.
- Stateful Streaming: Real-time chat sockets are long-lived, stateful pipes, not ephemeral request-response pairs.
WhatsApp uses Layer 4 TCP passthrough. The Layer 4 balancer inspects only IP addresses and TCP port numbers. It performs consistent hashing on the tuple (Source IP, Source Port) and forwards raw TCP packets directly to an Erlang edge gateway node (Node 42 in our example). The TLS handshake is terminated directly by Node 42 inside the BEAM runtime.
Hop 3: The Erlang Edge Gateway and Server ACK
Node 42 receives Alice's packet. Inside Node 42, an Erlang process dedicated to Alice's socket reads the binary frame:
- Header Validation: The process parses the binary header and validates that the sender phone number matches Alice's authenticated session credentials.
- Immediate Server Acknowledgment (The Single Tick): Node 42 immediately dispatches a lightweight ACK packet back over the socket to Alice:
ack_server(msg-401). - UI State Transition: Alice's phone receives this server ACK. Her application updates the local SQLite database from
PENDINGtoSENT_TO_SERVER. The clock icon on her screen instantly changes into a single grey tick.
Alice now has confirmation that the server has accepted responsibility for the message. Even if her phone suddenly loses network coverage or runs out of battery, the message is safe inside the server infrastructure.
Hop 4: The Session Registry Lookup
Node 42 holds Alice's connection, but Node 42 does not have an open socket to Bob (+1-555-0102). Bob could be connected to any of the 500 other gateway nodes in the worldwide cluster, or Bob might be completely offline.
To locate Bob, Node 42 queries the Distributed Session Registry:
- The Session Registry is an ultra-fast, in-memory distributed key-value store (conceptually an in-memory hash ring backed by Mnesia, Redis Cluster, or an internal distributed hash table).
- Node 42 executes a lookup:
lookup_session("+1-555-0102"). - The registry returns Bob's current connection location:
Node 88(IP10.0.4.88, Port5222).
Node 42 opens an internal high-speed Erlang Distributed node-to-node RPC message or cluster socket, forwarding msg-401 directly to Node 88 across the internal backbone.
+-----------------------------------------------------------------------------------+
| Session Registry Routing Record |
+---------------------+-------------------+---------------------+-------------------+
| User ID (Phone) | Gateway Node ID | Connection Socket | Last Ping Time |
+---------------------+-------------------+---------------------+-------------------+
| +1-555-0101 (Alice) | Node-42 | fd: 10423 | 1714560001 |
| +1-555-0102 (Bob) | Node-88 | fd: 28911 | 1714560002 |
+---------------------+-------------------+---------------------+-------------------+Hop 5: Node 88 and Delivery to Bob
Node 88 receives the forwarded payload from Node 42:
- Node 88 identifies the local Erlang actor process managing Bob's live TCP socket.
- The actor pushes the binary frame containing
msg-401down the open socket to Bob's phone. - Bob's Device Processes the Message: Bob's phone receives the packet, writes it to its local SQLite database, and computes the decryption key using its local Signal session ratchet.
- The Delivery Receipt (The Double Grey Tick): Bob's phone immediately sends an acknowledgment back up the socket:
ack_delivery(msg-401). - Back-Propagation: Node 88 routes this delivery ACK back to Node 42. Node 42 pushes the delivery ACK down to Alice's phone.
- Alice's UI Updates: Alice's application updates its local record to
DELIVERED. The single grey tick on Alice's screen turns into a double grey tick.
Later, when Bob unlocks his phone and opens the conversation with Alice, his application dispatches a read receipt (ack_read(msg-401)). This receipt traces the exact same return path, updating Alice's screen to the celebrated double blue ticks.
03The Four-State Lifecycle State Machine
A hallmark of WhatsApp's engineering is that state transitions are strictly monotonic and deterministic. A message moves forward through well-defined states; it can never regress to an earlier state, and every state change is backed by an explicit acknowledgment.
[ PENDING ] ---> [ SENT_TO_SERVER ] ---> [ DELIVERED ] ---> [ READ ]
(Clock Icon) (Single Grey Tick) (Double Grey Tick) (Double Blue Tick)
|
+----(Recipient Offline)----> [ OFFLINE_SPOOLED ]
|
(Wait max 30 days)
|
v
[ EXPIRED_DROPPED ]State 1: PENDING (Clock Icon)
- Location: Resides exclusively on the sender's client device.
- Meaning: The message has been persisted in local storage but has not yet been acknowledged by the server gateway.
- Behavior on Disconnect: If the sender's network disconnects while a message is in
PENDING, the client application keeps the message in its local SQLite queue. As soon as connectivity returns, the phone automatically re-dispatches all pending messages in chronological order.
State 2: SENT_TO_SERVER (Single Grey Tick)
- Location: Sender client and transient server memory.
- Meaning: The server edge gateway has validated the packet, accepted responsibility for delivery, and dispatched a server acknowledgment.
- Invariant: From this point forward, the sender device is no longer responsible for retrying transmission. The server infrastructure owns the delivery obligation.
State 3: DELIVERED (Double Grey Tick)
- Location: Both sender and recipient devices.
- Meaning: The recipient device has received the message, validated its cryptographic integrity, and committed it to local storage.
- Critical Server Action: The instant the server receives the
ack_deliverypacket from Bob, it completely purgesmsg-401from its memory buffers and any transient offline queues. The server's storage footprint for that message drops to zero bytes.
State 4: READ (Double Blue Tick)
- Location: Both devices.
- Meaning: The recipient has brought the specific chat view into the active mobile viewport.
- Privacy Controls: If either Alice or Bob has disabled read receipts in their application settings, the client application suppresses the transmission of
ack_readpackets, preserving double grey ticks indefinitely.
04The Distributed Session Registry: Finding Bob
How does the server locate Bob in constant time O(1) without searching millions of connection records?
Why Not a Centralized Relational Database?
In a naive architecture, an engineer might store user connection mappings in a relational table:
CREATE TABLE user_sessions (
user_id VARCHAR(32) PRIMARY KEY,
gateway_ip VARCHAR(45),
connected_at TIMESTAMP
);At WhatsApp scale, this approach collapses:
- With 500 million concurrent users whose cellular connections flap frequently (driving over 100,000 connection and disconnection events per second), this table would suffer over 200,000 write queries per second alongside 1.2 million read queries per second.
- Relational locking, transaction overhead, and replication lag would introduce unacceptable latency and database contention.
The In-Memory Distributed Hash Ring
Our design employs a distributed, in-memory key-value registry distributed across the cluster:
[ Gateway Node 42 ]
|
| Hash: hash("+1-555-0102") % RingSize
v
[ Session Shard Cluster (Virtual Nodes) ]
+---------------------------------------+
| Key: +1-555-0102 |
| Val: {node: "node-88", socket: 28911} |
+---------------------------------------+- Consistent Hashing by User ID: The user's phone number is hashed using a consistent hashing algorithm (such as MurmurHash3). The hash determines which shard in the session cluster owns Bob's session record.
- Sub-Millisecond In-Memory Reads: When Node 42 queries Bob's location, the request hits an in-memory shard over high-speed intra-datacenter networks, returning the target gateway node in under 2 milliseconds.
- Heartbeat and Lease Expiration: Every connection actor sends an internal heartbeat ping every 60 seconds. If Node 88 crashes or loses network connectivity, Bob's session lease expires automatically after 90 seconds, preventing stale routing.
+-----------------------------------------------------------------------------------+
| Session Registry Performance Profile |
+-------------------------------+---------------------------------------------------+
| Metric | Target Specification |
+-------------------------------+---------------------------------------------------+
| Shard Clustering Strategy | Consistent Hashing with 256 Virtual Nodes |
| Query Latency (Read P99) | < 2.5 milliseconds |
| Update Latency (Write P99) | < 4.0 milliseconds |
| Memory Footprint per Record | 64 bytes (User Phone + Node ID + Timestamp) |
| Total Cluster Memory (500M) | 500M * 64 bytes = ~32 GB RAM (easily sharded) |
+-------------------------------+---------------------------------------------------+05What Happens When Bob Is Offline?
What if Node 42 checks the session registry and discovers that Bob has no active connection? Perhaps his phone is turned off, in airplane mode, or out of cell coverage.
[ Alice: msg-401 ] ---> [ Gateway Node 42 ] ---> [ Session Registry: Bob is OFFLINE ]
|
v
[ Ephemeral Spool Buffer ]
(Encrypted queue, TTL: 30d)
|
v
[ Push Notification Service ]
(APNs for iOS / FCM for Android)
|
v
[ Bob's Phone Wakes Up ]
|
v
[ Establishes TLS Socket ]
|
v
[ Batched Spool Drain & Purge ]Buffering in the Ephemeral Spool
Instead of dropping the message, Node 42 writes msg-401 to the Ephemeral Spool Buffer:
- The spool buffer is organized as an encrypted, append-only commit log partitioned by recipient phone number (implemented using distributed disk-backed engines like RocksDB or partitioned Apache Cassandra).
- Zero Decryption Invariant: The stored payload is the exact same ciphertext byte array generated by Alice. The server cannot inspect its contents.
- Time-to-Live (TTL): The record is tagged with an automated expiration timestamp of 30 days.
The Silent Push Wake-Up
Immediately after writing to the spool, the gateway dispatches a high-priority silent push notification through Apple Push Notification service (APNs) for iOS devices or Firebase Cloud Messaging (FCM) for Android devices:
{
"to": "bob_device_push_token_xyz",
"priority": "high",
"content_available": true,
"data": {
"action": "sync_messages"
}
}Notice what is missing from this push payload: the message text. Sending message content through third-party push notification services would violate end-to-end encryption, exposing private text to operating system vendors. Instead, the push notification acts purely as an alarm clock. It instructs the mobile operating system to wake up WhatsApp in the background.
Reconnect and Batched Drainage
When Bob's phone receives the silent push or when Bob opens the application:
- The client establishes a fresh TLS socket to the nearest edge gateway.
- Upon completing the handshake, the client issues a synchronization request:
sync_offline(last_seen_msg_timestamp). - The gateway streams all pending spooled messages down to Bob in a compact binary batch.
- Bob's phone persists the messages locally and returns a batch delivery acknowledgment:
ack_batch([msg-401, msg-402, ...]). - The spool engine immediately executes a hard delete on all acknowledged records, returning server storage consumption back to zero.
06In the interview
- Why does the gateway delete the offline message as soon as the client acknowledges it? To preserve the zero-storage ephemeral invariant and prevent storage consumption from compounding across millions of users.
- What happens if Bob never acknowledges the spooled message? The message remains in the append-only spool until its automated 30-day TTL expires, at which point an asynchronous cleanup process drops the record as an expired tombstone.
07Check your understanding
Quiz · 4 questions
0 of 4 answered
1. Why does WhatsApp route client TCP traffic through Layer 4 load balancers rather than Layer 7 reverse proxies?
2. What triggers the server to delete an encrypted message permanently from its storage infrastructure?
3. Why do WhatsApp push notifications (APNs / FCM) omit the message text and sender name in their payload?
4. How does the client application handle receiving a READ receipt before an earlier DELIVERED receipt arrives?
What you now know
You have traced the full architectural data flow and component choreography of WhatsApp:
- How Layer 4 load balancers pass raw TCP streams directly to Erlang edge gateways without proxy TLS termination.
- How the in-memory distributed session registry resolves recipient socket locations in constant time O(1).
- The deterministic four-state tick lifecycle: from local client
PENDINGto serverSENT, recipientDELIVERED, and viewportREAD. - How offline messages are spooled in temporary encrypted queues, triggered via zero-knowledge silent push notifications, and permanently purged upon delivery acknowledgment.
In the next lesson, The Hard Problems, we tackle the three most intense distributed scaling challenges in WhatsApp: presence storms, group messaging fan-out to 1,024 members, and the mechanics of the Signal Protocol's Double Ratchet.