08-05
Chapter 08 · Messages in a world that loses them
Idempotent retries
00Recall
One card from 08-04 on what one bit can and cannot tell apart, one from 08-02 on how a set network duplicates, and one from 06-03 on how big a step should be. That last one decides what today's pass is worth.
08-04-a from Alternating bit
Why is one bit enough for stop-and-wait over a channel that keeps order, but not over one that reorders?
Show answer
When both the data and the ack channels keep order, only copies of the current and the previous message, and acks for them, can arrive, and the bit tells those two apart. With reordering, a copy of any older message or ack can arrive, and a bit cannot tell it from a new one.
08-02-a from Loss and duplication for free
In a spec whose network is a set, how do you allow duplicate delivery?
Show answer
Leave the message in the set when it is received. Nothing then forbids receiving it again.
06-03-b from Atomicity is a choice
How big should each step of a concurrency model be?
Show answer
As big as the implementation's real indivisible operation: one atomic hardware instruction (such as compare-and-swap), one single-row SQL update or a transaction run at SERIALIZABLE isolation, one thread-safe call. Bigger hides interleavings; smaller reports races the system rules out.
Skip recall Recall is never required.
01Commit
A checkout pays for orders through a payment API. Requests and replies travel over set networks, so either can arrive twice or never. A client that has no reply sends the request again. Every request carries an idempotency key, and the server charges at most once per key: a request with a key it has seen gets the old reply and no new charge.
In specs/NaiveRetry.tla the client makes the key inside its retry loop:
Key(o, t) is defined as tuple of o, t end tupleso try t for order o gets the key << o, t >>. The requirement is NoDoubleCharge: no order is charged twice. Each order may be tried twice (MaxTries = 2).
Commit a
TLC checks NoDoubleCharge on NaiveRetry. What will it report?
- A violation: one order, two tries, two keys, two charges.
- A violation, but only when the network duplicates a request.
- No violation: the server never charges the same key twice.
Answer A violation: one order, two tries, two keys, two charges.
- If you picked B
- No duplicate is needed. The client's own retry is the second request. A network copy and a retry look the same to the server; here they do not even have the same key.
- If you picked C
- True, and beside the point. The server deduplicates keys, and the client gave the retry a new key. To the server, the retry is a different payment.
specs/PaymentRetry.tla is the same spec with Key(o, t) == o: one key per order, reused on every try.
Commit b
In PaymentRetry, the client retries order o1. Its new request record is exactly the old one. What does the retry step change?
- requests now holds two copies of the record.
- Nothing at all, so TLC treats the retry as a stuttering step.
- Only tries: the record is already in requests.
Answer Only tries: the record is already in requests.
- If you picked A
- requests is a set. Adding an element it already holds leaves it as it was (08-03).
- If you picked B
- tries[o1] goes up by one, so the step changes a variable and is not stuttering. Only the network stays the same.
02Lab
There is no lab for this lesson. Run both specs:
./tla check chapters/08-messages/specs/NaiveRetry.cfg
./tla check chapters/08-messages/specs/PaymentRetry.cfg08-messages/specs/NaiveRetry08-messages/specs/NaiveRetry NaiveRetry.cfg (Orders={o1, o2}, MaxTries=2)
parse ok
model check: invariant NoDoubleCharge violated; trace has 5 states (4 steps); 23 distinct states
expected outcome met: violation NoDoubleCharge
trace (changed variables only; ./tla trace --full shows all):
1 Init tries = (o1 :> 0 @@ o2 :> 0), requests = {}, replies = {}, charged = (o1 :> 0 @@ o2 :> 0), keysSeen = {}, paid = {}
2 Request tries: (o1 :> 0 @@ o2 :> 0) -> (o1 :> 1 @@ o2 :> 0), requests: {} -> {[order |-> o1, key |-> <<o1, 1>>]}
3 Request tries: (o1 :> 1 @@ o2 :> 0) -> (o1 :> 2 @@ o2 :> 0), requests: {[order |-> o1, key |-> <<o1, 1>>]} -> {[order |-> o1, key |-> <<o1, 1>>], [order |-> o1, key |-> <<o1, 2>>]}
4 Charge replies: {} -> {<<o1, 1>>}, charged: (o1 :> 0 @@ o2 :> 0) -> (o1 :> 1 @@ o2 :> 0), keysSeen: {} -> {<<o1, 1>>}
5 Charge replies: {<<o1, 1>>} -> {<<o1, 1>>, <<o1, 2>>}, charged: (o1 :> 1 @@ o2 :> 0) -> (o1 :> 2 @@ o2 :> 0), keysSeen: {<<o1, 1>>} -> {<<o1, 1>>, <<o1, 2>>}Reveal for commit a
NoDoubleCharge is violated in a trace of 5 states. One order is requested twice, once per try, each request with its own key, and the server charges each key once. The deduplication worked exactly as written, and the customer pays twice.
Reveal for commit b
Only tries changes. The retry sends the record [order |-> o1, key |-> o1] again, and requests already holds it. With one key per order, a retry and a network duplicate are the same thing, and the server's rule, one charge per key, covers both. PaymentRetry passes, with 49 distinct states.
03Reason
If you picked "no violation", you checked the server's rule and found it sound. It is sound. The bug is in what the key identifies. An operation is idempotent when doing it twice has the same effect as doing it once. "Charge for key k" is idempotent. "Charge for this attempt" is not, because every attempt is new. The key has to name the thing that must happen once: the payment, not the try.
On a network, the client can never know whether its request arrived. No reply means one of two things. Either the request was lost or is still in flight, and nothing was charged; or the reply was lost or is still in flight, and the charge happened. The client cannot tell which. Its only safe move is to ask again in a way the server can recognise as the same question.
Write something before openingthe client could avoid retrying altogether. Why is that not a fix?
Then a lost request means an order never paid for, and the client cannot tell that case from a lost reply. Every retry policy picks a side: retry and risk a duplicate, or don't and risk a loss. "At least once" plus an idempotent receiver is how you get the effect of "once" from a network that offers neither. Notice the wording: the effect is once. The messages are not.
In specs/TaskBoard.tla a worker asks the board for a task by sending a claim, and claims, like everything on a set network, can arrive twice. "Give me a task" is not idempotent: a board that answers every claim with a fresh task gives one worker two tasks, and the worker only ever works on one. The other task is assigned and abandoned. The fix has to make the claim idempotent.
Write something before openingwhat does the board already know that would let a second copy of the same claim change nothing? And who answers the copy?
The board records who holds which task, so it can tell a worker that already holds one from a worker that holds none. A copy of a claim from the first kind needs no new task, and no new grant either: the grant for the first copy is still in the network, and the network may hand it over as often as it likes. The Core exercise has you write that rule as a guard.
With the rule in place, TLC finds no violation of OneHolder or NoOrphan in 52 distinct states.
Write something before openingin PaymentRetry the server charges and records the key in one step. What does that hide?
A real server does two things: call the card network, then write the key to its database. If it crashes between them, the key is not recorded, and the retry charges again. The spec made those two things one atomic step (chapter 06), so TLC could not see that window. To find it, split Charge into two actions and add a crash; you would then need a transaction, or to store the key before charging. A spec only checks the atomicity you wrote down.
The TaskBoard model is small on purpose: each worker takes one task and never asks again. A worker that finishes and claims a second task would send a claim equal to its first one, and the set would merge them. Then the claim needs an ID too, chosen once per claim and reused on every retry of it. That is the payment key again, under another name.
Three questions decide whether a retry is safe. Does every request carry a key that names the operation, not the attempt? Does the server remember keys for at least as long as a retry can arrive? Is "check the key, do the work, record the key" atomic in the real code? The spec assumes the first, and TLC checked what follows from it. The other two are on you, and so is making sure the real client matches the spec.
The client does not have to be a person or a browser. An agent that calls a tool, times out and calls it again is this client exactly: its retry is a second request, and the tool cannot tell it from a network copy. If the tool charges, books, sends or deletes, each operation the agent means once needs its own key, chosen before the first call and reused on every retry. A key chosen per call is NaiveRetry with a model in the loop.
04In your editor
The specs are chapters/08-messages/specs/NaiveRetry.tla, PaymentRetry.tla and TaskBoard.tla. Check this lesson's exercises with:
./tla check 08-05The idempotent version prints:
08-messages/specs/PaymentRetry08-messages/specs/PaymentRetry PaymentRetry.cfg (Orders={o1, o2}, MaxTries=2)
parse ok
model check: no violation found in 49 distinct states (211 generated, depth 9)
expected outcome met: pass
coverage: all 4 actions fired
witness PaidAfterRetry reached (trace of 5 states)
witness AllPaid reached (trace of 7 states)05Practice
Warm-up. Give each payment one key for all its tries.
Core. Make the TaskBoard's claims idempotent, so that a claim that arrives twice cannot hand one worker two tasks.
08-05-ex1Warm-up5 min
08-05-ex1 · One key per payment
Tier: warm-up. Time: about 5 minutes.
The lesson's NaiveRetry, renamed: the client makes a new idempotency key for every try, and an order is charged twice.
- Run
./tla check 08-05-ex1and read the trace. - Fill gap g1: the key for order
oon trytis the same on every try, and different for different orders. - Run the check until it passes with both witnesses,
PaidAfterRetryandAllPaid.
One wrong answer gives every order the same key. Predict which claim catches it before you try it: NoDoubleCharge, PaidMeansCharged, or a witness?
Hints: HINTS.md, under "08-05-ex1 hint 1" to "hint 3". The solution is in solutions/chapters/08-messages/exercises/05-ex1-one-key-per-payment/; open it after you have a passing answer of your own.
If TLC finds no violation but an action never fires or a witness is not reached, ./tla prints "goal not met" and exits with code 1.
Done when: ./tla check 08-05-ex1 prints "goal met: pass".
./tla check 08-05-ex1
Repo chapters/08-messages/exercises/05-ex1-one-key-per-payment/
Hints
Hint 1
The server charges once per key. Read the trace: what key does each request for the order carry?
Hint 2
The key must not depend on the try t. It must depend on the order o, or two orders could share one key.
Hint 3 (nearly the answer)
Make Key(o, t) equal to the order itself. Keys, TypeOK and the actions follow from it.
08-05-ex2Core8 min
08-05-ex2 · One task per claim
Tier: core. Time: about 8 minutes.
The TaskBoard over a network. A worker's claim can arrive at the board twice, and the board answers every claim with a free task. One worker ends up assigned two tasks and works on one of them.
- Run
./tla check 08-05-ex2and read the trace. Which requirement fails,OneHolderorNoOrphan, and what does the board believe at the end? - Change gap g1 so that a claim arriving a second time changes nothing at the board. What does the board already know about
wthat it could check? A repeated claim needs no answer of its own: the grant is already in the network. - Run the check until it passes with the witness
AllBusy.
A different fix takes the claim out of claims when the board assigns a task. Try it. That fix changes the network, not the board: why does TLC still find the bug?
Hints: HINTS.md, under "08-05-ex2 hint 1" to "hint 3". The solution is in solutions/chapters/08-messages/exercises/05-ex2-one-task-per-claim/; open it after you have a passing answer of your own.
If TLC finds no violation but an action never fires or a witness is not reached, ./tla prints "goal not met" and exits with code 1.
Done when: ./tla check 08-05-ex2 prints "goal met: pass".
./tla check 08-05-ex2
Repo chapters/08-messages/exercises/05-ex2-one-task-per-claim/
Hints
Hint 1
Read the trace: which worker does the board assign two tasks to, and which one does that worker start?
Hint 2
The board knows who has a task: owner. The guard must say that no task is already owned by w.
Hint 3 (nearly the answer)
Replace TRUE with a universally quantified condition over Tasks: for every task u, the owner of u is not w. Taking the claim out of claims fails because the worker claims again before its grant arrives.
06Explain it
Open NOTES.md and answer the three prompts under 08-05, about the Core exercise.
What I built, and why it is correct:
Which assumption, if false, breaks it:
What TLC did not check here:Compare your answers with "08-05 check your explanation" in HINTS.md.
After you writeCheck your explanation
A good answer: "The board assigns a task to a worker only if the worker owns none, so a claim that arrives twice cannot give one worker two tasks; the grant already in the network answers the repeat. It assumes the board's owner record and its assignment happen in one step, and that each worker takes one task in this model. TLC checked two workers and three tasks with every claim and grant duplicable; it did not check workers that finish and claim again, which would need request IDs."
A weak answer: "I added a check so workers can't get two tasks." It does not explain why the duplicate claim arrived, what idempotence means here, or which behaviors the model left out.
07Your system
Milestone 3: the network. Your system's messages, and what the network may do to them.
Keep this work in my-system/, which Git ignores, and in a private repository. Strip names and identifiers before you share any of it, and do not paste proprietary designs or customer data into third-party AI tools without your organisation's approval.
- List the messages your system sends between components: requests, replies, events, acknowledgements. For each, write who sends it and who acts on it.
- For each channel, choose a set, a bag or a queue, and write one sentence on why. A queue needs a named mechanism that keeps order (one connection, one partition). If you cannot name one, use a set.
- Write one action that sends and one that receives, with the receiver leaving the message in the network. If you take it out, write down the mechanism that stops this channel from ever delivering twice.
- Write one invariant that must hold however often and in whatever order messages arrive, and check it. Then remove your deduplication on purpose and confirm that TLC catches it.
- If an agent or an automation calls one of your APIs, list its retries as a channel too, and say which key, if any, makes a retry harmless.
Tick milestone 3 in my-system/MILESTONES.md when the check passes with a witness that needs a duplicate or a reordering.
Done?