Skip to main content

Chat App: Delivery Deep Dives

Editorial

How is a message shown exactly once?

No network delivers a message exactly once. A reply can always be lost after the other side has acted on the request, so every step of a messenger is retried, and every retry can repeat something that already happened. What a messenger can promise is that each message is delivered at least once and shown exactly once. Three places need care:

  • The send. The server stores the message, and the "stored" reply is lost. The phone sends it again.
  • The delivery. The device stores a batch of messages, and its acknowledgement is lost. The server sends the batch again.
  • The device itself. The app is killed halfway through storing a batch.

Three rules make every repeat harmless.

Rule 1: The Sender Keeps the Message Until the Server Has Stored It

The phone writes every message to a local outbox before sending it, and deletes it from the outbox when the server replies "stored". After any failure (no reply, a dropped connection, a restart) it sends the outbox again, oldest first.

The server makes the repeat harmless. deliver() stores a message for every device of one account in one transaction, and its first statement records the send in accepted. A send that is already there returns at once:

-- store one message for every device of one account: all of them or none
CREATE FUNCTION deliver(p_user bigint, p_devices smallint[], p_envelopes bytea[],
                        p_sender_user bigint, p_sender_device smallint, p_message_id uuid)
RETURNS text LANGUAGE plpgsql AS $$
DECLARE
  expected smallint[];
BEGIN
  -- a retry of a send this shard has already stored
  INSERT INTO accepted (user_id, sender_user, sender_device, message_id)
  VALUES (p_user, p_sender_user, p_sender_device, p_message_id)
  ON CONFLICT DO NOTHING;
  IF NOT FOUND THEN
    RETURN 'already stored';
  END IF;

  -- the sender must have encrypted for exactly the devices the account has now
  SELECT array_agg(device_id ORDER BY device_id) INTO expected
  FROM devices
  WHERE user_id = p_user AND (user_id, device_id) <> (p_sender_user, p_sender_device);
  IF expected IS DISTINCT FROM (SELECT array_agg(d ORDER BY d) FROM unnest(p_devices) AS d) THEN
    RAISE EXCEPTION 'device list changed' USING DETAIL = array_to_string(expected, ',');
  END IF;

  -- each device's counter row stays locked until commit, so a device's rows commit in the order of their seq
  WITH next AS (
    UPDATE devices SET next_seq = next_seq + 1
    WHERE user_id = p_user AND device_id = ANY (p_devices)
    RETURNING device_id, next_seq - 1 AS seq
  )
  INSERT INTO mailbox (user_id, device_id, seq, message_id, sender_user, sender_device, envelope)
  SELECT p_user, n.device_id, n.seq, p_message_id, p_sender_user, p_sender_device, e.envelope
  FROM next n JOIN unnest(p_devices, p_envelopes) AS e(device_id, envelope) USING (device_id);
  RETURN 'stored';
END $$;

The key is the message id the phone chose, a random UUID, together with the sending device. A counter would not do: it starts again after a reinstall, and a new message would then carry the id of an old one and be answered as a repeat, never to be stored.

Rule 2: The Device Stores Before It Acknowledges

The device reads a batch from its mailbox, in order, and stores it in one local transaction: the messages, the new state of its encryption sessions, and the position it has reached. Only after the commit does it acknowledge.

  • If the app dies before the commit, nothing happened. The server still has the batch and sends it again.
  • If it dies after the commit but before the acknowledgement, the server sends the batch again too, and the device skips every envelope at or below the position it stored.

The encryption session belongs in the same transaction because every message key works once. Signal's library refused to decrypt the same message twice (DuplicatedMessage). A device that decrypted a message, moved its session forward and died before storing the text would have lost that message for good: the key to read it is gone.

The device stores, then acknowledges: messages, session state and position in one transaction; then the ack. Bob's phone reads a batch, 8810 to 8812, from its mailbox and stores in one local transaction the messages (3 rows), the session state (the keys it used) and its position, 8812. Then it acknowledges 8812, and the mailbox deletes everything up to 8812. If the app dies before the commit, nothing happened: the server still has the batch and sends it again. If it dies after the commit, the ack never left: the server sends again and the device skips every seq up to 8812. A second copy at a new seq, a send retried after 30 days, is dropped by sender and id before decrypting. A device that acknowledges before storing loses the messages of a batch the app dies in: about 30 of 41 devices in the test.

