Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 3 of 5 · Worked example · 25 min · revision 1

Ordering, receipts and retries

Work through one conversation step by step: why timestamps misorder messages, a sequencer per conversation, client retries with idempotency keys, device cursors that catch gaps and duplicates, and delivered and read receipts kept as high-water marks.

Contentsand lesson path

What you will learn

  • Guarantee per-conversation ordering, delivery receipts and at-least-once delivery with client-side deduplication.

Prerequisites: Messaging & Event Streaming

01. The problem

In lesson 2's design, gateways pass messages to a chat service that stores them and routes copies through the registry. RFC 6455 promises nothing beyond frames, so this lesson builds the guarantees users notice, for one conversation:

  1. Every device shows the conversation's messages in the same order.
  2. An acknowledged message survives a server failure, because it is stored on several machines first (lesson 1).
  3. When a phone retries a send, the message still appears once.
  4. The ticks are honest: sent means the server stored it, delivered means a recipient's device has it, and read means the recipient opened the conversation.

The constraints: phones lose connections mid-send, servers crash, clocks disagree, and the network can delay, drop or repeat messages. One script, chat_order_sim.py, simulates each step with fixed inputs and a fixed random seed, so its output is the same on every run. Save it now (it needs only Python 3.12); each step below explains one part of its output.

Python · chat_order_sim.py
"""Ordering, retries and receipts in one conversation, simulated (Python 3.12)."""
import random

print("1. Two servers stamp messages with their own clocks")
SKEW_MS = {"s1": 0, "s2": -45}  # s2's clock runs 45 ms behind real time
SENT = [  # (real time in ms, server that handled it, sender, text)
    (1000, "s1", "ana", "Are we still on for six?"),
    (1020, "s2", "ben", "Yes, see you there"),  # typed after reading ana's message
]
for ts, who, text in sorted((t + SKEW_MS[s], w, x) for t, s, w, x in SENT):
    print(f"   by timestamp  {ts:>4} ms  {who}: {text}")
for seq, (_, _, who, text) in enumerate(SENT, start=1):
    print(f"   by sequence   seq {seq}     {who}: {text}")


class Conversation:
    """The single owner of one conversation: numbers and stores its messages."""

    def __init__(self, dedupe: bool = True):
        self.log: list[tuple[int, str]] = []  # (sequence, text), stored durably
        self.seen: dict[str, int] = {}  # idempotency key -> sequence it got
        self.dedupe = dedupe

    def append(self, key: str, text: str) -> tuple[int, str]:
        if self.dedupe and key in self.seen:
            return self.seen[key], "duplicate, same seq returned"
        seq = len(self.log) + 1  # next number comes from stored state
        self.log.append((seq, text))
        self.seen[key] = seq
        return seq, "stored"


print("\n2. The ack is lost and the client sends again")
for label, keys in [("same key", ["k-31", "k-31"]), ("new key", ["k-31", "k-32"])]:
    conv = Conversation()
    conv.append("k-1", "hi")
    conv.append("k-2", "hello")
    for attempt, key in enumerate(keys, start=1):
        seq, result = conv.append(key, "running late")
        print(f"   {label}, attempt {attempt}: key {key} -> seq {seq}, {result}")
    print(f"   {label}: log is {conv.log}")

print("\n3. 1,000 sends over a link that loses 10% of requests and 10% of acks")
for dedupe in (True, False):
    rng = random.Random(42)  # same losses in both runs
    conv, attempts = Conversation(dedupe), 0
    for n in range(1000):
        while True:
            attempts += 1
            if rng.random() < 0.10:  # request lost: the server never saw it
                continue
            conv.append(f"k-{n}", f"msg {n}")
            if rng.random() >= 0.10:  # ack arrived: stop retrying
                break
    label = "with idempotency keys" if dedupe else "without deduplication"
    print(f"   {label}: {attempts:,} attempts, {len(conv.log):,} messages stored")


class Device:
    """One recipient device: keeps a cursor, the highest seq with no gap before it."""

    def __init__(self, cursor: int):
        self.cursor = cursor
        self.held: set[int] = set()  # received, but waiting for an earlier seq

    def receive(self, seq: int) -> str:
        if seq <= self.cursor or seq in self.held:
            return "duplicate, ignored"
        self.held.add(seq)
        while self.cursor + 1 in self.held:
            self.cursor += 1
            self.held.remove(self.cursor)
        if self.held:
            return f"hold {sorted(self.held)}, fetch from seq {self.cursor + 1}"
        return "shown in order"


