Sub topic 5
Saving Checkpoints
This chapter assumes you can read Python and JSON, know that an agent calls tools in a loop, and understand that a process can be killed at any moment. It also assumes you have read the earlier chapters on task state and on breaking work into repeatable steps.
What a checkpoint is
A checkpoint is a snapshot of machine-readable task state, written to durable storage such as a file or a database. If the agent stops, a new run reads the latest checkpoint and continues from there instead of starting over.
A checkpoint is not a log. A log records everything that happened. A checkpoint records only what a new run needs in order to decide what to do next. Keep it small, so it is cheap to write often and easy to read back.
What to put in it
Store the minimum that a resumed run cannot work out for itself:
- The names of the steps that are finished.
- Any values later steps depend on, such as an output path, a cursor, or an ID returned by an API.
- A version number for the checkpoint format, so a newer program can detect an older file.
Do not store things you can cheaply recompute, such as a directory listing. Do not store secrets. Checkpoint files are often copied, committed, or shared.
When to save
Save after each step finishes, not before it starts. A checkpoint that says "transform is done" must be written only once transform really is done. If you save too early, a crash leaves a checkpoint that claims work that never happened.
Saving after every step has a cost. For steps that take milliseconds, save every N items instead. For steps that take minutes or call external services, save every time. A useful rule is to save whenever redoing the work would cost more than writing the file.
A working loop
The save_checkpoint and load_checkpoint functions below write the file safely. A later chapter explains the atomic swap in detail. For now, treat them as "write the state, or leave the old file untouched".
import json
import os
import tempfile
def save_checkpoint(path, state):
directory = os.path.dirname(os.path.abspath(path))
fd, tmp_path = tempfile.mkstemp(dir=directory, suffix=".tmp")
try:
with os.fdopen(fd, "w") as f:
json.dump(state, f, indent=2)
f.flush()
os.fsync(f.fileno())
os.replace(tmp_path, path)
except BaseException:
if os.path.exists(tmp_path):
os.unlink(tmp_path)
raise
def load_checkpoint(path):
try:
with open(path) as f:
return json.load(f)
except FileNotFoundError:
return NoneThe runner uses them like this:
STEPS = ["fetch", "transform", "validate", "publish"]
def run(checkpoint_path, step_functions):
state = load_checkpoint(checkpoint_path) or {"completed": [], "notes": []}
for name in STEPS:
if name in state["completed"]:
continue
step_functions[name](state)
state["completed"].append(name)
save_checkpoint(checkpoint_path, state)
return stateFollow one crash through this code. Suppose the process dies during validate. The checkpoint on disk lists fetch and transform. On restart, run loads it, skips those two, and runs validate again. This works only because validate is safe to repeat.
The gap between the work and the save
There is always a window between a step finishing its work and the checkpoint being saved. A crash inside that window means the step's effects exist, but the checkpoint does not record them. The resumed run will do the step again.
You cannot close this window. You can only make it harmless. If the step is idempotent, repeating it changes nothing. If it is not, for example sending an email, the repeat causes a duplicate. For such steps, record an identifier before the side effect, or check for the effect before repeating it.
Common mistakes
- Saving only at the end of the run, which makes the checkpoint useless after a crash.
- Writing directly to the checkpoint file, so a crash mid-write leaves invalid JSON.
- Keeping state in memory and assuming a later step can rebuild it.
- Storing a growing list of every item processed, which makes each save slower than the last.
Exercise
A step calls an API that creates an invoice, then the runner saves the checkpoint. The process crashes after the API call returns but before the save. What happens on restart, and how can you prevent a duplicate invoice?
Show answer
The checkpoint does not list the step as completed, so the step runs again and creates a second invoice. To prevent this, generate an idempotency key (or invoice reference) before the call and save it in the checkpoint, then pass it to the API so a repeat call returns the existing invoice. Alternatively, query for an invoice with that reference before creating one.