Unit 8 of 12 · about 5 hours · implement

Compensation for multi-step effects, and leases with fencing

A recovered worker may overlap with its replacement, and a failed workflow may already have changed the world. Compensation controls the business aftermath; fencing controls stale authority.

You'll be able to

  • Persist a compensation decision and recover incomplete compensations with stable operation identities.
  • Reject stale-worker effects using monotonically increasing fencing tokens enforced at the recipient.
  • Distinguish compensated, compensation-pending and non-compensable outcomes.

Covers

Compensation and saga semantics for multi-step effectsLeases, fencing and stale-worker exclusion
1

Read

In this order, only the parts listed

0 of 2 done

  1. Sagas: semantic repair and its limitsSagas

    Garcia-Molina and Salem, SIGMOD 1987: Section 1, printed p. 250; Sections 4 Backward Recovery and 5 Forward Recovery, pp. 253 to 254; Section 6 Other Errors, pp. 254 to 255; Section 9 Designing Sagas, pp. 257 to 258

    Skip implementation internals and parallel sagas. The paper's local transaction recovery does not atomically cover a remote effect.

  2. Kleppmann: the recipient rejects stale epochsHow to Do Distributed Locking (fencing tokens)

    What are you using that lock for?; Protecting a resource with a lock; Making the lock safe with fencing

    Stop before Using time to solve consensus. The 2016 Redlock debate is not this unit's implementation task.

2

Focus on

  • Compensation is a new authorized effect with its own intent, key, result and retry budget. In a sequential dependency chain, compensate committed steps in reverse order after resolving ambiguous steps.
  • Sagas p. 250 explicitly says compensation need not restore the earlier database state. Concurrent work may have observed or changed it; cancellation must preserve present business invariants.
  • A lease can expire while a worker pauses. The recipient must atomically compare the fencing token, update its highest accepted epoch and apply the protected mutation. A local expiry check leaves a race.
  • Fencing and idempotency are independent. A current worker can repeat an operation; a stale worker can invent a new key. Enforce both at the effect boundary, including compensation.
Common mistakes · 3
  • A random lock value is unique but not ordered. It cannot identify an older authority epoch.
  • Calling a failed release a completed cancellation. Keep unresolved compensation with an owner and escalation path.
  • Attaching fencing tokens only to logs. An external API that never checks them is not fenced.
3

Try it yourself

Closed-book, before checking anything

In the separately persisted fake recipient, accept a protected write with fencing token 34, then reject a distinct delayed operation carrying 33. Reopen the database and confirm that rejection still holds. For a reservation followed by a definitively rejected next step, persist the compensation decision, fail the first release without an effect, restart and retry the same release key. Keep compensation pending until a correlated release receipt arrives; redelivery must not release twice. Do not attempt to undo a simulated notification by deleting its history.
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 1.The recipient has accepted 34. A different operation arrives with 33. Does a fresh idempotency key help?Answer

    No. It is stale authority and must be rejected, even though it is not a duplicate operation.

  2. 2.Does fencing instantly revoke 33 before the recipient has seen a newer epoch?Answer

    Not by the highest-seen-token rule alone. It rejects backward epochs after observing a higher one; stronger admission guarantees need additional enforcement.

  3. 3.A release receipt is lost. May recovery generate another release identity?Answer

    No. Reconcile or replay the recorded compensation identity under its recipient contract. A new identity can duplicate the release.

  4. 4.Why can compensation require human handling?Answer

    Some actions have no adequate semantic inverse, and compensations themselves can fail. Retain the partial state and escalate rather than claim rollback.

You're done when

A stale distinct operation is refused after restart, repeated compensation has one effect, and compensation failure cannot produce a falsely completed cancellation.

Only when you can do this without notes.

Leads to

Notes

Resources · 2 for this unit, 12 more in the section
  • How to Do Distributed Locking (fencing tokens)Martin Kleppmann · required

    Read "What are you using that lock for?", "Protecting a resource with a lock" and "Making the lock safe with fencing". The effect recipient must remember the highest token and reject older ones (34 accepted, delayed 33 rejected); a random lock value is not a fencing token. Fencing rejects stale authority, while idempotency rejects repeated operations.

  • SagasHector Garcia-Molina and Kenneth Salem · reference

    Read Section 1 (p. 250: compensation does not necessarily restore the earlier state) and Section 9 Designing Sagas, with Sections 4 and 5 on backward and forward recovery. Some actions cannot be compensated; model failed compensation and manual handling explicitly.