print("\n4. A device that has seq 1-2 gets four deliveries")
phone = Device(cursor=2)
for seq in (3, 5, 4, 5):
    result = phone.receive(seq)
    print(f"   seq {seq}: {result:<30} -> delivered up to {phone.cursor}")

print("\n5. Read marks from two devices arrive out of order")
reports = [("phone", 6), ("tablet", 4)]  # the tablet was offline, its report is late
last_write = max_mark = 0
for device, mark in reports:
    last_write = mark
    max_mark = max(max_mark, mark)
    print(f"   {device} says read up to {mark}")
print(f"   last write wins stores {last_write}; keeping the maximum stores {max_mark}")
Terminal
python3.12 chat_order_sim.py

02. Step 1: try timestamps first

The obvious approach is to stamp each message when a server receives it and sort by the stamp. It is a fair start: with one server per conversation, its clock is the only one that matters. Client clocks are worse, since users and phone settings can put them anywhere. The trouble starts when two servers handle one conversation. Part 1 gives server s2 a clock 45 ms behind s1. Ana's question goes through s1; Ben reads it and replies 20 ms later through s2.

Expected output, part 1
1. Two servers stamp messages with their own clocks
   by timestamp   975 ms  ben: Yes, see you there
   by timestamp  1000 ms  ana: Are we still on for six?
   by sequence   seq 1     ana: Are we still on for six?
   by sequence   seq 2     ben: Yes, see you there

Sorted by timestamp, the reply comes before the question. Nothing failed: clocks on separate machines do not agree exactly, and synchronising them narrows the error without removing it. If the skew is smaller than the gap between two messages, timestamps look right, so the bug shows only in busy conversations. Lamport's 1978 paper gives the deeper reason: without a shared clock, happened before orders only some pairs of events; a total order needs a rule all machines follow.

03. Step 2: one sequencer per conversation

The fix is to give every conversation a single owner that numbers its messages 1, 2, 3 and so on, with no gaps. All writes for a conversation go to its owner, for example by hashing the conversation ID onto a ring of chat servers, as in the consistent hashing lesson. The owner takes the next number, stores the message under it, and only then acknowledges the sender with that number.

Why does this work? One writer means one sequence, so every device that sorts by sequence shows the same order. The numbers are dense, so a device that holds 41 and receives 43 knows that 42 exists and is missing. And a reply always gets a higher number than the message it answers, because the replier could only see that message after the owner had numbered it. The order is the order in which the owner received messages, not the order in which people pressed send; two messages sent at the same instant get an arbitrary order, but every device shows the same one.

Conversation takes the next number from what is stored (len(self.log) + 1), not from a separate counter. That matters when the owner restarts or moves after a failure: the new owner must continue from the stored history, and the old owner must be stopped from handing out numbers, a problem called fencing (see distributed systems fundamentals). The costs: every write to a conversation passes through one machine, which caps the write rate of one very busy conversation, and there is no order across conversations. Where those matter, Snowflake IDs (lesson 4) avoid the single owner but give up dense numbering, and since each ID carries its generator's clock, close messages from different servers are ordered only as well as clocks agree (step 1).

04. Step 3: retries with an idempotency key

A phone sends a message and the acknowledgement never arrives. Was the request lost, or the ack? The phone cannot tell, so the only safe move is to send again, which makes delivery at-least-once: the server may see the same message twice. The cure is an idempotency key (resilience lesson). The client creates a unique ID when the user presses send, keeps it with the message in a local outbox until the server acknowledges it, and sends the same ID on every attempt. The owner remembers which key got which number and answers a repeat with the original number instead of storing a second copy.

Expected output, part 2
2. The ack is lost and the client sends again
   same key, attempt 1: key k-31 -> seq 3, stored
   same key, attempt 2: key k-31 -> seq 3, duplicate, same seq returned
   same key: log is [(1, 'hi'), (2, 'hello'), (3, 'running late')]
   new key, attempt 1: key k-31 -> seq 3, stored
   new key, attempt 2: key k-32 -> seq 4, stored
   new key: log is [(1, 'hi'), (2, 'hello'), (3, 'running late'), (4, 'running late')]

