Building a Reliable Agent Runtime: State Machines, Checkpointing, Recovery, and Execution Control
An LLM agent that works in a prototype may fail when processes crash, tools time out, or tasks require human approval. This article explores how to build a reliable agent runtime using state machines, checkpoints, durable execution, idempotency, recovery, and controlled scheduling.
Table of Contents
- 1. Introduction
- 2. Why an Agent Needs a Runtime
- 3. Model Agent Execution as a State Machine
- 4. Designing the Agent Runtime
- 5. Checkpointing: Persisting Execution Progress
- 6. Durable Execution and Recovery
- 7. Retry, Idempotency, and Failure Handling
- 8. Managing Long-Running Agent Tasks
- 9. Concurrency and Execution Scheduling
- 10. Human Approval as a Runtime State
- 11. Observability and Execution Tracing
- 12. Testing Runtime Reliability
- 13. Production Architecture and Implementation Strategy
- 14. Summary
1. Introduction
An agent can work perfectly in a local prototype.
It receives a task, calls an LLM, selects a tool, receives the result, and generates a final response.
But what happens when the process crashes after executing a tool?
What happens when an external API times out, but the operation was actually completed?
What happens when a user approves an action several minutes after the agent requested approval?
What happens when an agent needs to run for 20 minutes, but the server restarts after five?
These are not primarily LLM problems.
They are runtime engineering problems.
Consider our Contract Operations Assistant. A user asks:
"Review contract CTR-1024, identify compliance risks, compare its clauses against company policies, and prepare a review report."
The execution may involve:
- Retrieving contract metadata.
- Loading and parsing the document.
- Retrieving relevant policies.
- Comparing clauses.
- Investigating missing evidence.
- Generating a report.
- Waiting for human approval.
- Creating a review task.
Some operations may finish in milliseconds. Others may take several seconds or minutes. Some may depend on external services. Others may require a human to make a decision.
A simple in-memory agent loop is not enough to manage this reliably.
A production agent runtime must make execution state explicit, persist progress, recover from failures, and control every transition between actions.
In this article, we will design the runtime layer that makes an agent system reliable beyond a single process execution.
2. Why an Agent Needs a Runtime
2.1. An agent loop is not a production runtime
A basic implementation might look like this:
while (!completed) {
const decision = await model.decide(context);
if (decision.type === "tool_call") {
const result = await executeTool(decision.toolCall);
context.add(result);
} else {
completed = true;
}
}This implementation has several assumptions:
- The process remains alive.
- The model always returns a valid response.
- Tool execution finishes successfully.
- Network requests do not become ambiguous.
- The application does not restart.
- No human approval is needed.
- The task finishes within the lifetime of the request.
These assumptions are acceptable for a prototype, but they are not reliable production guarantees.
Consider this failure:
sequenceDiagram
participant R as Agent Runtime
participant T as Tool Service
participant DB as Database
R->>T: Create review task
T->>DB: Insert task
DB-->>T: Insert successful
T--xR: Response lost
Note over R: Runtime times out
R->>R: Retry operation
R->>T: Create review task again
T->>DB: Insert another task
DB-->>T: Insert successfulThe result is a duplicate review task.
The runtime does not know whether the first operation succeeded.
This is one of the most important problems in distributed execution: a timeout does not necessarily mean an operation failed.
2.2. Separate reasoning from execution management
An agent runtime should own responsibilities that must not depend on model behavior.
| Responsibility | Owner |
|---|---|
| Decide which tool to use | Model |
| Validate tool arguments | Runtime |
| Check permissions | Policy engine |
| Execute the tool | Tool executor |
| Track task progress | Runtime |
| Persist checkpoints | State store |
| Recover interrupted tasks | Runtime |
| Enforce execution budgets | Runtime |
| Decide whether a task is completed | Runtime, based on validated outcomes |
| Generate the final explanation | Model or application |
The model contributes decisions.
The runtime guarantees that those decisions are executed within defined constraints.
2.3. The runtime is an execution engine
A useful conceptual architecture is:
flowchart TD
A[Agent Request] --> B[Agent Runtime]
B --> C[State Machine]
B --> D[Model Adapter]
B --> E[Tool Executor]
B --> F[Policy Engine]
C --> G[State Store]
C --> H[Checkpoint Manager]
E --> I[External Services]
E --> J[Execution Records]
H --> G
J --> GThe runtime coordinates all components.
It should not be responsible for implementing every business operation itself. Instead, it manages the lifecycle of those operations.
3. Model Agent Execution as a State Machine
The first step toward a reliable runtime is to stop representing an agent task as a simple loop.
Represent it as a state machine.
3.1. Define task states
A practical task lifecycle could include:
| State | Meaning |
|---|---|
pending | Task has been created but not started |
running | Runtime is actively processing the task |
waiting_for_tool | Waiting for a tool operation |
waiting_for_approval | Waiting for a human decision |
completed | Task finished successfully |
failed | Task failed permanently |
cancelled | Task was cancelled |
The exact states depend on the application.
The important requirement is that each state has a clear meaning and permitted transitions.
3.2. Define valid transitions
stateDiagram-v2
[*] --> Pending
Pending --> Running
Pending --> Cancelled
Running --> WaitingForTool
WaitingForTool --> Running
WaitingForTool --> Failed
WaitingForTool --> Cancelled
Running --> WaitingForApproval
WaitingForApproval --> Running
WaitingForApproval --> Cancelled
Running --> Completed
Running --> Failed
Running --> Cancelled
Completed --> [*]
Failed --> [*]
Cancelled --> [*]A transition should not be an arbitrary update to a database field.
For example, a task should not move from pending directly to completed without passing through the required execution steps.
The runtime should validate every transition.
Recovery is deliberately absent from the task lifecycle. A task that is being recovered is still running or waiting from the user's perspective; the recovery itself is tracked on the execution, as the next section shows.
3.3. Define task and execution state separately
A task represents the overall user request.
An execution represents one attempt or continuation of that task.
This distinction becomes useful when a task needs to resume after a failure or be retried under a new execution attempt.
type TaskStatus =
| "pending"
| "running"
| "waiting_for_tool"
| "waiting_for_approval"
| "completed"
| "failed"
| "cancelled";
type ExecutionStatus =
| "active"
| "interrupted"
| "recovering"
| "completed"
| "failed";
interface AgentTask {
id: string;
tenantId: string;
userId: string;
input: string;
status: TaskStatus;
currentExecutionId: string | null;
createdAt: string;
updatedAt: string;
}
interface AgentExecution {
id: string;
taskId: string;
attempt: number;
status: ExecutionStatus;
currentStepId: string | null;
startedAt: string;
finishedAt: string | null;
}Why separate them?
Imagine an agent execution crashes and the runtime starts a recovery attempt.
The user still has one task.
The system may have multiple execution records associated with that task.
This makes it possible to distinguish the original attempt from subsequent recovery attempts without losing history.
3.4. Enforce transitions in application code
A simple transition table can make the lifecycle explicit.
const allowedTransitions: Record<
TaskStatus,
TaskStatus[]
> = {
pending: ["running", "cancelled"],
running: [
"waiting_for_tool",
"waiting_for_approval",
"completed",
"failed",
"cancelled",
],
waiting_for_tool: [
"running",
"failed",
"cancelled",
],
waiting_for_approval: [
"running",
"cancelled",
],
completed: [],
failed: [],
cancelled: [],
};
function assertTransition(
current: TaskStatus,
next: TaskStatus,
): void {
if (!allowedTransitions[current].includes(next)) {
throw new Error(
`Invalid task transition: ${current} -> ${next}`,
);
}
}A production implementation should also enforce transitions transactionally in the persistence layer.
Application-level validation alone is insufficient when multiple workers may attempt to update the same task concurrently.
4. Designing the Agent Runtime
4.1. Separate the runtime into components
A practical runtime can be divided into several components.
| Component | Responsibility |
|---|---|
| Task Manager | Create, retrieve, cancel, and inspect tasks |
| Execution Engine | Run agent execution steps |
| State Machine | Validate lifecycle transitions |
| Model Adapter | Communicate with LLM providers |
| Tool Executor | Validate and execute tool calls |
| Checkpoint Manager | Persist recoverable progress |
| Scheduler | Dispatch and resume tasks |
| Policy Engine | Enforce authorization and execution rules |
| Event Publisher | Publish lifecycle and execution events |
These components do not need to be separate microservices.
They can initially exist as modules in one application.
The separation is about responsibility, not deployment topology.
4.2. Define a runtime contract
The runtime should expose a small interface to the application.
interface CreateTaskInput {
tenantId: string;
userId: string;
input: string;
}
interface AgentTaskResult {
taskId: string;
status: TaskStatus;
}
interface AgentRuntime {
createTask(
input: CreateTaskInput,
): Promise<AgentTaskResult>;
getTask(
taskId: string,
tenantId: string,
): Promise<AgentTask | null>;
cancelTask(
taskId: string,
tenantId: string,
): Promise<void>;
}The application does not need to know how the model loop works.
It only needs to interact with the task lifecycle.
4.3. Separate task creation from execution
For short-running tasks, synchronous execution may be acceptable.
For long-running tasks, prefer asynchronous execution.
sequenceDiagram
participant U as User
participant API as Application API
participant DB as State Store
participant Q as Task Queue
participant W as Agent Worker
U->>API: Submit task
API->>DB: Create pending task
DB-->>API: Task ID
API->>Q: Publish task event
API-->>U: Return task ID
Q->>W: Dispatch task
W->>DB: Load task
W->>W: Execute agent
W->>DB: Persist progress
W->>DB: Complete taskThe user receives a task identifier immediately.
The application can then expose:
- Task status.
- Execution progress.
- Result when completed.
- Cancellation.
- Approval actions.
This avoids holding an HTTP connection open for the entire agent execution.
4.4. Use an event-driven execution model
The runtime can publish events such as:
type AgentEvent =
| {
type: "task.started";
taskId: string;
}
| {
type: "tool.started";
taskId: string;
toolCallId: string;
toolName: string;
}
| {
type: "tool.completed";
taskId: string;
toolCallId: string;
}
| {
type: "approval.requested";
taskId: string;
approvalId: string;
}
| {
type: "task.completed";
taskId: string;
}
| {
type: "task.failed";
taskId: string;
errorCode: string;
};Events allow other components to react without coupling them directly to the execution engine.
For example:
- A notification service can inform the user when a task finishes.
- A monitoring service can track execution metrics.
- A dashboard can display progress.
- An audit service can record lifecycle events.
The event system should not become the authoritative task state.
The state store remains the source of truth. Events communicate changes.
5. Checkpointing: Persisting Execution Progress
5.1. What is a checkpoint?
A checkpoint is a persisted representation of the execution state at a particular point in time.
It allows the runtime to continue from a known state rather than reconstructing everything from the beginning.
For example:
Task: CTR-1024 Review
Checkpoint 1:
Contract retrieved
Checkpoint 2:
Contract clauses extracted
Checkpoint 3:
Relevant policies retrieved
Checkpoint 4:
Clause comparison completed
Checkpoint 5:
Waiting for human approvalIf the worker crashes after checkpoint 4, the runtime can resume from the latest valid checkpoint.
5.2. Define checkpoint data
interface AgentCheckpoint {
id: string;
taskId: string;
executionId: string;
sequence: number;
state: {
messages: AgentMessage[];
completedSteps: string[];
pendingToolCalls: string[];
};
createdAt: string;
}This is a simplified structure.
A production checkpoint may also contain:
- Current plan.
- Model response identifiers.
- Tool execution references.
- Token usage.
- Budget consumption.
- Pending approval identifiers.
- Version information.
- Runtime configuration.
Avoid persisting unnecessary sensitive information.
Large document contents should generally remain in their original storage systems, with checkpoints holding references and relevant metadata.
5.3. Checkpoint after meaningful transitions
A checkpoint does not necessarily need to be written after every small operation.
A useful strategy is to persist after meaningful transitions:
- Task execution starts.
- Model decision is received.
- Tool execution is completed.
- Plan step is completed.
- Human approval is requested.
- Human approval is received.
- Task is completed or failed.
The trade-off is straightforward:
- More frequent checkpoints improve recovery granularity.
- Fewer checkpoints reduce storage and write overhead.
The correct checkpoint frequency depends on execution cost and failure risk.
5.4. Use sequence numbers and optimistic concurrency
Multiple workers or recovery processes may attempt to update the same execution.
A sequence number helps prevent stale updates from overwriting newer state.
For example:
BEGIN;
UPDATE agent_executions
SET checkpoint_sequence = 12
WHERE
id = $1
AND checkpoint_sequence = 11
AND lease_owner = $2;
-- If zero rows were updated: ROLLBACK and reload.
INSERT INTO agent_checkpoints
(id, task_id, execution_id, sequence, state_reference, created_at)
VALUES
($3, $4, $1, 12, $5, NOW());
COMMIT;If the update affects zero rows, another process has already advanced the checkpoint or taken over the lease.
The worker should reload the latest state instead of blindly overwriting it.
5.5. Make checkpoint writes transactional
When a tool execution completes, the runtime may need to update:
- Tool execution status.
- Tool result reference.
- Agent state.
- Checkpoint sequence.
- Task status.
These updates should be committed atomically when they belong to the same database transaction.
Otherwise, the system may record a tool as completed while failing to persist the observation needed for the next model call.
A consistent checkpoint is more valuable than a collection of individually successful but unrelated writes.
6. Durable Execution and Recovery
Checkpointing is necessary, but it does not automatically provide durable execution.
The runtime must also understand how to recover from interruptions.
6.1. The difference between recovery and restarting
Consider this execution:
1. Retrieve contract
2. Search policy
3. Compare clauses
4. Create review task
5. Generate reportSuppose the worker crashes after step 4.
Restarting from step 1 is inefficient and may repeat side effects.
Recovery should identify:
- Which steps completed.
- Which operations are still running.
- Which operations have ambiguous outcomes.
- Which results are available.
- Which steps can safely resume.
The runtime should continue from the latest consistent execution state.
6.2. Use a durable step record
type StepStatus =
| "pending"
| "running"
| "completed"
| "failed"
| "unknown";
interface ExecutionStep {
id: string;
taskId: string;
executionId: string;
name: string;
status: StepStatus;
attempt: number;
idempotencyKey: string | null;
inputReference: string | null;
resultReference: string | null;
startedAt: string | null;
finishedAt: string | null;
}The unknown status is important.
A tool operation may have been submitted, but the runtime may have lost the response.
In that situation, the runtime should not automatically assume success or failure.
It needs a reconciliation strategy.
6.3. Recover ambiguous operations
Suppose the runtime calls an external task service.
The request times out.
The external service may have:
- Rejected the request.
- Accepted the request but not processed it yet.
- Completed the operation but lost the response.
The runtime should query the external system using an idempotency key or operation identifier if supported.
flowchart TD
A[Tool Request Submitted] --> B{Response Received?}
B -->|Yes| C[Persist Result]
B -->|No| D[Mark Outcome Unknown]
D --> E{Can Reconcile?}
E -->|Yes| F[Query Operation Status]
F --> G{Operation Exists?}
G -->|Yes| H[Recover Existing Result]
G -->|No| I[Retry Safely]
E -->|No| J[Escalate or Manual Review]
H --> K[Continue Execution]
I --> K
C --> KThe runtime must distinguish between:
- A failed attempt.
- A completed operation with a lost response.
- An operation whose outcome cannot be determined.
This is especially important for write operations.
6.4. Worker leases and stale execution detection
In a distributed worker system, a task may be claimed by one worker.
The worker should hold a lease for a limited period.
If it crashes and stops renewing the lease, another worker can recover the task.
A simplified execution record might contain:
interface WorkerLease {
taskId: string;
workerId: string;
leaseExpiresAt: string;
heartbeatAt: string;
}A recovery scheduler can periodically identify expired leases.
However, lease expiry does not prove that the original worker has stopped.
It may be delayed, disconnected, or unable to reach the state store.
Therefore, lease-based ownership should be combined with:
- Fencing tokens or monotonically increasing ownership versions.
- Conditional state updates.
- Idempotent operations.
- Execution deduplication.
A worker with an old ownership token must not be allowed to commit new state after another worker has taken over.
7. Retry, Idempotency, and Failure Handling
7.1. Classify failures before retrying
Retries are not a universal solution.
A retry may fix a temporary network failure, but it cannot fix invalid arguments or missing permissions.
A useful classification:
| Failure | Typical handling |
|---|---|
| Network timeout | Reconcile, then retry if safe |
| Rate limit | Backoff and retry |
| Service unavailable | Limited retry |
| Invalid input | Fail or request corrected input |
| Permission denied | Stop |
| Resource not found | Return business error |
| Model provider error | Retry selectively |
| Budget exceeded | Stop or request a new budget |
| Approval rejected | Stop the restricted action |
The runtime should classify errors before deciding what to do.
7.2. Implement bounded exponential backoff
A simple retry delay can be calculated as:
delay(n) = min(maxDelay, initialDelay × 2^n) + jitterWhere:
initialDelayis the delay before the first retry.nis the retry attempt.maxDelaycaps the exponential growth.jitteris a random component that prevents retries from synchronizing.
Example:
interface RetryPolicy {
maxAttempts: number;
initialDelayMs: number;
maxDelayMs: number;
}
function getRetryDelay(
attempt: number,
policy: RetryPolicy,
): number {
const exponential = Math.min(
policy.maxDelayMs,
policy.initialDelayMs * 2 ** attempt,
);
const jitter = Math.random() * exponential * 0.2;
return exponential + jitter;
}The retry mechanism must also respect the overall task deadline.
A task with only two seconds remaining should not start another operation that may take 30 seconds.
7.3. Use idempotency keys
For operations that change external state, the runtime should generate a stable idempotency key.
interface ToolExecutionRequest {
taskId: string;
executionId: string;
stepId: string;
toolName: string;
arguments: unknown;
idempotencyKey: string;
}A useful key can be derived from stable execution identifiers:
task_id + step_id + logical_operationThe exact strategy depends on whether the business operation should be unique per task, step, or user action.
The important requirement is that retries of the same logical operation reuse the same key.
A new logical operation should receive a new key.
7.4. Use the transactional outbox pattern
There is another failure scenario:
The runtime updates the database successfully but fails to publish the task event to the queue.
The task exists but is never executed.
A transactional outbox can solve this.
Within one database transaction:
- Create the task.
- Create an outbox event.
- Commit both.
A separate publisher reads the outbox and sends events to the message broker.
flowchart TD
A[Create Task Request] --> B[Database Transaction]
B --> C[Insert Task]
B --> D[Insert Outbox Event]
C --> E[Commit]
D --> E
E --> F[Outbox Publisher]
F --> G[Message Broker]
G --> H[Agent Worker]This avoids relying on two independent operations—database write and message publication—succeeding together without coordination.
The publisher may send the same event more than once, so workers must also handle duplicate delivery safely.
7.5. Exactly-once execution is not a realistic default assumption
Distributed systems commonly provide at-least-once message delivery.
This means a message may be delivered more than once.
Trying to guarantee exactly-once execution across arbitrary external systems is usually impractical.
A more realistic architecture uses:
- At-least-once delivery.
- Idempotent processing.
- Durable operation records.
- Deduplication.
- Reconciliation.
- Explicit handling of ambiguous outcomes.
The goal is to make repeated delivery safe, not to assume that duplicate delivery will never happen.
8. Managing Long-Running Agent Tasks
8.1. Do not bind agent lifetime to an HTTP request
A task may take longer than the request timeout of:
- The reverse proxy.
- The application server.
- The client.
- The API gateway.
A long-running agent should therefore run independently of the original HTTP request.
The API creates the task and returns its identifier.
The client can then inspect its progress.
For example:
POST /agent-tasksResponse:
{
"taskId": "task_123",
"status": "pending"
}The client can request:
GET /agent-tasks/task_123And receive:
{
"taskId": "task_123",
"status": "running",
"progress": {
"completedSteps": 3,
"totalSteps": 6
}
}Progress should be derived from persisted execution state, not guessed by the model.
8.2. Support cancellation
Users should be able to cancel long-running tasks.
However, cancellation is not always equivalent to immediately terminating every operation.
Consider:
- A model request is still running.
- A read-only tool is querying a database.
- A notification has already been sent.
- A payment or external operation has already been accepted.
The runtime needs cancellation semantics.
For example:
| Operation state | Cancellation behavior |
|---|---|
| Waiting for model | Abort request if supported |
| Waiting for read tool | Cancel request if supported |
| Pending write | Prevent execution |
| Write already accepted | Reconcile; do not assume rollback |
| Waiting for approval | Cancel pending approval |
| Completed operation | Preserve result and record cancellation outcome |
A cancellation request should update the task state and signal active workers through an AbortSignal or equivalent cancellation mechanism.
The runtime should not claim that an external side effect was undone unless the external system confirms it.
8.3. Support pause and resume
Some tasks naturally require waiting.
For example:
- Waiting for legal approval.
- Waiting for an external document.
- Waiting for a scheduled processing window.
- Waiting for a human to provide missing information.
The runtime should pause without keeping a worker occupied.
When the required event arrives, it can schedule a continuation.
stateDiagram-v2
[*] --> Running
Running --> Waiting: External input required
Waiting --> Queued: Input received
Queued --> Running
Running --> Completed
Running --> FailedThis is a major reason to use persisted state rather than relying on an in-memory agent loop.
8.4. Separate progress from estimated completion
A task may have completed four out of five steps, but the remaining step may take significantly longer than all previous steps.
It is safer to report factual progress:
- Contract retrieved.
- Policies found.
- Three clauses assessed.
- Awaiting approval.
Avoid presenting an estimated percentage as a guarantee unless the system has a meaningful way to calculate it.
9. Concurrency and Execution Scheduling
9.1. Independent steps can run in parallel
Suppose a contract review requires:
- Retrieving contract metadata.
- Searching internal policies.
- Loading historical review results.
These operations are independent.
A runtime can execute them concurrently.
flowchart TD
A[Start Review] --> B[Contract Retrieval]
A --> C[Policy Search]
A --> D[Historical Review Search]
B --> E[Aggregation]
C --> E
D --> E
E --> F[Compliance Assessment]This reduces unnecessary waiting.
However, the runtime must understand dependencies before parallelizing operations.
9.2. Use a dependency graph
Represent execution steps as a directed acyclic graph when dependencies are known.
interface ExecutionNode {
id: string;
dependencies: string[];
toolName: string;
arguments: unknown;
}A node can run only when all its dependencies have completed successfully.
The scheduler can identify ready nodes and dispatch them.
For example:
get_contract ──────────┐
├── compare_clauses ── generate_report
search_policy ─────────┘This is more reliable than asking the model to manually manage every dependency.
9.3. Enforce concurrency limits
Parallel execution must be bounded.
The runtime should consider:
- Maximum concurrent tasks per tenant.
- Maximum concurrent model requests.
- Maximum concurrent tool executions.
- External service rate limits.
- Database connection capacity.
- Token and cost budgets.
For example:
interface ConcurrencyPolicy {
maxTasksPerTenant: number;
maxModelRequests: number;
maxToolExecutions: number;
}A single user should not be able to create thousands of concurrent agents and exhaust shared infrastructure.
9.4. Distinguish task-level and step-level concurrency
There are two separate scheduling problems.
Task-level concurrency: How many agent tasks can execute simultaneously?
Step-level concurrency: How many operations inside one task can execute simultaneously?
They should have separate controls.
A task may be allowed to execute four independent retrieval operations concurrently while the overall tenant is limited to a fixed number of active tasks.
10. Human Approval as a Runtime State
Human approval is not merely a user interface feature.
It is part of the execution lifecycle.
10.1. Persist the approval request
When an agent proposes a restricted action, the runtime should create a durable approval record.
type ApprovalStatus =
| "pending"
| "approved"
| "rejected"
| "expired"
| "cancelled";
interface ApprovalRequest {
id: string;
taskId: string;
stepId: string;
action: {
toolName: string;
arguments: unknown;
};
status: ApprovalStatus;
requestedBy: string;
decidedBy: string | null;
createdAt: string;
expiresAt: string;
decidedAt: string | null;
}The task moves to waiting_for_approval.
The worker releases its resources.
10.2. Bind approval to the exact operation
Approval should not mean:
"The user approved this agent."
It should mean:
"The user approved this specific operation with these specific parameters."
For example:
{
"toolName": "send_notification",
"arguments": {
"recipient": "[email protected]",
"subject": "Contract review required",
"body": "Please review contract CTR-1024..."
}
}The runtime should record an immutable snapshot or a verifiable hash of the approved operation.
If the model later changes the recipient or message body, the original approval must no longer authorize the modified operation.
10.3. Resume execution after approval
sequenceDiagram
participant A as Agent Runtime
participant DB as State Store
participant U as User
participant Q as Scheduler
participant W as Worker
A->>DB: Save approval request
A->>DB: Set task to waiting_for_approval
U->>DB: Approve exact action
DB-->>Q: Approval event
Q->>W: Resume task
W->>DB: Load approved action
W->>W: Revalidate authorization and policy
W->>W: Execute approved action
W->>DB: Persist resultApproval should not bypass authorization.
The runtime should recheck that the operation is still allowed when it resumes.
For example, the user's permissions may have changed while the task was waiting.
11. Observability and Execution Tracing
11.1. Agent observability needs multiple levels
A normal API trace may show that a request took 15 seconds.
That does not explain why.
An agent task may include:
- Several model calls.
- Multiple tool executions.
- Checkpoint writes.
- Queue delays.
- Approval waiting time.
- Recovery attempts.
The runtime should capture these separately.
11.2. Use task-level and step-level traces
A useful hierarchy:
Agent Task: task_123
├── Execution: exec_001
│ ├── Model Call: model_001
│ ├── Tool Call: tool_001
│ │ └── Contract Service Request
│ ├── Checkpoint: cp_001
│ ├── Model Call: model_002
│ ├── Tool Call: tool_002
│ │ └── Policy Search Request
│ └── Approval Request: approval_001
│
└── Execution: exec_002
├── Recovery
├── Tool Call: tool_003
└── Task CompletedThe execution model should make it possible to identify which attempt produced each result.
11.3. Track important metrics
| Metric | Purpose |
|---|---|
| Task completion rate | Overall reliability |
| Task duration | End-to-end execution time |
| Queue waiting time | Scheduling performance |
| Model latency | Provider performance |
| Tool latency | Integration performance |
| Checkpoint write latency | Persistence overhead |
| Recovery count | Runtime stability |
| Retry count | Failure frequency |
| Duplicate operation count | Idempotency effectiveness |
| Approval waiting time | Human workflow delay |
| Budget exhaustion rate | Execution efficiency |
11.4. Protect sensitive data in logs
Agent traces can contain:
- Contract contents.
- User-provided documents.
- Personal information.
- Business identifiers.
- Model prompts.
- Tool arguments.
Do not log every payload indiscriminately.
Prefer:
- Structured metadata.
- Redacted arguments.
- References to stored artifacts.
- Explicit retention policies.
- Access-controlled trace storage.
Observability should improve debugging without creating another uncontrolled copy of sensitive business data.
12. Testing Runtime Reliability
A runtime can pass ordinary functional tests and still fail under production conditions.
Reliability testing should include failure injection.
12.1. Test state transitions
Verify that invalid transitions are rejected.
For example:
- A completed task cannot restart.
- A cancelled task cannot continue executing.
- A task waiting for approval cannot execute the restricted operation.
- A failed task cannot silently become completed.
12.2. Test process crashes
Simulate a worker crash:
- Before a tool call.
- During a tool call.
- After the external operation succeeds.
- Before the result is checkpointed.
- After the checkpoint is written.
- While waiting for approval.
The runtime should recover according to the operation's execution state.
12.3. Test duplicate messages
Send the same queue event multiple times.
Verify that:
- The task is not executed twice unnecessarily.
- Completed steps are not repeated unsafely.
- Idempotency keys remain stable.
- State transitions remain valid.
12.4. Test concurrent workers
Attempt to claim the same task from two workers.
Verify that:
- Only one valid execution owner exists.
- Stale workers cannot commit state.
- Lease expiry works.
- Fencing tokens prevent outdated updates.
12.5. Test external service ambiguity
Simulate a timeout after the external service has committed an operation.
The runtime should reconcile the result rather than blindly retrying.
12.6. Test budget enforcement
Verify that the runtime stops when:
- Maximum iterations are reached.
- Maximum tool calls are reached.
- The task deadline expires.
- The token budget is exhausted.
- The cost budget is exhausted.
These limits must be enforced by the runtime, not merely described in model instructions.
13. Production Architecture and Implementation Strategy
13.1. Reference architecture
The complete runtime can be represented as follows:
flowchart TB
U[Client] --> API[Application API]
API --> TM[Task Manager]
TM --> DB[(Task and State Store)]
TM --> OB[(Transactional Outbox)]
OB --> PUB[Event Publisher]
PUB --> Q[Message Broker]
Q --> SCH[Execution Scheduler]
SCH --> W[Agent Workers]
W --> SM[State Machine]
W --> CE[Execution Engine]
CE --> MA[Model Adapter]
CE --> TE[Tool Executor]
CE --> CM[Checkpoint Manager]
TE --> PE[Policy Engine]
TE --> EXT[External Services]
CM --> DB
SM --> DB
W --> AUD[Audit and Telemetry]
TE --> AUD
API --> AUD
HR[Human Review] --> DB
DB --> SCHThe state store is authoritative.
The message broker distributes work.
The workers perform execution.
The checkpoint manager makes progress recoverable.
The scheduler handles dispatch and recovery.
The policy engine controls operations.
These responsibilities should remain distinct even if the initial implementation runs in one deployable application.
13.2. Suggested persistence model
A relational database is a reasonable starting point.
A simplified schema might include:
agent_tasks
id
tenant_id
user_id
input
status
current_execution_id
created_at
updated_atagent_executions
id
task_id
attempt
status
current_step_id
lease_owner
lease_expires_at
checkpoint_sequence
started_at
finished_atagent_steps
id
task_id
execution_id
step_name
status
attempt
idempotency_key
input_reference
result_reference
started_at
finished_atagent_checkpoints
id
task_id
execution_id
sequence
state_reference
created_atagent_approvals
id
task_id
step_id
action_hash
status
requested_by
decided_by
expires_at
decided_atagent_outbox
id
event_type
aggregate_id
payload
published_at
created_atThis is not a mandatory schema.
The exact model should reflect the runtime's execution semantics and data retention requirements.
For large checkpoint payloads, storing the full content in object storage and keeping a reference in the relational database may be more appropriate.
13.3. An incremental implementation roadmap
Do not attempt to implement every distributed execution feature at once.
A practical roadmap is:
Phase 1: Reliable single-process runtime
- Explicit task states.
- State transition validation.
- Tool execution records.
- Execution budgets.
- Basic error handling.
- Persistent task storage.
Phase 2: Asynchronous execution
- Background workers.
- Message queue.
- Task status API.
- Checkpoints.
- Cancellation support.
- Retry policies.
Phase 3: Durable execution
- Worker leases.
- Recovery scheduler.
- Idempotency keys.
- Ambiguous operation reconciliation.
- Transactional outbox.
- Concurrency control.
Phase 4: Human interaction
- Approval records.
- Pause and resume.
- Approval expiration.
- Action snapshot validation.
- Human review interface.
Phase 5: Production observability
- Distributed tracing.
- Structured audit events.
- Cost and token accounting.
- Execution replay.
- Failure injection tests.
- Runtime reliability metrics.
13.4. Build the runtime around explicit execution semantics
The most important design decision is not which queue, database, or framework to choose.
It is defining what the runtime guarantees.
For example:
- A task has one authoritative lifecycle.
- Every state transition is validated.
- Every tool operation has a durable execution record.
- Repeated delivery does not cause unsafe duplicate side effects.
- Interrupted tasks can be recovered.
- Human approvals are persisted and bound to exact actions.
- Execution budgets are enforced independently of the model.
- Every completed task has an auditable execution history.
Once these guarantees are clear, infrastructure choices become easier.
14. Summary
An agent runtime is the foundation that turns an LLM-based execution loop into a reliable application capability.
Without it, an agent is often just a process that happens to call tools.
With it, the system can manage long-running tasks, survive failures, resume execution, and maintain a trustworthy record of what happened.
The most important principles are:
- Use explicit state machines: define valid lifecycle transitions instead of relying on an in-memory loop.
- Persist execution progress: checkpoints make interrupted tasks recoverable.
- Design for distributed failure: timeouts, duplicate messages, and ambiguous outcomes are normal conditions.
- Make operations idempotent: repeated execution must not create unintended side effects.
- Separate task state from execution attempts: recovery should preserve the original task history.
- Treat approval as a runtime state: human decisions must be durable and bound to exact operations.
- Enforce concurrency and budgets: model autonomy must remain within application-defined limits.
- Test failures deliberately: a runtime is reliable only when it behaves correctly under interruption and recovery.
The key architectural principle is:
An agent should not depend on a process staying alive. Its execution must be represented as durable state that can be inspected, recovered, and continued.
This is what allows agent systems to move from short-lived interactions to dependable long-running business processes.
Next article: Designing a Multi-Model Agent Architecture: Model Routing, Provider Abstraction, and Task-Specific Intelligence.
We will explore how to use multiple models and providers within one agent system, assign different responsibilities to different models, and build a routing layer that selects models based on task requirements, quality, latency, and cost.
- AI agent runtime architecture
- Agent state machine
- Agent checkpointing
- Durable execution
- Agent recovery
- LLM task orchestration
- Long-running AI agents
- Agent execution engine
- Human-in-the-loop agents
- Production agent systems