Practical technical guides / Agent-era architecture

An Agent Can Act on State Another Saga Will Compensate: Pending Flags and Version Checks at Commit

An agent that reads stock reserved by an in-flight saga can reorder on a value the saga later undoes. Expose pending state and check versions at commit.

By Sandeep Belgavi · Published 2026-11-30

An agent reading mid-saga state
Original explanatory diagram; synthetic values where shown.

An agent that reads stock reserved by an in-flight saga can reorder on a value the saga later undoes. Expose pending state and check versions at commit.

The reader nobody designed for

A saga gives up isolation in exchange for availability. Each step commits locally, and a later failure is repaired by compensation rather than by rollback. The general consequences are well documented. The Azure Architecture Center's saga pattern page lists lost updates, dirty reads and fuzzy reads. It also lists countermeasures: semantic locks, commutative updates, a pessimistic ordering of steps, re-reading values before updating them, and version files. This site's own saga articles cover those countermeasures with order-checkout examples.

This guide is about a reader those discussions rarely picture: an agent. An agent reads the system's state through a tool, reasons for a while, and then commits an action that has its own business effect. If what it read was the intermediate state of another saga, the action can rest on a value that never becomes true. Two things make this worse with agents than with ordinary services. Agents read broadly, because the whole point is to look at the situation and decide. And agent steps take minutes, not milliseconds, whether the agent is the reader or a step inside the saga itself.

The running example is Belgavi's Book Store. An order saga reserves copies of a book, takes payment, and either ships the copies or, when payment fails, releases the reservation. Separately, a reorder agent watches availability and places supplier purchase orders when stock runs low. The companion example saga_intermediate_reads models the timeline and is the source of every number below.

Worked example: a purchase order for copies that were never sold

The book has 3 copies on hand. At minute 10 the order saga reserves 2 of them for Jenya's order. Payment review takes until minute 40, at which point the payment fails and the saga compensates by releasing the reservation. The reorder agent reads availability at minute 20, thinks for 5 minutes, and orders 20 copies from the supplier when availability is at or below 1.

With a raw read, the stock tool returns on-hand minus reserved, so the agent sees 1 copy available. It commits a purchase order for 20 copies at minute 25. At minute 40 the saga compensates and availability returns to 3. The purchase order is real, it costs money, and it rests on a value that was undone. Had the saga completed instead, availability would have ended at 1 and the same order would have been correct. The agent cannot tell these two worlds apart from a raw number.

Read modeSaga outcomeDecisionReadFinalDecided on an undone value
RawCompensatesReorder at minute 2513Yes
RawCompletesReorder at minute 2511No
Pending flagCompensatesNo reorder at minute 4533No
Pending flagCompletesReorder at minute 4511No
Version checkCompensatesReorder at minute 2513Yes
Version check, 25-minute stepCompensatesNo reorder at minute 7033No

The version-check rows deserve attention. A version check at commit compares the row version the agent read with the version at commit time, and rejects the commit if they differ. In the default timeline the agent commits at minute 25, while the reservation is still pending, so the version has not moved and the check passes. The check protects against a value that changed during the agent's step. It does not protect against a value that was never final. Only when the agent's step is slow enough to straddle the resolution (25 minutes, committing at minute 45) does the check reject the commit and force a re-read, which then sees 3 copies.

The window grows with step duration

Two durations matter, and they affect different anomalies.

The first is how long the saga holds intermediate state, from the reservation to the resolution. If every saga step is a fast service call, that window is milliseconds and a broad reader rarely lands in it. When a step inside the saga waits on an agent, such as a payment review, a fraud assessment or a customer conversation, the window becomes minutes. In the model, sweeping the agent's read time across minutes 0 to 59 with an instant agent step, a 1-minute saga window puts 1 read minute on an undone value, a 10-minute window puts 10, and a 30-minute window puts 30. Exposure is proportional to the window, and an agent step inside the saga is what makes the window long.

The second is how long the agent itself takes between reading and committing. The longer the step, the more likely the world changes underneath it. With the 30-minute saga window, an agent that commits instantly never commits a value that changed after it read it. With a 5-minute step, 10 of the 60 read minutes commit a changed value. With a 20-minute step, 30 of them do. That anomaly is the one a version check catches. A dirty read of pending state is a different anomaly and needs a different fix.

What stays deterministic

