Almost none of this is about AI. It is ordinary distributed-systems engineering pointed at a new failure surface, which is the good news: you already know most of it. The trap is assuming the framework has done it for you.
An agent holds state across many tool calls and changes the outside world part-way through. So picture the ordinary case. It is three calls into a five-call run, it has already issued a refund, and the process dies. What should happen on restart?
That question is not new. It is what every payments system, order pipeline and provisioning workflow has dealt with for decades. What is new is that the thing driving the calls is non-deterministic. That removes the one assumption most retry logic quietly depends on: that a repeat of the same operation was requested for the same reason.
So the discipline is recovery rather than restart. Checkpoint after every successful tool call, including the ledger of which idempotency keys have been consumed.
Keep that ledger separate from the conversation transcript. On resume you need to restore commitments, not just context.
Read down a column for one control, or across a row to compare them. The chip on each column is the argument of this lesson: only the counting is new. Select any column for the detail.
Two of the five have no agent in them at all. The other three are ordinary mechanisms pointed at counters that are new.
Two details decide whether a ledger works, and both look fine in testing. The first is where the key comes from. It must be a function of what the agent intended, so that a retry of the same intent produces the same key.
Generate a random UUID inside the retry path and you have built an elaborate no-op. The retry gets a fresh key, the ledger recognises nothing, and the tool runs again.Stripe’s guidance is compatible with this and worth reading precisely. The client generates the key. A V4 UUID is fine. The point is that it is generated once per logical request and reused on every attempt.
The second detail is the write order, and it is the one teams get wrong. Picture a ledger written after the tool call. The agent issues the refund. The process dies before the write. On restart the ledger is clean, so the retry issues a second refund — and nothing in your system knows it happened twice.
So reserve the key as in_flight and checkpoint it before the side effect. Crash there and the retry finds evidence rather than a clean slate: a reserved key, which tells it to go and ask the downstream system what happened instead of firing blind.
Writing the ledger after the call only protects against an in-process retry — the case where the process is still alive, which was never the case that was going to hurt you.
One agent, one refund of ₹1,800, three places the worker can die and three ledger designs. Pick a combination. Only one design survives all three crash points, and it is not the one most codebases have.
The window this design leaves open is precisely the interval that matters. The refund succeeded, the ledger write never landed, and the retry sees a clean ledger and refunds again. Writing the ledger after the side effect protects only against an in-process retry — the case where the process is still alive, which is the case that was never going to hurt you.
This design survives 2 of the 3 crash points. The lesson is a write-ordering one and it is worth being able to say out loud: reserve the key and checkpoint it before the side effect, so that a crash leaves behind evidence that something may have happened. And be honest about where the real guarantee lives — the local ledger is a cache. The idempotency key reaching the downstream system is the actual protection.
import hashlib, json
def key_for(tool, args):
"""Derived from INTENT, not from a UUID minted at call time.
A retry of the same intent must produce the same key."""
blob = json.dumps({"tool": tool, "args": args}, sort_keys=True)
return hashlib.sha256(blob.encode()).hexdigest()[:32]
def call_tool(tool, args, ledger):
k = key_for(tool, args)
prior = ledger.get(k)
if prior == "in_flight":
# A previous attempt died between the call and the write.
# Ask the downstream system what it knows about this key;
# never re-fire blind.
return reconcile(tool, k, ledger)
if prior is not None:
return prior # already executed: replay it
ledger[k] = "in_flight" # reserve BEFORE the side effect
checkpoint(ledger)
# The local ledger is a cache. The real guarantee is that
# idempotency_key reaches the downstream system, which is the
# only place that can refuse a duplicate authoritatively.
result = TOOL_FNS[tool](**args, idempotency_key=k)
ledger[k] = result
checkpoint(ledger)
return resultThis one costs an afternoon the first time. Here is the afternoon, for free.
In LangGraph, when a node containing an interrupt() is resumed, the runtime restarts the entire node from the beginning. It does not resume at the line after the interrupt. The documentation says so explicitly, and it is a reasonable design: the node is a plain function, so there is no continuation to capture.
So everything before the interrupt runs again. Validation re-runs. Records created before the interrupt are created a second time.
And if you put two interrupts in one node to collect two approvals, resuming after the second one re-runs the first. That is how a system with a human gate ends up discarding the approval it just collected.
Nothing about the circuit breaker is AI. Closed, open, half-open, a trial call to decide whether to close again — Fowler wrote it up in 2014 and Nygard popularised it before that.
What is agent-specific is what you count. Cap total turns, wall-clock and spend. Then add the one people forget: repeated identical tool calls. That is the single most common agent failure mode and the cheapest to detect. Trip the breaker to a human, never to a silent failure.
Budget wants three layers rather than one. A per-response token ceiling the model cannot see. A task budget the model can see, so it paces itself and finishes gracefully instead of being cut off mid-sentence. And a hard currency cap enforced outside the agent entirely, because a budget the agent enforces on itself is a budget an agent can reason its way past.
Two published multipliers anchor everything. An agent uses roughly 4× the tokens of a chat interaction. A multi-agent system uses roughly 15×.
The same source reports that on BrowseComp, token usage alone explained 80% of performance variance, with tool-call count and model choice taking it to 95%. Read that carefully, because it inverts the usual instinct. You are largely buying quality with tokens. So the question is not how to use fewer, but how cheaply to buy each one.
Priced from the published Claude Opus 5 rates — $5/MTok input, $0.50/MTok cache read, $25/MTok output, batch at half — over a 12,000-token / 1,200-token unit of work. The architecture multipliers are the published 4× and 15×; everything else is arithmetic you can redo.
Drag the cache slider first. It is almost always the largest single lever, it changes no behaviour, and it is the one that quietly breaks — caching is a prefix match, so a timestamp early in a system prompt invalidates everything after it. If your bill jumps and nothing else changed, look for a new prefix invalidator before you look at the architecture.
The multi-agent premium is real, but it is not what kills a project — unengineered multi-agent is. Tiering models, caching aggressively and batching everything nobody is waiting for moves the same output by roughly an order of magnitude, and none of those three changes what the product does. Do them before you touch the architecture.
Write vendor-specific trace calls throughout your agent and you have chosen that vendor permanently. You will discover that at renewal.
OpenTelemetry is the only portable option, and every serious platform ingests OTLP. It is not finished: the GenAI semantic conventions are still marked Development and have moved out of the main OpenTelemetry semconv repository into their own. So pin the schema URL you emit and expect churn.
The span tree to emit: an invoke_agent root per session, a chat span per model call, execute_tool spans named for the tool, plus retrieval and MCP spans.
Capture all five token attributes — input, output, cache read, cache write and reasoning. Reasoning tokens bill as output. Omit them and your cost model is not approximate, it is wrong.
And keep a stable session id, so that a bad outcome pivots to the full trajectory. Every incident investigation starts by pulling the transcript.
The most useful production case in this space is not about model quality. It is about a team reading its own tail latency and concluding that the buy option could not meet the SLO.
Grab built its own vision LLM for identity-document processing rather than calling an external API, and the stated reason is tail latency: P99 on external APIs “can easily be 3 to 4× the P50”, which would not survive a large-scale rollout. The training story carries a second finding worth having. LoRA fine-tuning failed on non-Latin scripts and dense unstructured layouts. The fix was full-parameter fine-tuning plus continual pre-training on synthetic OCR data rendered from Common Crawl text. Thai accuracy moved roughly 70 percentage points, Vietnamese 40, while a LoRA-tuned model had already been accurate on Indonesian documents from the start.
Two engineering lessons, and the second is the one people miss. First: the buy-versus-build decision was made on the tail, not the mean. A P50 that meets your SLO and a P99 that does not is a system that fails for one user in a hundred and looks healthy on every dashboard you own. Second: the failure axis was the writing system, not the language. LoRA was, in Grab’s words, “promising for documents with Latin scripts” and reached high field-level accuracy on Indonesian, while struggling with Thai and Vietnamese. Worth noting that the article groups Vietnamese under “non-Latin scripts” when it is in fact Latin with dense diacritics — which suggests the real boundary is what the vision encoder has actually seen rendered, not the alphabet on paper. Either way, that is the axis your evaluation set has to be stratified on, and no amount of per-language accuracy reporting will surface it.
Four of these five are cheap enough that skipping them is hard to defend even at four people. One is a real problem that a seed team genuinely does not have, and saying so out loud is a better signal than having built it.
Nearly all guidance on this topic is written for one company size and then read by everyone. Pick yours — the list re-sorts, and what you should deliberately not build drops to the bottom.
A key derived from the agent's intent, reserved before the side effect and checkpointed, so a crash leaves evidence rather than ambiguity.
At this stage · Now with reconciliation for the in_flight case, because at this volume the mid-call crash stops being theoretical and starts being weekly.
Caps on turns, wall-clock, spend and repeated identical calls — three layers of budget, tripping to a human rather than to a silent failure.
At this stage · Add the per-tenant cap so one customer's bad input cannot exhaust a shared budget, and alert on cap trips — a rising trip rate is the earliest signal a tool has quietly broken.
An invoke_agent root span, a chat span per model call, execute_tool spans, and all five token attributes including cache and reasoning tokens.
At this stage · Now real OTel, because you have more than one person debugging and the first incident where nobody can reconstruct the trajectory costs more than the setup did.
Not tokens per month. Dollars per finished piece of work, split by cache hit rate, so a cost regression is visible before the invoice.
At this stage · On a dashboard now, because cost is about to become a board question and 'tokens per month' is not a sentence a CFO can act on.
Shift traffic gradually between versions so in-flight trajectories finish on the version they started on.
At this stage · Drain rather than kill: stop routing new runs to the old version and give in-flight ones a grace period. That covers most of the value for a fraction of the machinery.
Nothing is optional at this stage. That is itself the finding — the cost of the control set is part of the cost of operating here.
Not model capability. Cost escalating past the ROI case. No evaluation infrastructure, so nobody can tell whether a change helped. Risk controls inadequate for sign-off. Unclear ownership. No graceful escalation path to a human.
Gartner predicts more than 40% of agentic AI projects will be cancelled by the end of 2027 for essentially that list. Treat the percentage as an analyst forecast rather than a measurement, and the reasons as the useful part. Every one of them is an engineering-management failure, not an AI failure.
Four things belong on the operating review, and none of them are novel. Cost per completed task on the dashboard, because finance can read that line. A named owner and an on-call rota, since “who owns this when it breaks at 2am” is a question every serious interviewer asks. And a kill switch that has been tested, because an untested kill switch is decoration.
The fourth is the one that gets left off: fallback rate as an SLI. Not “is the service up” but “what fraction of responses came from the real path”. A system quietly degraded for six hours with green dashboards is worse than an outage.
Derive the idempotency key from intent, and write it before the side effect. A ledger written afterwards protects only against an in-process retry — the case that was never going to hurt you.
LangGraph restarts the whole node on resume. So validation re-runs, and an approval collected before an earlier interrupt is silently discarded. Split the gate and the action into separate nodes.
Cache reads bill at a tenth of input, batch at half, and neither changes what the product does. Do them before you touch the architecture, and watch cache_read_input_tokens rather than the invoice.
Durable execution, idempotency, circuit breakers, tail latency, tracing, blast radius. The agent-specific part is only ever what you count — turns, spend, and repeated identical calls.
Primary sources wherever one exists. Where a claim is contested or vendor-reported, the lesson says so at the point it is made.
Where the 4× and 15× token multipliers come from, and the BrowseComp finding that token usage alone explains 80% of performance variance (95% with tool-call count and model choice). Also the case for resuming rather than restarting long agents.
Closed, open, half-open, and a trial call to decide whether to close again. Popularised by Michael Nygard in Release It. Nothing about it is new and nothing about it is AI — which is the point of this lesson.
The P99-is-3-to-4×-P50 argument for owning the model, and the finding that LoRA failed on non-Latin scripts while full-parameter fine-tuning plus synthetic OCR pre-training moved Thai +70pp and Vietnamese +40pp.
Cited here for its internal incident log — deleted remote branches, an auth token uploaded to a compute cluster, migrations attempted against a production database. Each one is a durability and blast-radius problem, not a model-quality problem.
An analyst prediction, not a measurement — treat it as such. The reasons given are the useful part: escalating costs, unclear business value, inadequate risk controls. All three are engineering-management failures.
The definition worth borrowing: durable execution guarantees an application runs to completion despite adverse conditions, by replaying a complete Event History to reconstruct state after a worker crash.
The reference implementation. Stripe saves the status code and body of the first request per key and replays it — including 500s. Keys are client-generated, kept at least 24 hours, and a reused key with different parameters errors rather than silently proceeding.
States it plainly: on resume “the runtime restarts the entire node from the beginning — it does not resume from the exact line where interrupt was called”, so any side effect before the interrupt re-runs. The fix in the docs is to move side effects after the interrupt, or into their own node.
Moved out of the main semconv repo and still marked Development. Operation names include chat, embeddings, execute_tool, invoke_agent and create_agent; token attributes include input_tokens, output_tokens, cache_read, cache_write and reasoning.
Asynchronous processing at 50% of standard cost, most batches finishing inside an hour. It applies to every workload where nobody is waiting on the response — which is more of an agent estate than teams assume.
On Claude Opus 5 the documented rates are $5/MTok input, $0.50/MTok cache read (0.1×) and $6.25/MTok for a five-minute cache write (1.25×). Caching is a prefix match, so one timestamp early in a system prompt silently invalidates everything after it. Watch cache_read_input_tokens, not the bill.