Rule 3: The Device Drops a Second Copy by Its Id

The server remembers stored sends for 30 days. A phone that retries a send after that, or a server that has lost its accepted row, stores a second copy, with a new position. The device recognizes it by the sender and the message id, and drops it before decrypting it.

The two loops of a device, as the tests run them:

def send_pending(db, send):
    """send(message_id, recipient, payload) returns once the server has stored the message, raises if it fails"""
    pending = db.execute('SELECT message_id, recipient, payload FROM outbox ORDER BY rowid').fetchall()
    for message_id, recipient, payload in pending:
        send(message_id, recipient, payload)            # ✓: stored on the server
        with db:
            db.execute('DELETE FROM outbox WHERE message_id = ?', (message_id,))


def receive(db, batch, decrypt):
    """batch: the envelopes the server sent, in seq order; returns the seq to acknowledge"""
    with db:                                            # one local transaction, session state included
        (done,) = db.execute('SELECT last_seq FROM sync').fetchone()
        for e in batch:
            if e['seq'] <= done:
                continue                                # stored before: the server sent it again
            sender = f"{e['sender_user']}.{e['sender_device']}"
            known = db.execute('SELECT 1 FROM messages WHERE sender = ? AND message_id = ?',
                               (sender, e['message_id'])).fetchone()
            if not known:                               # a resent message carries the same id
                db.execute('INSERT INTO messages VALUES (?, ?, ?)', (sender, e['message_id'], decrypt(db, e)))
            done = e['seq']
        db.execute('UPDATE sync SET last_seq = ?', (done,))
    return done                                         # acknowledge only what is committed

Tested

We ran these loops on 41 devices of 24 people, all sending and receiving at once against PostgreSQL, 2,460 messages in all. About one send in five failed: before it reached the server, between the recipient's and the sender's own mailboxes, or after both (the "stored" reply lost). One acknowledgement in ten was lost, and in about one batch in twenty the app died partway through. Afterwards each device had to hold every message meant for it, once, each sender's messages in the order written. Then we broke the client in three ways, to see whether the test would notice:

ClientWhat happenedDevices whose history was wrong
The code aboveEvery failure repaired by a repeat; the mailboxes ended empty0 of 41
The code above, the server forgetting 30% of the retried sendsAbout 250 second copies reached devices; every one was dropped by its id0 of 41
Acknowledges a batch before storing itThe messages of every batch the app died in were never seen againabout 30 of 41
No id checkAbout 250 second copies reached decryption and were refused by the session0, with an error for every copy
Resends its outbox in any orderMessages written while offline arrived shuffledabout 40 of 41

The exact counts change from run to run, because the threads interleave differently; the zeros do not.

Where do undelivered messages wait?

A mailbox needs four operations: append an envelope at the end, read everything after a position, delete everything up to a position, and drop what has waited 30 days. And it keeps one promise: an envelope that was confirmed survives the loss of a machine.

Each Device Numbers Its Own Envelopes

One shared sequence for all mailboxes looks simpler, and it loses messages. A sequence hands out its number when a row is written, but the row becomes visible only when its transaction commits. A row that commits late appears behind the reader:

  1. Sender A's transaction takes number 1 and has not committed yet.
  2. Sender B's takes number 2 and commits.
  3. The device reads after 0, finds 2, stores it and acknowledges 2.
  4. A commits. Number 1 is now in the mailbox, behind the device's position. It is never read.

We ran exactly this on PostgreSQL: the device read only "second", and "first" stayed in the table, unread.

One shared sequence loses a message: a number is handed out at insert; the row appears only at commit. One shared sequence: 1, A inserts and gets number 1, not committed; 2, B inserts, gets number 2 and commits; 3, the device reads after 0, finds 2 and acknowledges 2; 4, A commits, and 1 is now behind the device's position: never read. We ran it on PostgreSQL: 1 stayed unread. A counter per device: 1, A's deliver() takes 1 and locks the device's counter row; 2, B waits for the lock; 3, the device reads after 0 and finds nothing yet; 4, A commits, B takes 2 and commits, and the device reads 1, then 2, in order. A device's rows commit in number order.

In deliver() the number comes from the device's own row in devices, and the UPDATE keeps that row locked until the transaction commits. A second sender to the same device waits, so a device's envelopes commit in the order of their numbers, and a reader can never pass one. Run the same way, the second sender waited and the device read 1, then 2. Signal's server does the same in Redis: a device's queue is a sorted set where "a message's score is its queue-local message ID", taken from a counter kept with the queue.

