LLM Agent Checkpoints and Recovery After Failure
Abstract
Briefly: Long agent tasks should be broken into steps with state saved in checkpoints after each step to continue from the last successful step after a failure, rather than starting over.
When is This Needed
An agent performs a chain of 10-100 LLM and tool calls. Any step can fail: API timeout, tool error, container restart. Without checkpoints, all progress is lost, and a restart duplicates side effects (sent emails, created records).
See also Agent Loop, Agent State Machine, Trajectory.
Step 1. Define the Unit of State
Agent state is more than just message history. Minimal set:
| Field | Type | Purpose |
|---|---|---|
| run_id | uuid | Launch identifier |
| step_index | int | Number of the last completed step |
| messages | json | Message history (role, content, tool_calls) |
| scratchpad | json | Intermediate results not included in messages |
| pending_tool | json | Tool called but not yet confirmed |
| status | enum | running, waiting_approval, done, failed |
| idempotency_keys | json | Keys for already executed side effects |
Storing everything in one document (JSONB in PostgreSQL or document in MongoDB) is simpler than splitting across tables.
Step 2. Saving Points
Save a checkpoint strictly after completing a step and before starting the next. Two safe moments:
- After receiving the LLM response, if it contains no tool_calls — the step is complete.
- After successfully executing a tool and recording its result in messages.
import json, uuid
from dataclasses import dataclass, asdict
@dataclass
class Checkpoint:
run_id: str
step_index: int
messages: list
scratchpad: dict
pending_tool: dict | None
status: str
idempotency_keys: list
def save_checkpoint(store, cp: Checkpoint) -> None:
store.upsert(cp.run_id, json.dumps(asdict(cp)))
Do not save state between tool call and recording result: if failure occurs here, it's unclear if the side effect was executed.
Step 3. Idempotency of Side Effects
Each tool changing external state receives an idempotency key derived from run_id and step_index.
def idem_key(run_id: str, step_index: int, tool_name: str) -> str:
return f"{run_id}:{step_index}:{tool_name}"
External system (CRM, mail gateway, DB) should reject duplicate calls with the same key. If the external system can't do this — maintain a local table of executed keys and check it before calling.
Step 4. Resumption
On agent start, first look for an unfinished checkpoint by run_id.
def resume(store, run_id: str, agent) -> Checkpoint:
raw = store.get(run_id)
if raw is None:
return agent.start(run_id)
cp = Checkpoint(**json.loads(raw))
if cp.status == "done":
return cp
if cp.pending_tool is not None:
# the tool might have executed — check by idempotency key
result = agent.replay_tool(cp.pending_tool, cp.idempotency_keys)
cp.messages.append(result)
cp.pending_tool = None
return agent.continue_from(cp)
Step 5. Flowchart
flowchart TD
A[Start run_id] --> B{Checkpoint exists?}
B -- no --> C[Step 1]
B -- yes --> D[Load state]
D --> E{pending_tool?}
E -- yes --> F[Check idempotency]
F --> C
E -- no --> C
C --> G[Call LLM]
G --> H{tool_calls?}
H -- yes --> I[Execute tool]
I --> J[Save checkpoint]
J --> C
H -- no --> K[Final response]
K --> L[status=done]
Step 6. Limitations
- Checkpoint should not contain secrets and PII in plain text — encrypt scratchpad field or remove sensitive data before writing.
- Size of messages grows linearly; apply context compression for long runs (llm-context-window-budgeting).
- Version checkpoint schema: schema_version field, migrations when reading old records.
- TTL for completed checkpoints to avoid accumulating garbage.