An agent action across stock and payment needs holds, not undo calls. Idempotent try, a tombstone for an early cancel and an expiry check stop overselling.
An agent action that spans two services
At Belgavi's Book Store, a help-desk agent can place a replacement order when a customer reports a damaged book. That one action touches two services owned by different teams: the stock service, which must set aside a copy, and the payment service, which must take payment for any price difference. Neither service can see the other's database, and neither will join a distributed transaction.
The first version did the obvious thing. The agent's tool called the stock service to decrement stock, then called the payment service to charge. When the charge failed, the tool called the stock service again to add the copy back. Within a week the team had three kinds of incident: a copy that was never put back because the compensation call timed out, a customer charged twice because the agent retried a tool call whose reply had been lost, and stock that went negative because a copy was released and sold while the original order was still being processed.
Try-Confirm-Cancel (TCC) is a protocol for this situation. It replaces "do, then undo" with "reserve, then decide", and it is mostly about what each participant must remember.
Try, confirm, cancel
Each participant exposes three operations, all keyed by a transaction id chosen by the coordinator:
- Try checks the business rules and places a hold: one copy is set aside, or an amount is held against the account. Nothing is visible as final. The hold has an expiry.
- Confirm turns the hold into the final effect. It must only succeed on a live hold.
- Cancel releases the hold.
The coordinator (here, the agent's tool runtime) calls Try on every participant. If all succeed, it calls Confirm on all; if any fails or times out, it calls Cancel on all. Pat Helland's paper on life beyond distributed transactions describes the underlying idea: entities agree through tentative operations and later confirmation or cancellation, instead of through a shared lock.
The happy path is easy. The protocol earns its keep in four less pleasant cases, and each needs a rule on the participant side.
Rule one: every operation is idempotent per transaction id
Agents retry. Networks drop replies. The coordinator will sometimes send Try twice for the same transaction, and Confirm or Cancel more than once. A participant that treats a second Try as a new request places a second hold. In the companion example, a retried Try for a one-copy order leaves the naive stock service holding two copies; the robust one recognises the transaction id and answers with the existing hold.
Store one record per transaction id with a state (TRIED, CONFIRMED, CANCELLED, EXPIRED), and make every operation a state transition that is safe to repeat:
def try_(self, now, tx, qty, ttl):
self.expire(now)
r = self.tx.get(tx)
if r:
if r['state'] == 'TOMBSTONE':
return False # cancel already seen: refuse the late try
return r['state'] == 'TRIED' # duplicate try: same answer, no new hold
if self.available < qty:
return False
self.available -= qty
self.tx[tx] = {'state': 'TRIED', 'qty': qty, 'expires': now + ttl}
return TrueRule two: a cancel can arrive before its try
Suppose the coordinator sends Try to the stock service, the request is delayed, and the coordinator times out waiting. Correctly, it cancels everywhere. The cancel reaches the stock service first; there is no hold yet, so a naive participant ignores it. Then the delayed Try arrives and places a hold that nobody will ever confirm or cancel. This is sometimes called a hanging hold, and in the example it leaves one copy set aside after the coordinator has finished with the transaction.
The fix is a tombstone. When Cancel arrives for an unknown transaction, record it as cancelled-before-try. A later Try for that id is refused. The cancel itself returns success, because from the coordinator's point of view the transaction is cancelled either way. This is the rule most first implementations miss, because it requires remembering something about a transaction that, locally, never started.
Rule three: confirm must check that the hold is still alive
Holds expire so that a crashed coordinator does not lock stock forever. That creates the third case. In the example, Jenya's replacement order is held at second 0 with a 60-second expiry, then waits 90 seconds for a supervisor to approve the price difference. At second 60 the hold lapses and the copy returns to stock. At second 70 Geetha's order takes the last three copies and confirms. At second 90 the approval arrives and the coordinator confirms Jenya's order.
A naive participant confirms anyway, and stock goes to minus one: the shop has sold a copy it does not have. The robust participant refuses Confirm on an expired hold on both services, and the coordinator now has a real decision to make: retry Try, offer a back-order, or tell the customer. That is the honest outcome. The expiry was a promise to release the stock, and a confirm after expiry cannot silently take it back.
| Scenario | Naive participant | Robust participant |
|---|---|---|
| Happy path | 1 copy sold, 30 charged | Same |
| Payment refused, then cancel | Stock and funds restored | Same |
| Cancel arrives before try | 1 copy held after the coordinator finished | Late try refused, nothing held |
| Retried try | 2 copies held for a 1-copy order | 1 copy held |
| Confirm after the hold expired | Oversold by 1 | Confirm refused on both services |
Choosing the expiry
The expiry is a business number, not a technical constant. Too short, and slow approvals (a person in the loop, an agent waiting for a model) lose their holds and customers see failures after being told yes. Too long, and abandoned transactions keep stock out of sale. Two practical rules:
- Set the expiry from the slowest legitimate path, including human approval, plus margin, and alert when confirms arrive within the last tenth of it.
- If an agent step can take unbounded time (waiting for a person), do not hold during it. Ask first, then run Try and Confirm back to back.
The coordinator should also record its own decision durably before sending Confirm or Cancel, so that after a crash it can resume and repeat the same decision. Because every participant operation is idempotent, repeating is safe.
Where an agent fits
An agent should never call Confirm and Cancel directly as separate tools chosen by the model. Give it one tool, such as place_replacement_order, whose implementation is the coordinator. The model decides whether to place the order; the protocol decides how. Two details matter for agents in particular:
- The transaction id must come from the tool runtime, derived from the case and the step (for example
CASE-3107:replacement:1), not from the model. If the model regenerates its plan and calls the tool again, the same id makes the call a duplicate rather than a second order. - The tool's reply to the model should state the final outcome, including refusals after expiry, so the agent tells the customer the truth.
Failure modes
- Compensation instead of cancellation. Decrement-then-increment looks like TCC but has no hold; between the two calls the effect is visible and can be acted on. Holds keep tentative work invisible to everyone else.
- Tombstones that expire too early. A tombstone must outlive the longest delay a Try can have in flight. Keep it at least as long as the hold expiry plus maximum retry time.
- Participant without expiry. A hold with no expiry turns a coordinator crash into permanently unavailable stock.
- Coordinator retries with a new id. If the retry path generates a fresh transaction id, idempotency is lost and every rule above is bypassed.
- Confirm that does more than finalise. If Confirm can fail for business reasons (price changed), those checks belong in Try.
Tradeoffs
TCC asks a lot of participants: three endpoints, a state table, tombstones, expiry handling. Sagas with compensation are simpler when intermediate states may safely be visible and effects can be reversed (a draft email, a reversible label). TCC fits when the intermediate state must not be acted on by others: stock that could be sold, money that could be spent, capacity that could be given away. Two-phase commit gives stronger guarantees but needs every participant to join one transaction manager, which services owned by different teams rarely do.
Verification
The companion example replays the five scenarios as scripts against both participants and checks final stock, funds, oversell and holds left open after the coordinator finished. To test a real participant, write the same scripts as integration tests: send Cancel then Try for a new id and assert the Try is refused; send Try twice and assert one hold; set a short expiry, let it lapse, sell the stock and assert Confirm is refused. Then watch three numbers in production: holds expiring unconfirmed, confirms refused for expiry, and tries refused by tombstones. The last should be rare but not zero; zero usually means the rule is not running.
Running the companion code
cd examples/python/try_confirm_cancel_holds
python example.py
python -m unittest -v test_example.pytcc.py holds one participant with the three rules switchable, and example.py prints the naive and robust results side by side, with the robust participant's log for each scenario.