Reading and acknowledging are one index range each:

SELECT seq, message_id, sender_user, sender_device, envelope
FROM mailbox
WHERE user_id = 1290001 AND device_id = 2 AND seq > 8790
ORDER BY seq
LIMIT 100;

DELETE FROM mailbox
WHERE user_id = 1290001 AND device_id = 2 AND seq <= 8812;

Redis Alone Loses Messages

A Redis sorted set per device is fast and has the right operations, but Redis copies writes to its replicas asynchronously. Its documentation says it plainly: "acknowledged writes can still be lost during a failover". We ran it with one primary and one replica, and a link between them that stopped carrying data, as a congested or broken network does:

  1. ZADD inbox:bob 1 msg-1, then WAIT 1 1000 returned 1: the replica had it.
  2. The link stalled. ZADD inbox:bob 2 msg-2 returned 1: the primary confirmed it. WAIT 1 300 returned 0: no replica had it.
  3. The primary died, and the replica was promoted.
  4. The inbox held msg-1 only. Three runs, three times the same.
Redis confirmed it; the failover lost it. The primary acknowledged msg-2; its replica never received it. Four steps with a primary and a replica. 1: ZADD msg-1 returns 1 and WAIT 1 returns 1: the replica has it. 2: the link stalls; ZADD msg-2 returns 1, confirmed, and WAIT 1 returns 0. 3: the primary dies with msg-2. 4: failover: the replica is promoted, and the inbox holds msg-1 only.

WAIT tells the writer that a write has not reached a replica; it cannot make it reach one. In Redis's own words, it "does not make Redis a strongly consistent store".

What Durability Costs

On one laptop, with the 32 connections of a busy mailbox server, deliver() stored about 8,400 envelopes a second when every commit waited for the drive to flush, and about 110,000 when the drive's own cache absorbed the flush. Waiting for the flush cut the throughput more than tenfold.

Waiting for the drive is the cost: deliver() calls a second on one laptop, by what the commit waits for. When the drive's cache absorbs the flush, which is not safe on power loss: about 55,000. Flushed on the primary, one machine: about 4,200. Plus a standby that has received it, remote_write, this design: about 2,000. Plus the standby flushing it too, on: about 1,400. Two envelopes a call, 32 connections, PostgreSQL 17; both servers on one laptop's drive, so the standby rows are a floor: on two machines the standby's flush is on its own drive.

Most of that work is wasted. Most envelopes are deleted seconds after they are written: WhatsApp's 2014 talk listed "I/O bottleneck writing to mailboxes" and "Most messages picked up very quickly", and its fix was a "write-back cache with variable sync delay". Signal's server, which is open source, keeps each device's queue in a Redis cluster and moves it to DynamoDB only once its oldest message has waited longer than a set delay (one minute in its sample configuration), with rows that expire after 30 days. Kafka's designers made the same call for logs: an fsync on every write "can reduce performance by two to three orders of magnitude", so Kafka writes to the operating system and relies on its replicas.

A server can confirm an envelope at four points, and each survives different failures:

Confirmed whenSurvivesCan lose a confirmed message whenExample
On disk on two machinesany one machine, drive or zone; both machines crashingboth drives are lostPostgreSQL, synchronous_commit = on with a synchronous standby
On disk on one machine, received by a secondany one machine, drive or zonethe primary's drive is lost and the standby's operating system crashes before it has written the data to diskPostgreSQL, synchronous_commit = remote_write with a synchronous standby
In memory on two machines, written to disk laterany one machineboth machines crash in the same momentKafka with acks=all and min.insync.replicas=2
In memory on one machine, copied latera clean restartthe machine dies just after confirmingRedis with asynchronous replicas

This design confirms an envelope when it is on two machines in two different zones: the primary mailbox server, which has flushed it, and a synchronous standby, which has received it (remote_write). PostgreSQL's documentation describes the standby side exactly: the commit waits until "the standby has received the commit record and written it out to its own operating system, but not for the data to be flushed to disk". Losing any one server, drive or zone loses nothing.

We measured it on the laptop, both servers sharing one drive: about 4,200 deliver() calls a second on the primary alone, about 2,000 with a remote_write standby, and about 1,400 with an on standby that flushes too. Every row the primary had confirmed was on the standby. On two machines the standby's flush does not compete with the primary's for one drive, so these are the worst case.