With the same key, attempt 2 gets seq 3 back and the log keeps one copy. With a new key per attempt, a common bug, the server stores the message twice. Part 3 sends 1,000 messages over a link that loses one request in ten and one ack in ten, with the same losses in both runs:

Expected output, part 3
3. 1,000 sends over a link that loses 10% of requests and 10% of acks
   with idempotency keys: 1,223 attempts, 1,000 messages stored
   without deduplication: 1,223 attempts, 1,107 messages stored

Both runs needed 1,223 attempts; without deduplication the server stored 107 extra copies, with keys none. This is not exactly-once delivery. It holds only while the server still remembers the key, and only if the server records the key and the message in one atomic write, so that a crash cannot keep one without the other; Amazon's Builders' Library describes the same rule for its APIs. The delivery guarantees lesson applies it between services.

05. Step 4: gaps and duplicates on the device

The server pushes each new message, with its number, to every connected device of every member. Copies can still arrive twice or out of order, for example when a push and a catch-up read overlap. So each device keeps a cursor: the highest number up to which it holds every message. A number at or below the cursor is a duplicate. A number above the cursor plus one reveals a gap, so the device holds the message and fetches the missing range from storage.

Expected output, part 4
4. A device that has seq 1-2 gets four deliveries
   seq 3: shown in order                 -> delivered up to 3
   seq 5: hold [5], fetch from seq 4     -> delivered up to 3
   seq 4: shown in order                 -> delivered up to 5
   seq 5: duplicate, ignored             -> delivered up to 5

Seq 5 arrives before 4, so the device holds it and asks for messages from 4. When 4 arrives, both show and the cursor jumps to 5; the second 5 is dropped. A device that set its cursor to the highest number seen would skip 4 for good after a reconnect.

06. Step 5: delivered and read receipts

Only the recipient's device knows that a message arrived, so the delivered tick comes from the device: after storing messages it sends delivered up to N, its cursor. A write on the server proves only that the server has it, and a push service that accepts a notification delivers it on a best-effort basis. The read tick works the same way: when the user opens the conversation, the device sends read up to N. Both receipts are high-water marks, the highest point reached so far, so one small event covers every message up to N. That is how the receipt traffic of lesson 1 shrinks.

A high-water mark only moves forward, and the server must keep it so, because reports can arrive late, for example from a tablet that was offline:

Expected output, part 5
5. Read marks from two devices arrive out of order
   phone says read up to 6
   tablet says read up to 4
   last write wins stores 4; keeping the maximum stores 6

Storing the last report moved the mark backwards; keeping the maximum is right whatever the arrival order. In a group, the server keeps one mark per member and per kind of receipt. Message s has been delivered to member m when that member's delivered mark is at least s, so the sender can see delivered to 9 of 11 without one receipt per message per member.

07. Check your understanding

Practice check · 3 questions

Order, retries and receipts

Predict what happens in each case, using the mechanisms of this lesson.

Q1. A conversation's owner keeps its next sequence number only in memory. It restarts and begins again at 1, although the store already holds messages 1 to 80 and does not check for an existing (conversation, seq). Devices drop any message whose number they already have. What do users see?
Q2. The server remembers idempotency keys for 24 hours. A phone sends a message in a tunnel, the ack is lost, and the phone stays offline for three days. When it reconnects, its outbox resends the message with the original key. What happens?
Q3. In a group, the server keeps each member's delivered mark: Ben 12, Cleo 9, Dan 12, Eve 15. Ana's latest message has seq 12. To whom has it been delivered?
Practice only: not graded, not saved, not evidence.

08. Apply it

Extend the two-gateway demo of lesson 2 into the message path of this skill's practice prototype:

  1. Add a Conversation owner to route() that numbers each message and acks the sender with the number.
  2. Give the client an outbox that keeps each message and key until the ack, resending after a timeout.
  3. Make each recipient keep a cursor and send delivered up to N.
  4. Drop the first ack on purpose; show the conversation holds one copy.

In the design doc, state how long keys are kept and what a sender sees in a 500-member group.

09. Review prompt

Without looking back, answer in your own words:

  1. Why can two servers' timestamps put a reply before its question, and why does one sequencer per conversation fix it?
  2. Why must the next sequence number come from stored state?
  3. Walk through a lost ack: what the client does, what the server stores, what devices show.
  4. What do delivered up to N and read up to N mean, and why does the server keep the maximum?

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check