What Breaks in Long-Running Agents
See how crashes, timeouts, lost replies, redelivered jobs and long waits break an agent run that lives in one process, watch a crash repeat a refund, and learn what durable execution records so that a run can continue instead of starting again.
Contentsand lesson path
On this page
- Why it matters
- Five ways a long run breaks
- A crash in the middle, without and with a journal
- What durable execution means
- Check your understanding
- Apply it
- Review prompt
Lessons of Durable Agent Execution
- What Breaks in Long-Running Agents Concept · 15 min
- Checkpointers Versus Workflow Engines Concept · 15 min
- Idempotent Side Effects Worked example · 20 min
- Lab: Background Runs with Retries and Cancellation Lab · 25 min
- Crash, Resume, Compare Lab · 25 min
- Check: Failure and Recovery Scenarios Knowledge check · 8 questions
What you will learn
- Explain durable execution and choose between framework checkpointing and a workflow engine for a given agent workload.
Prerequisites: Agent Loops & ReAct
01. Why it matters
A chat answer takes a few seconds. An agent task can take minutes or days: it reads a ticket, calls a model several times, looks things up, issues a refund, sends an email, and perhaps waits for a person to approve a step. The longer a run takes, the more likely it is that something around it fails before it finishes. Servers are redeployed, containers are killed for using too much memory, cloud machines are reclaimed, and networks drop connections.
In the agent loop you built earlier, the whole state of a run lives in Python variables: the message list, the step counter, the results so far. If the process dies, that state dies with it. The only way to recover is to start again from the beginning, and starting again is not free. You pay again for every model call. Worse, every side effect (a change the agent makes in the outside world, such as a refund or an email) can happen a second time.
This lesson names the failures that matter for long runs, shows one of them on your own machine, and defines durable execution: running code so that its progress is recorded outside the process and a new process can carry on from the last recorded step.
02. Five ways a long run breaks
The failures below are ordinary. A system that runs many agent tasks will see all of them, often several times a day.
- The process dies. A deploy stops the old version, the kernel kills a process that runs out of memory (an OOM kill), or a spot instance disappears. Nothing in the process gets a chance to clean up:
try/finallyblocks and shutdown hooks do not run after akill -9. - A timeout cuts the run. If the run lives inside an HTTP request, the load balancer or proxy may close the request after 60 seconds or a few minutes, even though the work is not finished. Model and tool APIs also time out, or answer with
429 Too Many Requestsor503 Service Unavailable. - A reply is lost. The agent sends "create ticket", the ticket system creates it, and then the connection breaks before the reply arrives. From the agent's side, a timeout looks the same whether the action happened or not. This is the hardest case, because the safe-looking choice (try again) can do the action twice.
- A job is delivered twice. Most job queues promise at-least-once delivery: a message is delivered until a worker acknowledges it. If a worker finishes the work and crashes before it acknowledges, another worker gets the same job. The background jobs lesson covers this from the queue's side.
- The run has to wait. An approval from a manager, a payment that settles tomorrow, a reminder in three days. No process should sit in memory for three days hoping not to be restarted.
Each of these has the same two costs. You lose work that has to be redone, and you risk repeating effects that should happen once. Lost work costs money and time. Repeated effects cost trust: a customer refunded twice, or emailed five times, notices.
03. A crash in the middle, without and with a journal
The script below imitates a four-step refund agent. Each step appends its name to effects.log, which stands in for the outside world. Setting CRASH_AT=issue_refund makes the process kill itself with os._exit(9) straight after the refund, which behaves like a kill -9: no cleanup code runs.
The journal mode adds the simplest possible durable record: after each step finishes, the script writes the list of finished steps to journal.json. It writes a temporary file first and then renames it, because a rename on the same file system replaces the old file in one operation, so a crash never leaves half a journal behind. Save the file in an empty folder; it needs Python 3.10 or newer and no packages.
"""Four steps of a refund agent. CRASH_AT=<step> kills it after that step's effect."""
import json
import os
import sys
STEPS = ["read_order", "draft_reply", "issue_refund", "send_email"]
JOURNAL = "journal.json"
def do(step: str) -> None:
with open("effects.log", "a") as f: # stands in for the real world
f.write(step + "\n")
print("ran ", step, flush=True)
if os.environ.get("CRASH_AT") == step:
os._exit(9) # like a kill -9 or an out-of-memory kill: no cleanup runs
def run(use_journal: bool) -> None:
done = []
if use_journal and os.path.exists(JOURNAL):
done = json.load(open(JOURNAL))
for step in STEPS:
if step in done:
print("skip", step, "(journal)", flush=True)
continue
do(step)
if use_journal: # record the step only after it has finished
done.append(step)
with open(JOURNAL + ".tmp", "w") as f:
json.dump(done, f)
os.replace(JOURNAL + ".tmp", JOURNAL) # atomic rename
if __name__ == "__main__":
run(use_journal=sys.argv[1] == "journal")CRASH_AT=issue_refund python3 refund_agent.py plain
python3 refund_agent.py plain
sort effects.log | uniq -cran read_order
ran draft_reply
ran issue_refund
ran read_order
ran draft_reply
ran issue_refund
ran send_email
2 draft_reply
2 issue_refund
2 read_order
1 send_emailThe second process knew nothing about the first, so it started from read_order and issued the refund again. In a real system that is a second payment to the customer. Now delete effects.log and try the journal mode.
rm -f effects.log journal.json
CRASH_AT=issue_refund python3 refund_agent.py journal
python3 refund_agent.py journal
sort effects.log | uniq -c
cat journal.json; echoran read_order
ran draft_reply
ran issue_refund
skip read_order (journal)
skip draft_reply (journal)
ran issue_refund
ran send_email
1 draft_reply
2 issue_refund
1 read_order
1 send_email
["read_order", "draft_reply", "issue_refund", "send_email"]The journal saved two steps of work: read_order and draft_reply were skipped on the second run. But the refund still happened twice. The crash came after the refund but before the journal entry for it, so from the journal's point of view the refund never finished. This gap between "the effect happened" and "we recorded that it happened" is called the crash window, and every recording scheme has one. Recording before the effect does not help either: then a crash after the record but before the effect skips the refund completely.
So a journal changes the problem from "repeat everything" to "repeat at most the step that was running". That last repeat has to be made harmless by the step itself, which is what an idempotency key does: the refund service is told "this is refund request run-7/issue_refund", recognises the repeat and returns the first result instead of paying twice. You will build that in Idempotent Side Effects.
04. What durable execution means
Durable execution is a way of running a multi-step program so that each completed step and its result are recorded in durable storage (a database or a log that survives restarts). When a process dies, another process loads that record and continues from the last completed step. The record goes by different names: an event history in Temporal, a journal in Restate, checkpoints in DBOS and LangGraph. The idea is the same.
Three consequences follow, and they explain most of the rules in the rest of this skill.
- Steps run at least once, not exactly once. Because of the crash window, the step that was running during a crash runs again. Durable execution bounds lost work to roughly one step; it does not make an external API call happen exactly once. Exactly-once effects come from combining durable steps with idempotent side effects.
- Granularity decides what is lost. A run that records progress after every tool call loses at most one tool call. A run that records only at the end loses everything. Fine-grained recording costs some storage writes and latency per step, which is usually small next to a model call.
- State must live outside the process. Anything you need after a restart, such as the model's earlier answers, the ID of a ticket you created, or the step number, has to be in the record. Values that exist only in memory are gone after a crash.
Durable execution also does not prevent failures, and it does not make a slow run fast. Steps still fail and are retried; a run that waits for a person still waits. What changes is that a failure costs one step instead of the whole run, and a run can wait for days without a process holding it in memory.
There are two common ways to get this. A framework checkpointer saves the agent's state after each step of its graph and resumes from there; LangGraph's checkpointers are the usual example. A workflow engine, such as Temporal, DBOS or Restate, records every step of ordinary code and adds timers, queues, retries and an operations view. The next lesson, Checkpointers Versus Workflow Engines, runs the same task on both and shows when each one fits.
05. Check your understanding
06. Apply it
Take the agent you will run as a background job in this skill's practice project. Write down its steps in order and mark each one as read-only (a model call, a search) or side effect (creating a ticket, charging, emailing). For every side effect, answer three questions: what happens if it runs twice, how you would find out whether it already happened, and whether the service it calls accepts an idempotency key. Keep this list: lesson 3 turns it into idempotent tools and lesson 5 into crash tests.
07. Review prompt
Without looking back, name five ways a long agent run can be interrupted and say for each whether it loses work, repeats an effect, or both. Then explain the crash window: why a journal written after each step still lets one step repeat, why writing it before the step is no better, and what has to be added to make that repeat harmless.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.