Durable Agent Runs: Save a Checkpoint After Every Tool Turn, Resume After a Kill, and Key the Email So It Goes Out Once
A worker sends ticket T-103's invoice email and is killed before it saves. Without saved state the restart sends a second email. Save a checkpoint after every tool turn, resume from step 1, and let an idempotency key turn the repeated send into duplicate_skipped: two runs, one email.
What you will learn
- Save an agent's run state to a file after every tool turn, with a write that a crash can't leave half done
- Resume a killed run from the saved step instead of starting from the top
- Build an idempotency key from the ticket, the step and the tool name so a repeated side effect is skipped
- Tell what an Agent SDK session resume restores and what it does not
Before you start
- The agentic loop and stop_reason
- Claude tool use: tool_use and tool_result
A support agent is halfway through a long ticket. It has looked up the customer and sent the invoice email. Then the process is killed: a deploy, a crash, a machine that restarts.
When the worker comes back, what does it know? If the answer is "nothing", it starts again from the top, looks up the customer again and sends the email again. The customer gets the same invoice twice. In this article we make the run pick up where it stopped, and make sure the email goes out once.
Two problems, two tools
Two everyday pictures cover the whole idea.
- A game's save point. When you load, you continue from the last save, not from level one. That's the checkpoint: it says where to continue.
- A stamped parcel. If a parcel already carries the "sent" stamp, nobody posts it again. That's the idempotency key: it says what already went out.
You need both, because of a gap. The game saved before the parcel went out. So the save can be older than the last thing that really happened. The checkpoint brings the run back to the right step, and the key stops that step from doing its side effect a second time.
A worker dies after the email
Here is the use case from SupportDesk. A worker handles ticket T-103 with no checkpoint. It calls lookup_customer, then send_email. One email is in the outbox. Then the process is killed. On restart it has nothing saved, so it runs both tools again and the outbox holds two emails. Without saved state, a restart repeats what already happened.
The fix lives in the agent loop and one small file beside it. After each tool turn the loop writes its run state to the checkpoint. When a worker starts, it reads that state back before it does anything else. Save as you go, load when you start.
What one checkpoint holds
This is the state for T-103 right after the first tool turn, as the run printed it from disk: step 1, three messages, tools lookup_customer, keys none.
- ticket_id: which run this state belongs to.
- step: 1. It counts the tool turns that are done, so it says where to continue.
- messages: three of them. The question, the tool request and the tool result. The tool results are saved too, so a resume doesn't call the tool again just to remember the answer.
- tools_used: the tools run so far.
- keys: empty. The email's key isn't here, because the crash came before the next save.
That empty list is fine. The key is not read from the checkpoint; it's built again from the ticket and the step, so a restarted run gets the very same key.
checkpoint.py: save, load, clear
The project runs on a stand-in model (the Anthropic SDK on an httpx mock transport), so no API key is needed and the replies are test replies. The checkpoint store is the smallest file in it:
"""Checkpoint store: one JSON file per ticket holds the run state between tool turns."""
import json, os, pathlib
STATE = pathlib.Path(__file__).parent / "state"
def path(ticket_id):
return STATE / f"{ticket_id}.json"
def save(state):
STATE.mkdir(exist_ok=True)
tmp = path(state["ticket_id"]).with_suffix(".tmp")
tmp.write_text(json.dumps(state), encoding="utf-8")
os.replace(tmp, path(state["ticket_id"]))
def load(ticket_id):
if not path(ticket_id).exists():
return None
return json.loads(path(ticket_id).read_text(encoding="utf-8"))
def clear(ticket_id):
path(ticket_id).unlink(missing_ok=True)
- One JSON file per ticket, in a
statefolder. It lives outside the process, so it survives the kill. savewrites to a temp file first, thenos.replaceswaps it in. A crash in the middle never leaves a half-written checkpoint: you get the old file or the new one.loadreturnsNonewhen there is no file. That means a fresh run.cleardeletes the file once the run is done.
agent.py: resume, key, save
The agent loop is the usual tool-use loop with three additions. This is an excerpt of run(); the helpers fresh, dump, final_text and log are one-liners in the same file.
SIDE_EFFECTS = {"send_email"}
MAX_CALLS = 6
def run(ticket_id, question, client, after_tool=None):
state = checkpoint.load(ticket_id)
if state:
log(resume_line(ticket_id, state))
else:
state = fresh(ticket_id, question)
log(f"start {ticket_id} | fresh")
for call in range(1, MAX_CALLS + 1):
response = client.messages.create(
model=MODEL, max_tokens=512, system=SYSTEM,
tools=TOOLS, messages=state["messages"])
if response.stop_reason != "tool_use":
text = final_text(response)
checkpoint.clear(ticket_id)
log(f"done | checkpoint cleared | calls {call}")
return {"text": text, "calls": call,
"tools_used": state["tools_used"]}
state["messages"].append(message("assistant", dump(response)))
step = state["step"] + 1
results = []
for block in response.content:
if block.type == "tool_use":
name = block.name
extra, key = {}, "none"
if name in SIDE_EFFECTS:
key = f"{ticket_id}:step{step}:{name}"
extra = {"idempotency_key": key}
state["keys"].append(key)
output = RUNNERS[name](**block.input, **extra)
status = output.get("status", "ok")
log(f"step {step} {name} | key {key} | {status}")
state["tools_used"].append(name)
results.append({"type": "tool_result",
"tool_use_id": block.id,
"content": json.dumps(output)})
if after_tool:
after_tool(name)
state["messages"].append(message("user", results))
state["step"] = step
checkpoint.save(state)
n = len(state["messages"])
log(f"checkpoint saved | step {step}, {n} messages")
raise RuntimeError("the agent used up its calls")
- Load first. If a checkpoint exists, the loop continues from its messages. If not, it starts fresh.
- Key before a side effect. For
send_emailit buildsticket:step:tool, for exampleT-103:step2:send_email, and hands it to the tool. Nothing in that key comes from the model, so a restart builds the same one. - Save after every tool turn. The step and the messages, including the tool results.
- Clear when the answer is final. A finished run leaves nothing behind.
The after_tool hook is only there for the demo: it lets the worker kill itself right after a named tool. If the loop itself is new to you, start with the agentic loop and stop_reason.
tools/email.py: the key sends once
def send_email(to, subject, body, idempotency_key):
queue = sent()
if idempotency_key in queue:
return {"status": "duplicate_skipped", "to": to}
entry = {"to": to, "subject": subject, "body": body}
queue[idempotency_key] = entry
OUTBOX.parent.mkdir(exist_ok=True)
OUTBOX.write_text(json.dumps(queue), encoding="utf-8")
return {"status": "queued", "to": to}
The outbox is a file, keyed by the idempotency key, so it survives a restart too. A key already in the outbox means "this already went out": the tool skips the send and says duplicate_skipped. A new key is recorded and the email goes out.
Killed, then resumed
run_all.py starts the worker twice. The first time it sets CRASH_AFTER=send_email, and the worker ends with os._exit(137) right after that tool, with no cleanup, the way a killed process would. The second time it just restarts the worker.
Here is what the two workers printed:
run 1: the worker is killed after it sends the email
start T-103 | fresh
step 1 lookup_customer | key none | ok
checkpoint saved | step 1, 3 messages
step 2 send_email | key T-103:step2:send_email | queued
killed after send_email, before the checkpoint | exit code 137
disk | exit 137 | checkpoint step 1, 3 messages, tools lookup_customer, keys none
outbox: 1 email
run 2: restart the worker
resume T-103 | from step 1, 3 messages
step 2 send_email | key T-103:step2:send_email | duplicate_skipped
checkpoint saved | step 2, 5 messages
done | checkpoint cleared | calls 2
test model reply: I emailed your invoice to [email protected].
disk | exit 0 | checkpoint gone
outbox: 1 email to [email protected]
- Run 1 queued the email and was killed before checkpoint 2. On disk: step 1, three messages, no key yet.
- Run 2 resumed from step 1, so it did not look the customer up again.
- The model asked for
send_emailagain, because from step 1 that's the next move. Same ticket, same step, same tool, so the same key, and the tool answeredduplicate_skipped. - Two runs, one email. The checkpoint is gone once the run finished.
Notice that run 2 really did repeat the interrupted turn. That's the normal case: a checkpoint written after a turn can never cover the moment inside the turn. So you don't try to make the save "faster than the crash". You make the side effect safe to repeat. The same key idea, applied to a lost reply from an email service, is in reliability controls: backoff, idempotency keys and breakers.
The Agent SDK version: resume by session id
The Claude Agent SDK has its own form of this, called a session. The result message carries a session id; you pass it back with resume in ClaudeAgentOptions, and the SDK brings back the conversation. It takes the id, not a name. (This part of the lecture is from the docs; the project doesn't run it.)
| Our checkpoint | Agent SDK session | |
|---|---|---|
| Who decides what is saved | You: step, messages, tools, keys | The SDK |
| Where it is stored | Where you choose | Where the SDK keeps sessions |
| How you get it back | checkpoint.load(ticket_id) | resume= the session id |
| Un-sends an email? | No | No |
A resumed session restores the conversation. The key on the side effect is still your job. For the SDK basics see the Claude Agent SDK; for checkpointing inside a graph framework, see checkpointing in LangGraph.
Common mistakes
- Restarting from the top. Every tool runs again, side effects included.
- A checkpoint with no key. The resume lands on the right step and still sends the email twice, because the crash came after the send and before the save.
- Keeping the state in memory. It dies with the process, which is exactly the moment you need it.
- Letting the model invent the key. It could word it differently each time. Build it in code from the ticket, the step and the tool.
- Writing the checkpoint in place. A crash mid-write leaves a broken file. Write a temp file, then replace.
- Never clearing it. A finished ticket's old checkpoint would make the next run "resume" a job that's already done.
Quick recap
| Piece | What it does | In the run |
|---|---|---|
| Checkpoint after every tool turn | Says where to continue | step 1, 3 messages on disk after the kill |
| Load on start | Resume instead of restart | resume T-103 from step 1 |
| Idempotency key from ticket, step, tool | Says what already went out | T-103:step2:send_email, duplicate_skipped |
| Temp file, then replace | No half-written checkpoint | os.replace in save |
| Clear when done | No stale state | checkpoint gone, outbox 1 email |
Try it yourself
Move the crash: set CRASH_AFTER=lookup_customer instead. Before you run it, predict what the checkpoint holds on disk, whether the restart calls lookup_customer again, and how many emails end up in the outbox. Then think about what would happen if lookup_customer were a tool that charged a card.
Related course on Udemy
Claude Certified Developer - Professional (CCDV-P) Exam Prep
Claude agents in production: reliability, observability, evals, cost, guardrails and fleets.View on Udemy ↗: Claude Certified Developer - Professional (CCDV-P) Exam Prep (paid course, opens in a new tab)Related posts
The Claude Messages API: Your First Call, Field by Field
One request in, one Message out. The four fields of a Messages API call (model, max_tokens, system, messages), how to read content blocks, stop_reason and usage, and why every turn resends the history.
Claude Tool Use: How tool_use and tool_result Work in the Messages API
Follow one order question through Claude's tool round trip: define a tool, read the tool_use block, run your own function and send a matching tool_result back, including parallel calls and is_error.
Claude Client SDKs Wrap One REST API: Raw HTTP, Python, TypeScript and Async Calls Compared
Every Claude client SDK wraps the same REST request: a POST to /v1/messages with a JSON body. See it built by hand, through the Python and TypeScript SDKs, as typed errors, and as async calls that wait together.
Anthropic SDK Timeouts, Retries and Error Classes: Configure the Client Once, Then Give 429, 529, 400 and Timeouts Their Own Move
Configure the Anthropic SDK client (timeout, max_retries, with_options, async, pagination), see which errors it retries by itself, then repair a retry wrapper so a 429, a 529, a 400 and a timeout each get the move the docs support.
