Agents need an execution model, not a longer prompt
Durable state, idempotency, tool contracts and replay boundaries determine whether an agent can operate safely.
Technical review by Aashutosh Kumar
Most agents begin life as a loop. The model reads the goal, reasons, chooses a tool, observes the result and repeats until it decides it is done. The ReAct pattern made this interleaving of reasoning and action concrete, and it is a remarkably effective way to get a model to solve multi-step problems.1 In a notebook, the loop is the whole system.
In production, that loop has to survive things a notebook never sees. Runs last minutes, hours or days. Workers crash and are redeployed mid-step. A human approval arrives the next morning. A payment API times out after it has already charged the card. Two copies of the same run start because a queue delivered a message twice. If the loop lives in the memory of one process, then when that process dies, the agent’s progress, and its knowledge of what it has already done in the world, die with it.
Teams typically respond by adding to the prompt: remember what you have done, do not repeat actions, check before retrying. These instructions address the wrong layer. Whether an action runs twice is not a reasoning problem. It is determined by where state is stored, what counts as a step, how effects are keyed and what happens on restart. Those are properties of an execution model, and an agent without one cannot operate safely regardless of how good its prompt is.
Agent execution model
01 / Program
An agent is a long-running program with side effects
The most useful reframing is to stop thinking of an agent as a conversation and start thinking of it as a program. It has inputs, intermediate state, branching control flow and side effects on external systems. Two properties make it unusual: the control flow is chosen at run time by a nondeterministic model, and the program can run far longer than any single process.
Software engineering has mature answers for long-running programs with side effects: workflow engines, durable execution, event sourcing, idempotent messaging and sagas. The work of building a production agent is largely the work of applying those answers to a program whose next step is proposed by a model. An execution model makes five decisions explicit:
- Where the authoritative state of a run lives, and what the context window is relative to it.
- What a step is, and what is guaranteed to be recorded before the next step begins.
- How each side effect behaves when it is attempted more than once.
- What each tool promises about its inputs, outputs, effects and failures.
- What is recomputed and what is read back when a run is resumed, debugged or replayed.
02 / State
Durable state: the journal is the source of truth
In a prototype, the agent’s state is its message history. That history is held in memory, appended to on every turn, truncated or summarized when it grows too long, and sent to the model as context. It is simultaneously the working memory, the audit log and the recovery mechanism, and it is poorly suited to all three.
A durable design separates them. The authoritative record of a run is an append-only journal of events: the run started with this goal and these versions; the model returned this output; this tool was requested with this key; the tool returned this result; this approval was granted by this person; this much budget was consumed. This is event sourcing applied to agents: current state is derived by folding over the events, and the events themselves are never edited.2
The context window then becomes what it should always have been: a projection of the journal, built for the model’s next decision. It can be summarized, filtered or reordered to fit a token budget without losing anything, because nothing authoritative lives there. Compaction is a change to the view, not a change to history.
03 / Steps
Steps, and the crash window between acting and recording
A step is the unit of progress that the system guarantees to record. The simplest durable step looks up whether it has already completed, executes if it has not, and records the result before the run moves on.
Illustrative TypeScript / durable step
async function step(run: Run, n: number) {
const recorded = await journal.get(run.id, n);
if (recorded) return recorded.result; // replay: read, never re-execute
await journal.append(run.id, n, { type: "step_requested" });
const result = await perform(run, n, {
idempotencyKey: `${run.id}:${n}`, // stable across retries
});
await journal.append(run.id, n, { type: "step_completed", result });
return result;
}The interesting part is the gap between perform and the final append. If the worker crashes after the effect happens but before the completion is recorded, the journal shows a requested step with no result. On recovery, the system cannot know whether the effect occurred. It must either attempt it again or go and find out.
No ordering of writes eliminates this window. Recording before acting risks claiming an effect that never happened; recording after acting risks repeating one that did. This is the same reason distributed messaging systems offer at-least-once delivery rather than exactly-once: a sender cannot distinguish a lost request from a lost acknowledgement. The practical consequence is that every step must be safe to execute more than once. That is what idempotency is for.
04 / Idempotency
Exactly-once effects are built from at-least-once execution
Since a step may run more than once, the effect of running it twice must be the same as running it once. Helland put it plainly: in distributed systems, idempotence is not optional.3 The standard construction is an idempotency key sent with every side-effecting request. The receiver stores the key with the result of the first execution and returns that stored result for any repeat. Payment providers such as Stripe expose exactly this mechanism.4
Three details decide whether it actually works.
- The key must be derived deterministically from the run and step, such as
run_id:step, so that every retry of the same logical action carries the same key. A key generated randomly on each attempt defeats the purpose entirely. - The key must be scoped to the logical action and its parameters. Reusing a key with different arguments should be rejected rather than silently returning a result for a different request.
- When a downstream system does not support idempotency keys, the agent platform must provide them itself, with a deduplication table checked before the call and updated atomically with the recorded result where possible.
The hardest case is the unknown outcome: a request that timed out after it may have been processed. Retrying blindly risks a duplicate when the receiver does not honor keys. Giving up risks a missing effect. The correct response is to reconcile: query the downstream system by idempotency key or business identifier, determine what happened, record it, and only then decide whether to retry. Every tool that writes should define how its outcomes are reconciled.
05 / Contracts
Tool contracts describe effects, not just parameters
Most tool definitions given to models describe a name, a description and a parameter schema. That is enough for the model to call the tool. It is not enough for the runtime to call it safely. A production tool contract also declares what kind of effect the tool has, how it may be retried, who it acts as, when it needs approval and how its outcome can be verified.
Illustrative TypeScript / tool contract
export const issueRefund = defineTool({
name: "issue_refund",
version: 3,
input: z.object({
orderId: z.string(),
amountMinor: z.number().int().positive(),
reason: z.enum(["damaged", "late", "not_received"]),
}),
output: z.object({ refundId: z.string(), status: z.enum(["pending", "succeeded"]) }),
effect: "non_idempotent_write", // read | idempotent_write | non_idempotent_write | irreversible
idempotency: "required",
authorization: "acting_user",
approval: { requiredAboveMinor: 50_000 },
timeoutMs: 10_000,
retry: { on: ["timeout", "rate_limited", "unavailable"], maxAttempts: 3 },
reconcile: (key) => payments.findRefundByIdempotencyKey(key),
});The effect classification is the field that drives the most runtime behavior. Classifying every tool forces a conversation that is otherwise skipped: what happens if this runs twice?
| Effect class | Examples | Safe to retry | On replay | Required controls |
|---|---|---|---|---|
| Read | Search documents, fetch an order | Yes | Use recorded result for faithful replay | Timeouts, caching, rate limits |
| Idempotent write | Upsert by natural key, set a status | Yes | Use recorded result | Natural or derived key |
| Non-idempotent write | Create a charge, send an email | Only with an idempotency key | Never re-execute | Provider key or deduplication table |
| Irreversible | Wire transfer, delete an account, publish | No automatic retry | Never re-execute | Human approval, compensation plan |
Contracts also need an error taxonomy, because the runtime’s response depends on the kind of failure, not merely its presence:
- Retryable: timeouts before sending, rate limiting, temporary unavailability. Retry with backoff within the run’s budget.
- Non-retryable: validation failures, authorization denials, missing resources. Return a structured error to the model so it can choose a different action, and never retry the same call.
- Unknown outcome: the request may have taken effect. Reconcile before anything else.
Finally, version the contracts. Tools change while runs are in flight. A run that started against version 2 of a tool, and is resumed after version 3 is deployed, must either continue on the version it started with or be migrated deliberately.
06 / Replay
Replay boundaries decide what is recomputed and what is remembered
Replay is the ability to reconstruct a run by re-executing its control logic against its recorded history. It is the mechanism behind recovery, and it is also the most powerful debugging and evaluation tool an agent platform can offer. It depends on a clear boundary.
Above the boundary is orchestration: the code that decides which step comes next given the results so far. This code is re-executed on replay, so it must be deterministic. It cannot read the system clock, generate random numbers or call the network directly, because each of those would produce different values on replay and send the run down a different path. Below the boundary are effects: model calls, tool calls, timers and human input. Their results are recorded the first time and read back on replay.
Model calls belong firmly below the boundary. Re-sampling a model during recovery produces a different decision and, potentially, a different set of actions than the ones already taken. The recorded output is what happened. Durable execution engines such as Temporal formalize exactly this division between deterministic workflow code and recorded activities.5
With the boundary in place, replay serves three purposes:
- Recovery. A crashed run resumes on any worker by replaying its journal to the last completed step and continuing from there.
- Faithful debugging. An engineer can reproduce exactly what the agent saw and decided at every step, rather than trying to recreate the conditions of a failure.
- Counterfactual evaluation. A run can be forked at step
k, with recorded history up to that point and a new prompt or model from there on, with write tools stubbed or sandboxed. This answers the question “would the new version have avoided this failure?” on real production trajectories.
07 / Waiting
Waiting is a durable state, not a sleeping process
Agents spend much of their lives waiting: for a human to approve an action, for an external job to finish, for a scheduled time, for a customer to reply. A process that sleeps while holding the run in memory is a process that will eventually be killed while waiting.
- Represent approvals and external replies as durable signals: the run records that it is waiting, releases its worker, and resumes when the signal is written to the journal.
- Represent delays as durable timers recorded in the journal, not as sleeps.
- Give every wait a deadline and a defined outcome when it expires: escalate, cancel or take a safe default.
- Show approvers the exact recorded proposal, with the parameters that will execute, rather than a fresh model-written summary.
08 / Control
Concurrency, cancellation and compensation
Durable runs raise questions that in-memory loops never had to answer. What happens if two workers pick up the same run? How does an operator stop a run safely? What happens to the effects already taken by a run that is stopped halfway through?
- One run, one writer. Use a lease or lock with fencing so that only one worker can append to a run’s journal at a time, and a worker that lost its lease cannot write stale results.
- Cancellation is an event. Record it in the journal and check for it at step boundaries, so a run stops between effects rather than in the middle of one.
- Plan compensation. Multi-step processes that span systems rarely have a single transaction. For each step with a durable effect, define the action that undoes or offsets it, so a cancelled or failed run can be unwound in order. This is the saga pattern.
Compensation is not the same as rollback. An email cannot be unsent, and a refund reversal is itself a new transaction with its own audit trail. Effects that cannot be compensated belong in the irreversible class and should sit behind approval.6
09 / Operations
The journal is also the trace
A useful side effect of a journaled execution model is that observability comes almost for free. The journal already contains every model output, every tool request and result, every approval and every retry, in order, with versions. It answers the operational questions directly:
- How many steps, retries and tool calls does a typical run take, and how is that changing?
- How often do tools return unknown outcomes, and how often does reconciliation find the effect already happened?
- How long do runs wait for approvals, and how many waits expire?
- How often are runs cancelled or compensated, and at which step?
These measures connect reliability to cost. Every retry, duplicate guard and expired wait has a price, and the journal is where it can be attributed to a run and an outcome.
10 / Practice
A minimal execution model
Not every agent needs a full workflow engine on day one. Every agent that takes actions in the world does need answers to the following:
- Persist an append-only journal per run, and build the model’s context from it rather than treating the context as state.
- Define steps and record each one before proceeding; resume from the journal after any crash.
- Send deterministic idempotency keys with every side-effecting call, and reconcile unknown outcomes before retrying.
- Write tool contracts that declare effect class, authorization, approval, timeouts, retry policy and reconciliation, and version them.
- Keep orchestration deterministic, record every model and tool result, and use replay for recovery, debugging and counterfactual evaluation.
- Make waits, cancellations and compensations durable events with deadlines.
A longer prompt changes what an agent intends to do. An execution model determines what actually happens when the process crashes, the network lies and the same message arrives twice. Only one of those can be relied on in production.
References
- 1. Yao, S. et al. (2022). ReAct: Synergizing Reasoning and Acting in Language Models. arXiv:2210.03629
- 2. Fowler, M. (2005). Event Sourcing. martinfowler.com
- 3. Helland, P. (2012). Idempotence Is Not a Medical Condition. ACM Queue, 10(4). queue.acm.org
- 4. Stripe. Idempotent requests. API reference. docs.stripe.com
- 5. Temporal. Workflows and Activities. Documentation. docs.temporal.io
- 6. Garcia-Molina, H. and Salem, K. (1987). Sagas. Proceedings of the ACM SIGMOD International Conference on Management of Data. doi:10.1145/38713.38742
Authors and reviewers