Review the prerequisites
Suitable for: Cross-system task recovery and approval need to be designed.
- Idempotency
- Repeated requests for the same business operation do not produce duplicate business effects. The guarantee's scope depends on the server implementation and its validity period.
- Operation identity
- A stable identifier representing the same business intent, which is different from the identifier for each network attempt.
- Checkpoint
- Computational state saved by the caller. It does not automatically establish what has happened in the external service.
- Unknown outcome
- The caller lacks a reliable receipt and can assert neither success nor that the action was never executed.
How does the mechanism work?
- 1Caller
Saves a prepared intent with stable business key K and parameter digest H.
- 2Provider
Receives K/H and atomically commits the business effect and queryable receipt R.
- 3Network
The response is lost. The caller knows only that a timeout occurred; the outcome stays unknown.
- 4Recovering worker
Looks up or retries using the same K. Identical parameters return R; conflicting parameters are rejected.
- 5Caller
Persists R before marking the outcome confirmed; verifies that the provider has only one effect.
Safe retries depend on provider deduplication/lookup, retention periods, and current authorization. If neither capability exists, pause for human verification. A local checkpoint cannot supply a remote guarantee.
Step-by-step explanation
- Persist the intent
Save the stable operation identity and parameters before initiating the action.
- Commit at the provider
The provider executes and deduplicates the operation according to its own contract.
- Reconcile at the caller
If the response is lost, query the outcome or retry using the same operation identity.
- Update task status
Confirm the outcome after obtaining a verifiable receipt. If it cannot be reconciled, retain the unknown state.
Design · Explain the trade-offs
Choose recovery guarantees based on the remote service capabilities
Objectives of this level: State the guarantee scope, deduplication retention period, verification path, and conditions for escalation to a human.
Visual guide · Unknown is a knowledge state
A provider may commit before the caller confirms. The two-store lab simulates receipt loss; it does not establish arbitrary remote-service guarantees. Select the figure to open it at full size.
Inventory provider guarantees
A stable idempotency identity permits retries only within that service's contract. Business-ID queries allow reconciliation. A service with neither requires acceptance of unknown outcomes and duplicate risk. A local state machine cannot establish end-to-end exactly-once for every provider.
Define identity scope and lifetime
Visual guide · A retry keeps the same intent
These outcomes depend on the provider’s deduplication scope and retention. A new lease, call ID or connection does not create a new business intent. Select the figure to open it at full size.
Include the appropriate tenant and business scope. Use an argument digest to detect changed intent. Deduplication retention must cover allowed retries and recovery: three days of approval waiting with one day of provider retention leaves a gap. Define status queries, rejection, or manual verification after expiry in advance.
Treat recovery as a current decision
Recheck permissions, approved content, tool versions, and resource state. Earlier approval does not authorize changed content, and old permissions may no longer apply. Account for durable ledgers, reconciliation requests, conflicts, and manual work. Choose mechanisms according to the loss and reversibility of side effects.
Run experiments and observe counterexamples
Two local SQLite files simulate independent commits and response loss. No real remote service, process termination, or network failure is involved; this does not establish end-to-end exactly-once execution.
Python 3.10+ · Runs by default using only the standard library · Runs on your computer
- Observe the differences between the caller's prepared and the server's submitted
- Get the original receipt along the same operation identity
- Use the same identity to change content and verify conflicts
python3 idempotency_recovery.pyView the entry-point script
"""Two local SQLite files model independent caller/provider commits.
Not a real remote service, production queue or end-to-end exactly-once proof.
"""
import json
import sqlite3
import tempfile
from pathlib import Path
def provider(path, operation, payload):
with sqlite3.connect(path) as db:
db.execute("CREATE TABLE IF NOT EXISTS effects (operation TEXT PRIMARY KEY, payload TEXT NOT NULL, receipt TEXT NOT NULL)")
# Serializes the read/check/write in this local demonstration.
db.execute("BEGIN IMMEDIATE")
existing = db.execute("SELECT payload,receipt FROM effects WHERE operation=?", (operation,)).fetchone()
if existing:
if existing[0] != payload:
raise ValueError("same operation with different payload")
return existing[1]
receipt = "receipt:" + operation
db.execute("INSERT INTO effects VALUES(?,?,?)", (operation, payload, receipt))
return receipt
def demo():
with tempfile.TemporaryDirectory() as folder:
remote, local = Path(folder) / "provider.db", Path(folder) / "caller.db"
with sqlite3.connect(local) as db:
db.execute("CREATE TABLE intents(operation TEXT PRIMARY KEY, payload TEXT, status TEXT, receipt TEXT)")
db.execute("INSERT INTO intents VALUES('publish-1','report-v1','prepared',NULL)")
first = provider(remote, "publish-1", "report-v1")
# Simulated response loss: provider committed, caller did not get receipt.
with sqlite3.connect(local) as db:
before = db.execute("SELECT status FROM intents").fetchone()[0]
second = provider(remote, "publish-1", "report-v1")
with sqlite3.connect(local) as db:
db.execute("UPDATE intents SET status='confirmed', receipt=?", (second,))
with sqlite3.connect(remote) as db:
effects = db.execute("SELECT COUNT(*) FROM effects").fetchone()[0]
assert before == "prepared" and first == second and effects == 1
return dict(caller_before_recovery=before, same_receipt=first == second,
provider_effects=effects, caller_after_recovery="confirmed")
if __name__ == "__main__":
print(json.dumps(demo(), sort_keys=True))
Expected output when running locally
{"caller_after_recovery": "confirmed", "caller_before_recovery": "prepared", "provider_effects": 1, "same_receipt": true}- There is only one business effect for the server
- Consent diagram retry receipt consistent
- Remote capabilities and deduplication deadlines need to be verified separately
Continue to do advanced research experiments
After the process really exits, how can it continue?
From the idempotent counterexample of two databases, continue to verify the lease, checkpoint and independent server receipt. Unzip the reliability experiment v3 and execute it in a separate directory.
Read full text and fault analysis → · Download experiment package ↓
python3 cli.py submit --db crash.sqlite
python3 cli.py run --db crash.sqlite --lease-seconds 2 --fault after_collect
python3 cli.py inspect --db crash.sqlite
# 首次运行预期退出码 75;等待至少 2 秒后分别执行
python3 cli.py run --db crash.sqlite
python3 evaluate.py --db crash.sqliteKeep evidence and check item by item
- First inspect shows running, collect checkpoint saved.
- After the lease expires, succeeded, generation=2, collect is only submitted once.
- Press README and run after_effect to check that there is only one receipt in the independent publisher database.
Fixed collect → draft → verify → publish flow; verifying local persistence protocol with real process exit does not prove that any remote service executes exactly once.
code example
Read-only query timeout
Writes with side effects become queries without side effects
Do we still need idempotency keys?
It is generally not necessary to prevent query results from being duplicated, but deadlines, backoffs, and call budgets are still used to avoid amplifying the load. The query may read different versions. When checking payment, it must be judged based on the same business number, rather than treating the new query results as proof of failure of the original request. Read-only and easy to retry does not mean consistency is not important.
Whether it is safe to retry depends on the operational semantics, and the timeout itself does not describe the business results.
Acceptance task for this level
Write separate recovery plans for report publishing and non-queryable email services to clarify what they can guarantee.
Reading this browser’s record…
Hide the answer and check your understanding
Why can't this lab prove that every third-party API executes an operation only once?
Expand reference derivation
The lab's provider explicitly implements local transactional deduplication. Real APIs differ in semantics, validity periods, concurrency behavior, and external side effects. Verify each contract separately.
Further explanations and practice
When encountering unfamiliar principles, first read the implementation, continuous questioning and migration cases, and then independently explain the premise and boundaries. Answers and notes are saved to the original account record.
All linked explanations and exercises (5 )
- Idempotency and compensation when outcomes are unknown · answer independently
- Checkpoints, replay, and external side-effect boundaries · answer independently
- Lease takeover and fencing stale workers · answer independently
- One state machine for retries, deadlines, cancellation, and budgets · answer independently
- Approval snapshots, durable waiting, and one logical resumption · answer independently
Sources and verification scope
The principles are based on public information; the numbers, cases and tasks are the teaching design of this website. Offline experiments verify the range noted on this page, and the learning effect still needs to be judged through independent tasks and feedback.