A memory tier in front, as WhatsApp and Signal run, is the next step when the drives become the bottleneck: with an average wait of a minute, about 120 million envelopes wait at any moment, tens of gigabytes across a cluster. It keeps the promise only if a second machine has each envelope before the tick, which is exactly what Redis's asynchronous replicas do not give.

How Much Waits, and for How Long

By Little's law, the envelopes waiting are the deliveries per second times the average wait. At our 2 million deliveries a second on average, a one-minute average wait means 120 million envelopes (34 GB), an hour 7.2 billion (2.0 TB), a day 172 billion (49 TB). The store is sized by the phones that stay away, not by the ones that are online.

Two jobs keep it bounded. Once a day, rows older than 30 days go, in batches:

DELETE FROM mailbox  WHERE stored_at   < now() - interval '30 days';
DELETE FROM accepted WHERE accepted_at < now() - interval '30 days';

And a linked device that has not connected for 30 days is unlinked, with its mailbox: WhatsApp disconnects linked devices "after 30 days of inactivity".

Split by Person

Mailboxes are split across servers by user_id, so all of a person's devices live on one server and one transaction stores a message for all of them. A 1:1 message touches two servers: the recipient's, and the sender's for their own other devices. A person who receives a flood of messages has a long queue, but appending to the end of one queue is as cheap as appending anywhere.

In what order do messages arrive?

Order is promised in three ways, and not promised in a fourth:

  1. One sender's messages appear in the order they were written, on every device that shows them.
  2. A group's messages appear in one order for all of its members.
  3. A device reads its mailbox in order.
  4. When two people write at the same moment in a 1:1 chat, each may see their own message first. Both orders are true; nothing in the world decided which came first.

A Mailbox Is Ordered by Its Numbers

A device reads its mailbox by seq, the number its own counter gave each envelope when it was stored, and the gateway pushes envelopes in that order. Promise 3 is the mailbox's job alone.

A Sender's Order Is Kept by the Sender

The mailbox keeps the order in which sends arrive. The order in which they arrive is the phone's: it sends its outbox oldest first and the next message only after the previous one was stored, and a connection handles one device's frames in order. A retry repeats the oldest unconfirmed message first. When we broke that rule and let the client resend its outbox in any order, the messages written while offline arrived shuffled on about 40 of 41 devices.

A Group's Order Is the Log's

All of a group's messages go through one Kafka partition, so the log puts them in one order, and the fan-out writes them into every member's mailboxes in that order. The ✓ for a group message carries its position in the log, and every device, the sender's included, sorts the group's messages by it. The sender's own message may move up or down when the log has put another member's message before it.

Order comes from numbers, not clocks: a mailbox reads by its own seq; a group by its log position. 1:1, written at once: Alice's phone shows her "lunch?" before Bob's "dinner?", and Bob's phone shows his first. Each shows its own first; both orders are true: nothing decided which came first. One sender's own order is kept. A group: the log's order. Positions 40, 41 and 42 in the log; Alice's, Carol's and Dan's phones all show Carol's "hi" (40), Alice's "hey" (41) and Dan's "yo" (42) in that order. Every device sorts by position, the sender's too. Clocks only label: 12 messages in one millisecond, in a set sorted by timestamp, came back as part 1, 10, 11, 12, 2, 3 … of 12.

Clocks Do Not Order Messages

Every envelope carries the time it was sent, and the app shows it. It does not decide order. Phones' clocks are set by their owners and their networks; servers' clocks drift apart by milliseconds; and many messages share a millisecond. A Redis sorted set scored by timestamp shows the last problem plainly: twelve messages stored in one millisecond came back as part 1, 10, 11, 12, 2, 3 … of 12, because equal scores are ordered by their bytes.

The Encryption Does Not Need Order

The Double Ratchet tolerates any order. WhatsApp's encryption paper says messages "can arrive delayed, out of order, or can be lost entirely without any problems"; Signal's library decrypted three messages in the order 3, 1, 2. Order is the mailbox's and the sender's job, not the encryption's.

What happens when connections drop?

On a phone, connections drop all the time: a lift, a tunnel, a switch from Wi-Fi to mobile data, the operating system closing a background app. The design treats a dropped connection as routine.

Noticing That a Connection Is Dead

