Sub topic 5
Saving Checkpoints
This chapter assumes you can read Python and JSON, know that an agent runs tools in a loop, and understand basic file system behavior such as files, directories, and processes. It covers what a checkpoint is, what belongs in one, when to write it, and the errors that make checkpoints misleading.
What a checkpoint is
A checkpoint is a small, machine-readable record of how far a task has progressed. It lives outside the agent's memory, usually in a file or a database row. If the process dies, the context window fills up, or the session ends, a new run reads the checkpoint and continues from there instead of starting over.
A checkpoint answers one question for the program: "What has already been done, and what do I need to continue?" That is different from a progress file, which is written for humans and covered in the next chapter. A checkpoint is precise and structured. A progress file is explanatory and loosely structured.
| Property | Checkpoint | Progress file |
|---|---|---|
| Main reader | Code | A person or an agent reading prose |
| Format | JSON, a database row, or similar | Markdown or plain text |
| Content | Completed steps, cursors, IDs | Goal, decisions, next action, open problems |
| Failure if wrong | The run skips or repeats work | The reader makes a poor decision |
What to put in a checkpoint
Store the minimum a restarted run needs to continue. A good checkpoint usually contains:
- The names or IDs of completed steps.
- Cursors for work done in batches, such as "last processed row ID" or "next page token".
- Identifiers of external things the task created, such as a file name, a job ID, or a remote resource ID.
- A schema version, so a newer program can recognize an older checkpoint.
- A timestamp or run ID, so you can tell which run wrote it.
Leave out anything you can cheaply recompute, and anything large. Do not paste whole documents or entire conversation histories into a checkpoint. Store a path or an ID that points to them instead. Never store secrets such as API keys. A checkpoint is often copied, logged, or shared during a handoff.
A checkpoint for a four-step pipeline might look like this:
{
"version": 1,
"run_id": "2026-11-28-a",
"completed": ["fetch", "transform"],
"cursor": {"validate": {"last_row_id": 18250}},
"artifacts": {"fetch": "out/raw.csv", "transform": "out/clean.csv"}
}The completed list says which steps are finished. The cursor records partial progress inside the step that was running. The artifacts map says where each step left its output, which lets a later run check that the output still exists.
When to save
The core rule is to save after a unit of work is finished and its effects are durable, not before and not halfway through. The order matters.
- Do the work.
- Confirm the effects are in place (the file is written, the API call returned success).
- Record the step as complete in the checkpoint.
If you write the checkpoint first and then crash, the checkpoint claims work that never happened. On resume the step is skipped, and the task finishes with a silent gap. If you do the work and crash before saving, the worst outcome is that the step runs again. That outcome is safe only if the step can be repeated without harm, which is the subject of the idempotent steps chapter. For steps with side effects such as sending an email, plan for this window explicitly.
How often to save
Saving more often loses less work on a crash but costs more time and more writes. Choose a granularity based on the cost of redoing work.
- Save after every step when steps are expensive, slow, or have side effects.
- Save every N items when you process many cheap items, such as every 100 rows. A crash then costs at most N items of rework.
- Save at natural boundaries, such as after each file, each page of results, or each tool call that changes the outside world.
For an agent, a useful rule is to checkpoint after any action that cannot be undone and after any action that took a long time to produce. Reading a file is cheap to repeat. Creating a pull request or spending 20 minutes on a model call is not.
A minimal implementation
The save_checkpoint function below writes to a temporary file in the same directory and then swaps it into place with os.replace. A crash during the write leaves either the old checkpoint or the new one, never a half-written file. The next chapter explains why this works. For now, treat it as the correct way to write the file.
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 Noneload_checkpoint returns None when no file exists, which means "this is a fresh run". That gives the caller one clear branch for the first run and another for a resumed run.
Now use it in a loop. The loop skips steps already recorded as completed and saves after each new step, so a restarted run continues at the first unfinished step.
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 stateNotice the order inside the loop: the step function runs, and only then is the step appended to completed and saved. This is the "work first, record second" rule in code.
To see it work, run it with step functions that print a message, and make one of them fail the first time:
import os
attempts = {"validate": 0}
def make_step(name):
def step(state):
if name == "validate" and attempts["validate"] == 0:
attempts["validate"] += 1
raise RuntimeError("simulated crash")
print("running", name)
return step
step_functions = {name: make_step(name) for name in STEPS}
try:
run("demo_checkpoint.json", step_functions)
except RuntimeError as e:
print("first run failed:", e)
run("demo_checkpoint.json", step_functions)
os.remove("demo_checkpoint.json")This snippet assumes the save_checkpoint, load_checkpoint, STEPS, and run definitions above are in the same file. The first run prints running fetch and running transform, then fails at validate. The second run prints running validate and running publish. It does not repeat fetch or transform.
Checkpointing inside a long step
Step-level checkpoints are too coarse when one step is itself long, such as processing a million rows. Add a cursor that records progress within the step.
def process_rows(state, rows, checkpoint_path, batch_size=100):
cursor = state.setdefault("cursor", {}).get("process", 0)
for i in range(cursor, len(rows), batch_size):
batch = rows[i:i + batch_size]
for row in batch:
handle(row)
state["cursor"]["process"] = i + len(batch)
save_checkpoint(checkpoint_path, state)
state["completed"].append("process")
save_checkpoint(checkpoint_path, state)
def handle(row):
print("handled", row)A restarted run resumes at the saved cursor. Rows handled after the last save but before the crash are handled again, at most batch_size of them. So handle must tolerate being called twice on the same row, or the cursor must be saved after every row.
Common mistakes
- Saving before the work is done. The checkpoint then records work that may not exist. Always save after confirming the effect.
- Writing the file in place. Opening the real checkpoint path with mode
"w"truncates it first. A crash in the middle leaves an empty or partial file. Use the temporary-file-and-replace pattern. - Treating a corrupt file as a fresh run. If
json.loadraisesJSONDecodeError, do not silently returnNone. That would restart the task and repeat side effects. Stop and report the problem, or fall back to a known backup. - Storing a flag that can drift from reality. A
"published": trueentry says nothing about whether the page is still live. The resume chapter covers checking saved state against the outside world. - Keeping the only copy in agent memory. If the checkpoint lives in a variable and is saved "at the end", an interruption loses everything. Save as you go.
- Checkpointing too much. Large checkpoints slow every save and increase the chance of storing sensitive data. Keep them small and point to artifacts by path.
Where to store checkpoints
A local JSON file is the simplest choice and suits a single process on a single machine. Use something else when the situation changes.
- If the task may resume on a different machine, store the checkpoint in shared storage such as an object store or a database.
- If several workers update progress, use a database with transactions, or follow the locking guidance in a later chapter.
- If the working directory may be cleaned between sessions, store the checkpoint in a location that persists, and check that it does.
Exercise
A task sends a report email and then saves a checkpoint marking the "notify" step complete. The process crashes right after the email is sent but before the checkpoint is saved. What happens on resume, and how can you reduce the harm?
Show answer
On resume the checkpoint does not list "notify" as complete, so the step runs again and the recipient gets a second email. You can reduce the harm by making the step idempotent, for example by recording a unique message ID or a "sending" marker before the send and checking it on resume, or by using a mail API that accepts an idempotency key. Saving the checkpoint before sending would be worse, because a crash would then skip the email entirely.
Exercise
Why does the batch loop in process_rows save the cursor as i + len(batch) after the batch is handled, rather than before the batch starts?
Show answer
Saving after the batch records only work that has actually been done. If the cursor were saved before handling, a crash in the middle of the batch would make the resumed run skip rows that were never handled. Saving after means a crash can only cause rows to be handled again, which is the safer failure.