Also in this section

  • Durable Tool-Using WorkflowRoadmap-Final · primary

    Build the reduced core through typed tools, one approval, one simulated irreversible effect, one compensable effect, capability policy, idempotency, durable intent and outcome, bounded execution and replay. Run kill tests around every persistence and effect boundary before adding an agent loop.

  • AI Agents in Depth - Tools and Asynchronous InteractionBojie Li · required

    Read Chapter 4: 4.2 tool design and schema fidelity, 4.3 MCP, 4.5 versus 4.6 (read-only perception tools against execution tools), the "Idempotency and Cancellation Semantics" passage and the observability part of 4.6, and 4.7 human-in-the-loop timeouts. Add 5.1.5 Failure and Error Recovery and 6.2 asynchronous interaction. Translate the advice into explicit state and effect contracts.

  • Model Context Protocol Specification 2026-07-28Model Context Protocol · required

    Read the 2026-07-28 architecture and versioning pages: there is no initialize handshake, every request carries _meta protocol version, client info and capabilities, and server/discover lists versions and capabilities. Then the stdio and Streamable HTTP bindings, tools/list and tools/call (input and output schemas, isError versus JSON-RPC errors), resources and prompts, the tasks extension, and the roots and sampling deprecations. Build one small stdio server and client, record the wire messages, and keep application authorization outside the protocol.

  • Making Retries Safe with Idempotent APIsAmazon Builders' Library · required

    Read "Retrying and the potential for undesirable side effects", "Reducing client complexity with idempotent API design", "Semantic equivalence and support for default retry strategies", "Late arriving requests and the life span of unique client request identifiers" and the parameter-mismatch section. Record the key and the effect atomically, scope keys by caller, and reject a reused key with different parameters.

  • Idempotent RequestsStripe · required

    Read the page as one concrete recipient contract: an Idempotency-Key header, the first result saved and replayed, parameter mismatch rejected, keys pruned after at least 24 hours (API v1), and the different API v2 retry semantics. Encode these cases in your fake effect recipient; do not treat 24 hours as universal.

  • Timeouts, Retries, and Backoff with JitterAmazon Builders' Library · required

    Read "Timeouts", "Retries and backoff" and "Jitter": a timeout leaves the outcome unknown, side-effecting calls are unsafe to retry without idempotency, and retries belong at one layer with a token-bucket budget. Model the unknown outcome as its own workflow state.

  • LangGraph Persistence and InterruptsLangChain · support

    Read persistence (checkpointer versus store; the in-memory saver does not survive a restart), interrupts (interrupt, Command(resume=...), the rules of interrupts, "side effects called before interrupt must be idempotent") and the Functional API determinism and idempotency sections. Resuming restarts the interrupted node from its beginning: reproduce the repeated pre-interrupt action with a SQLite checkpointer across two processes.

  • DBOS Transact Python: Workflows and StepsDBOS · support

    Read the workflow tutorial ("Workflow IDs and Idempotency", "Determinism"), the step tutorial ("Configurable Retries", "Step Timeouts") and the system-database page (SQLite by default). Kill a process mid-workflow and confirm that completed steps do not rerun while the interrupted step does. Choose this or LangGraph as the implementation companion, not both.

  • Temporal: Workflow Replay, Activity Retries and TestingTemporal · reference

    Read Event History and replay, the Python workflow logic requirements, "Make Activities idempotent", the default retry policy (unlimited attempts unless set) and Signals versus Updates. Activities may run more than once, so replay does not make an external effect exactly-once.

  • Writing Effective Tools for AI AgentsAnthropic · support

    Read "Running an evaluation" and "Principles for writing effective tools" through "Prompt-engineering your tool descriptions": a small task-shaped tool surface, unambiguous parameter names, bounded and paginated results, actionable errors. Compare with the OpenAI function-definition best practices and rewrite one tool contract.

  • AI Engineering Handbook - Agent EngineeringHandbook Academy · support

    Study the Part 7 chapters on tool design, MCP and security, human review and long-running agents. Use them to audit user-facing workflow behavior and failure paths after the durable core works.

  • The Hitchhiker's Guide to Agentic AI - Harness and MCPHaggai Roitman · support

    Use v3 sections 18.4 to 18.7 (tool integration, orchestration with the explicit state machine in 18.5.5, state management and checkpoints, error handling), then Chapter 23 for MCP vocabulary and 23.6 for its security model. Its transport lists predate the 2026-07-28 specification and 18.4.5 contradicts Chapter 23, so take protocol facts from the specification.