A connection that dies without a goodbye can look alive to the other side for a long time. Both ends send heartbeats. The WebSocket protocol has Ping and Pong frames for this: "A Ping frame may serve either as a keepalive or as a means to verify that the remote endpoint is still responsive". A gateway that hears nothing for a few intervals closes the connection and removes its registry entry. A device that hears nothing reconnects.

The Race When a Phone Moves

A phone that switches networks reconnects, often through another gateway, before the first one has noticed. The new gateway writes the registry entry; then the old one closes the dead connection and removes the entry, and with a plain DEL it removes the new one. The phone is connected but no message reaches it until it reconnects again.

A late DEL unregisters a connected phone: remove an entry only if it still names the connection that closed. The registry entry conn:bob:1. 1: Bob's phone connects to gw-1; the entry is gw-1 · c-1. 2: it switches networks and reconnects via gw-2; the entry is gw-2 · c-2. 3: only now gw-1 notices that c-1 is dead and removes the entry. The phone is connected to gw-2 the whole time; only the order of the two events decides. With DEL conn:bob:1 there is no entry: the phone is connected, but no message can find it until it reconnects again; we ran it: no entry left. With the compare-and-delete script for c-1, the entry names c-2, not c-1, so it stays; when c-2 closes, the same script removes it; we ran it: gw-2, c-2 kept.

The fix is a compare-and-delete: remove an entry only if it still names the connection that closed, in one atomic step:

-- KEYS[1] = conn:{user_id}:{device_id}, ARGV[1] = the id of the connection that closed
if redis.call('HGET', KEYS[1], 'connection') == ARGV[1] then
  return redis.call('DEL', KEYS[1])
end
return 0

We ran the race both ways: after DEL the entry was gone; after the script it still named the new gateway and connection, and when that connection closed, the same script removed it.

A device has one live connection. When it registers on a new gateway while an old entry still names another gateway, the message service tells the old gateway to close that connection, so it stops pushing into a dead socket.

Reconnect Storms

When a gateway dies, its million devices reconnect at once, to the other gateways. When a network fault cuts many gateways off, all of their devices do.

Every login costs the fleet work: the TLS handshake, authentication, the registry entry, a mailbox read. A fleet that loses many connections at once has to take them all back, and WhatsApp learned what a mass reconnect can do on 22 February 2014. A back-end router glitch made the servers of its cluster disconnect from each other and reconnect at once, which left the cluster in "a novel unstable state" and ended in a "full stop & restart", its first in years. We simulated a million devices reconnecting to a fleet that admits 100,000 logins a second; a login over that is refused and the device waits by its backoff rule. Admitted perfectly evenly, they would all be back in 10 seconds.

RuleBack afterAttempts per device
Wait 1 s, then 2, 4, 8, … seconds, at most 30453 s9.4
Wait a random time between 0 and the same 1, 2, 4, … 30 s36 s3.2

Without randomness the devices that failed together retry together: every wave hits the fleet in the same instant, a few are admitted and the rest wait for the next wave, twice as long. AWS's architecture blog put it in one line: "The solution isn't to remove backoff. It's to add jitter."

Jitter brings them back 12× sooner: a million devices reconnect to a fleet that admits 100,000 logins a second. The share of devices back over time. Waiting 1, 2, 4 … 30 seconds, the refused retry together, in waves: 2% after 2 s, 24% after 32 s, 37% after 92 s, and all back at 453 s, 9.4 attempts each. Waiting a random time up to the same: 10% a second at first, 91% after 11 s, all back at 36 s, 3.2 attempts each. Each attempt takes 0–200 ms to arrive; perfectly even admission would take 10 s.

The rule in code:

def next_wait(attempt, base=1.0, cap=30.0):
    return random.uniform(0, min(cap, base * 2 ** attempt))

Push Notifications Wake Devices, They Do Not Deliver

A phone in a pocket has no open connection most of the time; the operating system closes it to save battery. The message service then sends a push notification through Apple's or Google's service, and the phone connects and reads its mailbox.

The notification carries no message, for three reasons. Apple describes its service as "best-effort", and it "may reorder notifications"; for a device that is offline it stores "only one notification per bundle ID", so of ten notifications nine are gone. Google may hold a normal-priority message for a sleeping Android phone until it wakes; only a high-priority one may "wake a sleeping device". And the text is end-to-end encrypted. So the notification says only "you have mail", and the mailbox does the delivering.