Area 03 · AI Agents · Concept 15 of 20

State and Checkpoints

Save the agent’s state at every step so a run can pause, resume or be replayed.

11–20 · Production levelPhase 3 · Weeks 11–14≈ 1 hour

The idea

Long agent runs fail: an API times out, a server restarts, a human needs a day to approve. If the run lives only in memory, all progress is lost. Checkpointing saves the full state (messages, plan, intermediate results, step number) after every step to durable storage.

With checkpoints you can resume from the last good step, replay a run to debug it, branch from an earlier step to try a different decision, and pause indefinitely for human input.

Store checkpoints in Postgres, Redis or SQLite, keyed by a run or thread ID. Make tool calls idempotent where possible, so resuming does not repeat side effects.

Why it matters

It is what makes agents reliable enough for real work that takes minutes or days.

Words to know

  • Thread IDIdentifier that groups the checkpoints of one run or conversation.
  • IdempotentSafe to run twice with the same effect as once.

Try it without code

Kill a run

  1. Start an agent with checkpointing.
  2. Stop the process mid-run.
  3. Restart with the same thread ID and confirm it continues.

Use it in code

Minimal checkpointing for a hand-written loop using SQLite.

python
import json, sqlite3

db = sqlite3.connect("runs.db")
db.execute("CREATE TABLE IF NOT EXISTS ckpt (run_id TEXT, step INT, state TEXT, PRIMARY KEY (run_id, step))")

def save(run_id, step, state):
    db.execute("INSERT OR REPLACE INTO ckpt VALUES (?, ?, ?)", (run_id, step, json.dumps(state)))
    db.commit()

def load_latest(run_id):
    row = db.execute("SELECT step, state FROM ckpt WHERE run_id=? ORDER BY step DESC LIMIT 1",
                     (run_id,)).fetchone()
    return (row[0], json.loads(row[1])) if row else (0, None)

# in the loop: step, state = load_latest(run_id); ...; save(run_id, step + 1, state)
# (serialise messages as plain dicts, not SDK objects)
PRACTICE · TICK IT AFTER THIS

Add checkpointing to your agent and prove resume works by killing it twice during a 6-step task.

Common mistakes

  • Non-idempotent tools (sending an email twice on resume).
  • Checkpointing SDK objects that cannot be serialised.

Go deeper