Lesson 61.4 · 4 of 4 · 6 min read · Reviewed 24 Nov 2026
Checkpointing agent state to SQLite or Postgres
By the end, you can
- Save agent state at each step so a run can resume after a crash.
- Choose between SQLite and Postgres for checkpoints.
ResumingSession resumption: Continuing an earlier session by reloading its saved history or state. a session (61.1) reloads the conversation. A long-running agentAgent: A system where a model decides its own next steps, calling tools in a loop until the task is done. often needs more than that: the plan, the step it reached, the tool results it has already paid for, and any structured state (62.3). If the process dies, all of that should survive. A checkpoint is how.
What a checkpoint is
A checkpoint is a snapshot of the agent’s state, saved after a step finishes. Each one is keyed by:
- a thread id: one run or conversation (one per user, ticket or job, as in 57.3);
- a step number (or checkpoint id), so you keep a history, not only the latest value.
The state itself is usually JSON: messages or a summary, the current plan, structured fields and a status.
A worked example
An agent triages a support ticket in four steps: classify, look up the order, draft a reply, request approval. After each step your code writes one row:
CREATE TABLE checkpoints (
thread_id TEXT NOT NULL,
step INTEGER NOT NULL,
state TEXT NOT NULL, -- JSON; JSONB in Postgres
created_at TEXT NOT NULL,
PRIMARY KEY (thread_id, step)
);
The worker crashes while drafting (step 3). On restart it runs SELECT state FROM checkpoints WHERE thread_id = ? ORDER BY step DESC LIMIT 1, gets the step 2 state with the order details already in it, and drafts again. The classification and the order lookup are not repeated.
The order matters: do the step, then write the checkpoint in a transaction. If you write first and the step then fails, the checkpoint lies about what happened.
SQLite or Postgres?
| SQLite | Postgres | |
|---|---|---|
| Setup | A single file, no server | A database server |
| Writers | One process at a time | Many workers at once |
| Good for | Local agents, prototypes, tests, a desktop tool | Production services, many users, queues of workers |
| Backups and access control | Copy the file | Roles, replication, point-in-time recovery |
| JSON | Stored as text, JSON functions available | JSONB with indexes on fields |
A common path is SQLite while you build, then Postgres when several workers must share threads. Frameworks offer this as a pluggable “checkpointer”: LangGraph, for example, ships in-memory, SQLite and Postgres savers behind one interface, so the agent code does not change when the store does.
What you get beyond crash recovery
- Human in the loopHuman-in-the-loop: A design where a person reviews, approves or corrects AI decisions at defined points.: pause at an approval step, save, and resume hours later when someone clicks approve.
- Time travel: load an earlier step to see what the agent knew, or fork from it to try another path (61.2).
- Debugging: the rows are a step-by-step record of the run, next to your logs (63.4).
Common mistakes
- Treating a checkpoint as idempotencyIdempotency: The property that doing an operation twice has the same effect as doing it once.. If the crash happened after a refund was sent but before the checkpoint was written, the step runs again. Tools with side effects still need idempotency keysIdempotency key: A unique id sent with a write request so the server can ignore duplicate retries of the same request. (63.2).
- Saving secrets or raw personal dataPII: Personally identifiable information: data that can identify a person, such as name, email, address or ID numbers. in state. Checkpoints are long-lived; redactRedaction: Removing or masking sensitive data, such as PII or secrets, before it is stored, logged or sent. and set an expiry, as for sessions.
- Only keeping the latest row. You lose replay and debugging. Keep a short history per thread and prune old threads.
- Unversioned state. When the state shape changes, old checkpoints fail to load. Store a schema version with each row.
Key points
- A checkpoint is a saved snapshot of an agent's state after a step, keyed by a thread id and a step number.
- Write the checkpoint after each step commits, so a restart resumes from the last good step instead of from zero.
- SQLite suits one process on one machine; Postgres suits many workers, many users and production backups.
- Checkpoints let you resume, replay and inspect a run, but tools with side effects still need idempotency keys.
Checkpoint an agent run to SQLite
Save agent state after every step so a crashed run resumes from its last good step.
You will have: A save() and load_latest() pair backed by an in-memory SQLite table, and a run that survives a crash at step 3.
Steps
- Run the starter: after the crash, the restart repeats every step.
- Create a checkpoints table keyed by thread_id and step, as in the lesson.
- Write save() so it inserts one row per finished step inside a transaction, with a schema version in the JSON.
- Write load_latest() to return the highest saved step and its state.
- Run again and count how many steps the restart repeats.
Done when
- The output shows 'resumed from step 2'.
- Only 2 steps run after the restart, and lookup_order ran once in total.
- The final status is 'awaiting approval'.
Open in the Playground No API key needed.
Starter code (Python)
import json
try:
import sqlite3
DB = sqlite3.connect(":memory:")
except Exception: # if sqlite3 is missing, fall back to a dict
DB = None
MEM = {}
STEPS = ["classify", "lookup_order", "draft_reply", "request_approval"]
calls = [] # every step that actually ran, so we can count repeated work
def do_step(name, state):
calls.append(name)
state = dict(state)
if name == "classify": state["category"] = "late delivery"
if name == "lookup_order": state["order"] = {"id": "A-1001", "status": "in transit"}
if name == "draft_reply": state["draft"] = "Your order A-1001 is on its way."
if name == "request_approval": state["status"] = "awaiting approval"
return state
def save(thread_id, step, state):
# TODO: write (thread_id, step, json state) to a checkpoints table, or to MEM if DB is None
pass
def load_latest(thread_id):
# TODO: return (step, state) for the highest saved step, or (0, {}) if none
return 0, {}
def run(thread_id, crash_at=None):
step, state = load_latest(thread_id)
for i in range(step, len(STEPS)):
if crash_at == i + 1:
raise RuntimeError(f"worker crashed during step {i + 1}")
state = do_step(STEPS[i], state)
save(thread_id, i + 1, state)
return state
try:
run("ticket-42", crash_at=3)
except RuntimeError as e:
print(e)
before = len(calls)
final = run("ticket-42")
print("steps run after restart:", len(calls) - before)
print("final status:", final.get("status"))
Show a solution
import json
try:
import sqlite3
DB = sqlite3.connect(":memory:")
DB.execute("CREATE TABLE checkpoints (thread_id TEXT NOT NULL, step INTEGER NOT NULL, state TEXT NOT NULL, PRIMARY KEY (thread_id, step))")
BACKEND = "sqlite"
except Exception:
DB = None
BACKEND = "dict"
MEM = {}
STEPS = ["classify", "lookup_order", "draft_reply", "request_approval"]
calls = []
def do_step(name, state):
calls.append(name)
state = dict(state)
if name == "classify": state["category"] = "late delivery"
if name == "lookup_order": state["order"] = {"id": "A-1001", "status": "in transit"}
if name == "draft_reply": state["draft"] = "Your order A-1001 is on its way."
if name == "request_approval": state["status"] = "awaiting approval"
return state
def save(thread_id, step, state):
row = json.dumps({"v": 1, **state}) # store a schema version with the state
if DB is None:
MEM.setdefault(thread_id, {})[step] = row
return
with DB: # one transaction per checkpoint
DB.execute("INSERT INTO checkpoints VALUES (?, ?, ?)", (thread_id, step, row))
def load_latest(thread_id):
if DB is None:
rows = MEM.get(thread_id, {})
if not rows: return 0, {}
step = max(rows); data = json.loads(rows[step])
else:
r = DB.execute("SELECT step, state FROM checkpoints WHERE thread_id = ? ORDER BY step DESC LIMIT 1", (thread_id,)).fetchone()
if r is None: return 0, {}
step, data = r[0], json.loads(r[1])
data.pop("v", None)
return step, data
def run(thread_id, crash_at=None):
step, state = load_latest(thread_id)
if step:
print(f"resumed from step {step}")
for i in range(step, len(STEPS)):
if crash_at == i + 1:
raise RuntimeError(f"worker crashed during step {i + 1}")
state = do_step(STEPS[i], state)
save(thread_id, i + 1, state)
return state
print("backend:", BACKEND)
try:
run("ticket-42", crash_at=3)
except RuntimeError as e:
print(e)
before = len(calls)
final = run("ticket-42")
print("steps run after restart:", len(calls) - before)
print("final status:", final.get("status"), "| order:", final["order"]["id"])
print("lookup_order ran", calls.count("lookup_order"), "time(s)")
Finished the chapter? Take the chapter check.