đĨ Crash, Stop, Resume: How I Made My AI Agent Survive Failure (With Code)
My agent was on step 6 of 8. Research done. Draft written. Cover image downloaded. Then the server restarted. Me: "Okay, just continue." Agent: "Hi! How can I help you today?" All the work, all the tokens, gone. I
My agent was on step 6 of 8.
Research done. Draft written. Cover image downloaded.
Then the server restarted.
Me: "Okay, just continue."
Agent: "Hi! How can I help you today?"
All the work, all the tokens, gone. I had to pay for steps 1â5 again.
So I made a rule: a long-running agent must be able to die and come back. And to prove it, I crash it on purpose.
Content Studio: my Deep Agent harness at a glance
Give it one sentence ("write a blog post about AI agents") and it runs a long, multi-step task on its own:
- Memory:
AGENTS.mdholds brand voice + workflow rules, loaded into every run- Skills: playbooks loaded on demand (
blog-post,social-media,code-analysis)- Planning:
write_todosbreaks the task into steps and ticks them off live- Agents: local subagents (
researcher,evaluator) + remote A2A agents (infotainment,todolist,code_analyzer)- Sandbox: one Docker container per conversation
- Checkpoints: every step is saved, so a crash or Stop can be resumed
- Self-evaluation: it grades its own draft and revises until it passes
- Streaming: FastAPI SSE â React UI showing plan, tool calls, subagents, files and score
This post (Part 2/5): Checkpoints, crash and resume
Key Takeaways
- Save state after every step, keyed by
thread_id. - In LangGraph, resume = stream again with input
None. - Stop is just a clean crash: same checkpoint, same resume button.
- Test failure on purpose: a 20-line middleware that breaks the next tool call.
Table of Contents
- The Problem
- Step 1 A Checkpointer That Survives Restarts
- Step 2 Resume Is Just Input None
- Step 3 Stop Without Losing Anything
- Step 4 Crash It On Purpose
- Step 5 Wire It To The API
- Before Real Production
- Conclusion
- Reference
đ The Problem
A blog post run is ~8 steps and a few minutes long. In that time, lots can go wrong:
- The server restarts (hello
--reload) - The browser tab closes, the SSE connection drops
- A tool throws (rate limit, timeout, bad URL)
- The user hits Stop because the plan looks wrong
Without checkpoints, every one of these means start over.
đž Step 1 A Checkpointer That Survives Restarts
LangGraph saves a checkpoint after every node, keyed by thread_id. The default InMemorySaver is great... until the process dies.
The Fix: InMemorySaver already keeps everything in a few plain dicts. So I just mirror those dicts to disk after every write.
class JsonFileSaver(InMemorySaver):
def __init__(self, state_path="state.json", memory_path="memory.json"):
super().__init__()
self.state_path = state_path
self._lock = threading.Lock() # langgraph writes from many threads
self._load() # reload previous run on startup
def put(self, config, checkpoint, metadata, new_versions):
result = super().put(config, checkpoint, metadata, new_versions)
self._dump()
return result
def put_writes(self, config, writes, task_id, task_path=""):
result = super().put_writes(config, writes, task_id, task_path)
self._dump()
return result
And the dump is atomic, so a crash mid-write never leaves a broken file:
tmp = f"{self.state_path}.{uuid.uuid4().hex}.tmp"
with open(tmp, "w") as f:
json.dump(raw, f)
os.replace(tmp, self.state_path) # atomic swap
Small gotcha: the saver's dicts have tuple keys and raw bytes. JSON hates both.
def _encode(obj):
if isinstance(obj, bytes):
return {"__bytes__": base64.b64encode(obj).decode()}
if isinstance(obj, tuple):
return {"__tuple__": [_encode(x) for x in obj]}
if isinstance(obj, dict): # keys are often tuples -> store as pairs
return {"__dict__": [[_encode(k), _encode(v)] for k, v in obj.items()]}
...
Result: kill the server, start it again, and every thread is still there.
âļī¸ Step 2 Resume Is Just Input None
This is my favorite part. It's one line:
def stream_run(self, task: str, thread_id: str):
"""Start a new task on `thread_id`."""
yield from self._stream({"messages": [{"role": "user", "content": task}]}, thread_id)
def stream_resume(self, thread_id: str):
"""Continue `thread_id` from its last checkpoint (input None = resume)."""
yield from self._stream(None, thread_id)
Why this works:
- Same
thread_idâ LangGraph loads the last checkpoint for it. - Input
Noneâ "don't add a new message, just keep going from where you were". - The todo list is in state too, so the agent knows it's on step 6, not step 1.
Pro Tip: the
thread_idin the config is your resume key. Lose it and you lose the run. I put it in the URL (#/t/<thread_id>) so a page reload finds it again.
âšī¸ Step 3 Stop Without Losing Anything
The user hits Stop (or Esc). I don't kill anything. I set a flag and check it between chunks:
def request_stop(self) -> None:
"""Stop the current stream at the next chunk; the checkpoint is kept."""
self._stop_requested = True
def _stream(self, agent_input, thread_id: str):
self._stop_requested = False
stream = self.agent.stream(agent_input, self._config(thread_id),
stream_mode=["updates", "messages"],
subgraphs=True, version="v2")
try:
for chunk in stream:
yield {"type": "chunk", "data": chunk}
if self._stop_requested:
yield {"type": "stopped"}
return
except Exception as e:
yield {"type": "crash", "error": str(e)}
finally:
stream.close()
Result: Stop, crash and connection drops all end the same way: the last checkpoint is kept, and Resume picks it up. One recovery path for three problems.
đ Step 4 Crash It On Purpose
How do you test resume? You can't wait for production to break. So I wrote a tiny middleware that makes the next tool call fail:
from langchain.agents.middleware import AgentMiddleware
class CrashMiddleware(AgentMiddleware):
def __init__(self):
super().__init__()
self.armed = False
def arm(self) -> None:
self.armed = True
def wrap_tool_call(self, request, handler):
if self.armed:
self.armed = False
raise RuntimeError(f"Simulated crash during: {request.tool_call['name']}")
return handler(request)
Then plug it in like any other middleware:
create_deep_agent(..., middleware=[TodoListMiddleware(...), self.crash])
Why this works:
- The exception escapes the graph before the tool runs.
- The stream ends with a
crashevent. - The checkpoint is from just before that call, so Resume retries it.
Pro Tip: this is chaos testing for agents. Netflix kills servers; I kill tool calls.
đ Step 5 Wire It To The API
Three tiny FastAPI endpoints:
@app.post("/api/arm_crash")
async def arm_crash(req: ThreadRequest):
"""Debug: the next tool call on this thread raises."""
pool.get_or_create(req.thread_id).arm_crash()
return {"armed": True, "thread_id": req.thread_id}
@app.post("/api/threads/{thread_id}/stop")
async def stop_thread(thread_id: str):
existing_runner(thread_id).request_stop()
return {"stopping": True, "thread_id": thread_id}
@app.post("/api/resume")
async def resume_task(req: ThreadRequest):
runner = pool.get_or_create(req.thread_id)
return sse_response(sse_stream(runner.stream_resume(req.thread_id)))
Try it yourself:
- Open the UI with
?debug=1â a Simulate crash button appears - Start a task, click Simulate crash
- The next tool call fails â a red banner shows up
- Click Resume â it continues from the last checkpoint
| Event | What's kept | How to continue |
|---|---|---|
| Server restart | memory/state.json |
Resume |
| Tool crash | Checkpoint before the call | Resume |
| User Stop / Esc | Last checkpoint | Resume |
| Tab closed | Thread in URL + checkpoint | Reopen, Resume |
đ Before Real Production
Honest list of what I'd still change:
- JSON file â Postgres/Redis checkpointer. Rewriting one JSON file per step is fine for a demo, slow for 1,000 users and only works with one backend process.
-
Idempotent tools. After a resume, a tool can run twice.
download_imagetwice is fine.send_emailtwice is not. Use idempotency keys. - Auto-retry with backoff for flaky tools, so not every timeout needs a human to click Resume.
-
Checkpoint cleanup (TTL), or
state.jsongrows forever.
â Conclusion
- Save every step by
thread_id - Resume =
agent.stream(None, config). That's it. - Stop, crash and disconnect share one recovery path
- Test it with a 20-line
CrashMiddleware, don't wait for prod to test it for you
Future me: if it can't resume, it's not a long-running agent. It's a long-running gamble.
Coming up next (Part 3): From subagents to A2A. How my orchestrator talks to agents running as separate services, and how to plug any A2A agent in with one JSON line.
Reference
All the code is live here on my GitHub:
mrzaizai2k/harness_learning
Feel free to clone it, star it, or ask me anything.
-
backend/json_saver.py,backend/crash.py,backend/agent_runner.py,backend/main.py - LangGraph persistence docs
Like, comment (how do you handle agent crashes?), save it for later!
Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes â full credit and traffic to the original publisher.