The agent decides whether to reorder and how many copies. Everything about what it is allowed to believe should stay in deterministic code:

  • The stock read tool decides what availability means. It returns committed and pending reservations separately, with the saga that holds each one, instead of one subtracted number.
  • A deterministic policy, not the prompt, decides what the agent does when relevant state is pending: defer, wait for resolution, or treat pending as sold for this decision class.
  • The commit path checks the row version the agent read and rejects a stale commit. The agent's plan carries the version it relied on, so the rejection names the cause.
  • The purchase-order service applies its own idempotency and limits regardless of how the decision was made.
def read_stock(isbn):
    row = stock.get(isbn)
    return {
        "isbn": isbn,
        "on_hand": row.on_hand,
        "committed_reserved": row.committed_reserved,
        "pending_reserved": [{"saga": r.saga_id, "qty": r.qty, "since": r.since} for r in row.pending],
        "version": row.version,
    }

def commit_reorder(plan):
    row = stock.get(plan["isbn"])
    if row.version != plan["read_version"]:
        raise StaleRead(f"stock version {row.version}, plan read {plan['read_version']}")
    if row.pending and plan["policy"] != "pending_counts_as_sold":
        raise PendingState("reservations still pending; defer until they resolve")
    return purchase_orders.create(plan["isbn"], plan["qty"], idempotency_key=plan["key"])

The pending flag is a semantic lock, the first countermeasure on the Azure list, exposed to the reader instead of being used only by other sagas. The version check is the re-read countermeasure, enforced at the commit boundary instead of trusted to the caller.

Migration steps for an existing saga

  1. List every agent tool that reads state written by a saga: stock, account balances, order status, refund status. For each one, decide whether a pending value can change a decision the agent makes.
  2. Make pending state visible in those tools. Most sagas already track it, either in an orchestrator's state table or as a status column such as RESERVED or REFUND_PENDING. Return it rather than folding it into one number.
  3. Put the deferral policy in code, keyed by decision class. A reorder can wait for resolution. A reply to a customer can say "reserved, not yet confirmed".
  4. Add a version or timestamp to every read tool's result and require the agent's commit to carry it back. Reject mismatches with a structured error that the agent loop handles by re-reading.
  5. Measure the window. Log the time each saga spends between its first compensable step and its resolution, and the time between an agent's read and its commit. These two numbers tell you how often the anomalies can occur.
  6. Replay recorded saga timelines through the agent's tools in tests, and assert on the decisions, not on the transcript.

Failure modes

  • A pending flag that no policy reads. The tool returns it, but the prompt is left to interpret it, and the model sometimes treats pending as available. The fix is a code path that refuses the commit, not a sentence in the instructions.
  • Deferring forever. A saga stuck in its pending state blocks every dependent decision. Give deferral a deadline and an escalation path.
  • Version checks on the wrong row. The agent read the stock row but commits through a purchase-order table, and the check compares the purchase-order version. The version must belong to the data the decision depended on.
  • Retry loops on rejection. Each rejected commit triggers a new model call. Cap re-reads, as the example does with one, and surface the conflict after that.
  • Compensation that changes meaning. A compensated reservation may not restore the exact prior state, for example when another order took the copies in between. Re-reading after compensation is still required.

When an agent is unnecessary

A reorder rule of the form "order 20 when availability is at or below 1, counting only committed reservations" needs no model at all. It is a query and a threshold, and it can run in the same transaction as the stock update. Use an agent when the decision really needs judgement: choosing a supplier, weighing a promotion that will raise demand, or reading a publisher's notice about a reprint. Even then, the threshold check and the pending-state policy stay in code, and the agent is asked only the question that code cannot answer.

Verification

Run the companion example's tests. They assert each row of the table above, the proportional growth of exposure with the saga window (1, 10 and 30 read minutes), the growth of changed-before-commit reads with step duration (0, 10 and 30), and that a version check does not catch a dirty read that commits inside the window. In a real system, replay a recorded saga timeline in a staging environment, run the agent at chosen points inside the window, and check that no purchase order is created while a relevant reservation is pending. The interactive lab lets you move the read time, the step duration and the saga window and see which decisions survive.

Interactive experiment

Saga intermediate state: what an agent reads and what it commits. Synthetic browser-local fixtures, adjustable inputs, decision traces and JSON export.

Primary references and authorship

Sources checked 2026-11-30. Original explanation and synthetic examples by Sandeep Belgavi. Companion code: Sandeep-BA/agent-decision-lab/examples/python/saga_intermediate_reads. Views are my own and do not represent any employer, past or present.