CertPrep
Domain 1 · Lesson 1.2 · 8 min read

Durable Execution and State

Exam skillDurable Execution and State Management

Applying session persistence, checkpointing, resumability, and memory architecture patterns to long-running agents that must survive interruption, restart, and model version change.

Keep long-running agents correct through crashes, disconnects, pauses and model changes by putting progress in durable state, resuming from checkpoints, making repeated side effects safe, and reading stop reasons as explicit run states.

What you need to know

An agent that runs for hours will be interrupted: containers are replaced, connections drop, approvals take days, snapshots retire. Durable execution means the run's progress lives outside the conversation, so a new process (or a new model) can pick up exactly where the old one stopped. The conversation is working memory; it is not a database.

Four questions every long run must answer

QuestionDurable answerFragile answer
What has been done?A journal or status file updated after each verified stepThe transcript, or the agent's own judgment
Where do I resume?The last completed step in the journalThe beginning
Is repeating a step safe?An idempotency key from the business action on every side effect"Check your earlier messages first"
Why did the run stop?The stop reason mapped to a recorded state"It printed something, so it must be done"

Checkpoints that work

A checkpoint is what a new run needs to resume, not everything the old run saw.

  • Write at step boundaries, after a unit of work is verified (a report converted, a test passed).
  • Store compact state: the task, completed items, key findings, open questions. Keep large artifacts (tool outputs, files) in external storage and checkpoint references to them.
  • Make state machine-readable: a structured feature list with pass or fail per item, updated only after tests pass, tells each fresh session what is truly finished. Without it, new contexts either redo work or declare victory early.

Serializing the full transcript every few seconds is slow to write and may not fit back into a context window. Compressing it does not fix either problem.

Sessions and where they live

RuntimeWhere session state livesWhat the application must do
Messages API loop you writeWherever you store itPersist messages and your own step journal
Agent SDKOn the host, unless you configure durable storageIn ephemeral containers, mount or externalize session storage; store the session ID with your business record and resume by it
Claude Managed AgentsServer-side event historyReconnect by listing past events; deduplicate by event ID
Claude Code headlessSession files on the runnerCapture the session ID from JSON output and resume with it

Keeping a container alive for days so its local files survive is expensive and still fails on host maintenance.

Reconnecting to a Managed Agents session

The event stream delivers only events that happen after it opens. Two rules follow:

  1. Open the stream before sending the kickoff message, or the first events can be missed.
  2. On reconnect, open a new stream, list the session's past events to recover what was missed, and skip live events whose IDs the listing already returned.

A session that goes idle is not necessarily finished. Check the stop reason: end_turn means the turn finished, requires_action means a tool call (often an approval) is waiting for an answer.

Stop reasons as states

On the Messages API, stop_reason tells the harness why a response ended:

Stop reasonState to recordNext action
end_turnTurn completeCheck task completion against your own criteria
tool_useTool call pendingRun the tool, return the result
max_tokensTruncatedRaise the budget or continue
pause_turnServer tool paused a long turnSend the content back as the assistant turn, same tools
refusalDeclinedSafety path, not retry

Treating any text as completion, or parsing the output for a magic word, produces runs that look finished when they are not.

Side effects across restarts

A run that crashed after paying but before confirming must not pay again. Combine a step journal (skip steps already done) with an idempotency key derived from the business action (the shipment, the refund), so even a repeated call returns the original result. Reordering steps only moves the crash window.

Durable workflow engines

If a workflow engine orchestrates the agent, model calls must run as activities whose results are recorded. Replay re-executes deterministic workflow code and reuses recorded results; a model call made directly in workflow code runs again on replay and can produce a different decision.

Surviving a model version change

Multi-day runs may outlive a snapshot. Store findings, decisions and open items as structured artifacts that any model can read, so the new snapshot resumes from facts instead of re-reading another model's long transcript. Pinning a retiring snapshot past its retirement date fails hard; restarting from scratch wastes days of valid work.

In the exam

Durability items describe a run that was interrupted, resumed badly, duplicated a side effect, or misread its own state. Ask what durable record was missing (progress, session ID, event IDs, step journal, stop-reason state) and choose the option that creates it. Distractors keep infrastructure alive longer, add prompt reminders, serialize everything more often, or restart from the beginning.

Check your understanding

Question 1

A conversion agent restarts from item 1 whenever its container is replaced. What is the best fix?

Show answer

Answer: B. Progress must live where a new run can read it. Final messages are never written on a crash, and infrastructure will always restart containers.

Question 2

A Managed Agents client misses the agent's first events in some sessions. What is the cause?

Show answer

Answer: D. The stream only delivers events that occur after it opens. Open it first, then send the kickoff; missed events can be listed from the history.

Question 3

After a crash, a freight agent paid twice for 0.3% of shipments. Which fix is most robust?

Show answer

Answer: A. The journal skips finished steps and the key makes a repeated call harmless. Reordering moves the window; prompts and retries leave it open.

Apply it: Make Riverbend's migration agent resumable

Exercise · about 25 minCase: Riverbend Software

Riverbend's platform team runs a long Claude Code job, headless in CI, that upgrades 300 services to a new HTTP client library over two days. It runs in batches; a runner can be preempted at any time. Last month a preempted run restarted from the first service and opened duplicate pull requests for 40 services.

  1. Design the durable state the job keeps, and where it lives.
  2. Define how a new run resumes, including how it finds the right Claude Code session.
  3. Make pull-request creation safe to repeat.
    Done when: a restarted run cannot open a second pull request for a service.
  4. Map the run's possible endings to states an operator sees.
Check your work
Show model answer

1. State. A migration-status.json file in a dedicated branch (or an external store), one entry per service: pending, in_progress (with session ID and branch name), pr_open (with PR number), merged or failed (with reason). The job updates it only after the step is verified (tests pass, PR created).

2. Resume. On start, the job reads the file, skips pr_open and merged, resumes in_progress entries with claude --resume <session_id> if the branch exists, and otherwise starts fresh for that service. Session IDs come from the JSON output of the earlier run.

3. Idempotent PRs. The branch name is derived from the service (migrate/http-client/<service>). Before creating a PR, the job checks for an open PR from that branch and records its number instead of opening another. The check is in the job's code, not in the prompt.

4. Endings. done (all entries merged or PR open), partial (turn or budget limit reached; resumable), needs_human (a service failed twice, with its reason), and error (job crashed; resumable). Each ending posts a summary to the platform channel.

Key termsClaude CodeClaude Managed AgentsContext windowIdempotencyMessages APIStop reason

Sources