Zero Labs
Industry News / AI

Durable AI Agents: How to Build Long-Running Workflows That Survive Crashes, Restarts, and Real…

Source · Towards AI By Anna Jey

From the publisher’s feed, collected in the ZeroLabs newsroom.

Durable AI Agents: How to Build Long-Running Workflows That Survive Crashes, Restarts, and Real UsersThe next hard problem in AI engineering is not making an agent impressive for five minutes. It is making the same agent reliable after five hours, three retries, one human approval, a deploy, a failed tool call, and a restart.A durable agent is less like a chatbot and more like a small distributed system with memory, logs, checkpoints, approvals, and recovery paths.Most AI agent demos quietly assume a perfect run. The model gets a task, calls a few tools, writes a result, and stops. That is useful for a demo, not enough for production.Production agents run into boring, expensive reality. A browser session expires. A queue worker restarts. A model call times out after the agent has already sent an email draft to an approval queue. A deployment kills an in-memory process. A user returns six hours later and expects the system to know what happened. A tool succeeds, but the model never receives the response. The agent retries and performs the same side effect twice.That is why the phrase durable AI agents deserves more attention. The industry has spent the last year talking about tool calling, multi-agent orchestration, MCP servers, and evals. Those pieces matter. But if your agent cannot survive interruption, reconstruct state, avoid duplicate side effects, and resume from a trusted checkpoint, it is still a fragile script with a model in the middle.This guide is for developers, founders, and AI professionals moving from impressive prototypes to systems that must keep working when real users touch them.Why Durable Agents Are Suddenly a Developer PriorityThe market signal is clear: agents are becoming longer-lived. OpenAI has been expanding its Agents SDK and agent-building primitives, LangGraph emphasizes persistence and human-in-the-loop execution, Cloudflare documents long-running agents on top of Durable Objects, and workflow runtimes such as Temporal and Restate keep showing up in production agent conversations. The common theme is simple: an agent is no longer just one request and one response.Recent developer discussions point to the same pain. Builders are asking where agent state should live, what should be checkpointed, how to handle user approvals behind an API, and how to keep a persistent workspace separate from chat history. Those are not prompt-engineering questions. They are systems questions.Once an agent becomes long-running, the failure mode moves from “the model gave a weak answer” to “the runtime lost track of reality.”The shift matters because valuable agent use cases are rarely one-shot chats. They include investigating production bugs, processing invoices, reconciling support tickets, running research, updating CRM records, testing code changes, generating reports, and coordinating approvals. These jobs have multiple steps, partial progress, side effects, and delayed decisions.If those workflows fail, users do not want a charming explanation. They want to know what happened, what changed, what did not change, what needs approval, and whether it is safe to continue.What Makes an AI Agent Durable?A durable AI agent is an agent whose important progress can survive process death, deploys, restarts, timeouts, human delays, and recoverable tool failures.That definition has practical parts:Persistent task state: the task goal, current status, owner, acceptance criteria, and next expected action live outside the model context.Checkpointed execution: the system stores enough state after important steps to continue without replaying unsafe actions.Idempotent tools: retries do not accidentally create duplicate payments, messages, files, records, or tickets.Event history: the agent has an append-only record of decisions, tool calls, approvals, outputs, and failures.Recoverable workspace: files, logs, screenshots, browser state, and generated artifacts are treated as first-class execution state, not stuffed into chat memory.Human interruption points: the workflow can pause for approval, clarification, or review without losing the execution graph.Replay and inspection: engineers can reconstruct what happened when the answer, action, or cost looks wrong.This is why durable agents borrow ideas from distributed systems, job queues, workflow engines, database transactions, event sourcing, and CI pipelines. The model is important, but durability mostly comes from the runtime around the model.The Wrong Mental Model: Chat Memory as StateThe easiest mistake is treating conversation history as the system of record. It feels natural because agents are often built through chat interfaces. The user says something. The model responds. Tool outputs are appended to the message list. The next model call sees the list and continues.That works until the workflow becomes long, expensive, or operationally meaningful. Chat history is a poor database. It is verbose, lossy when summarized, expensive to send to the model, hard to query precisely, and dangerous to trust after many tool calls. It also mixes different kinds of information: user intent, model reasoning, tool output, temporary errors, user approvals, generated files, assumptions, and stale intermediate plans.A better model is to split the agent system into four stores:Task store: durable business state, such as goal, status, deadline, assignee, approvals, and acceptance criteria.Event log: append-only execution history for actions, observations, model calls, tool calls, and decisions.Workspace store: artifacts created during execution, such as files, logs, screenshots, patches, reports, and browser captures.Model context package: a compact, current, purpose-built slice of information passed into the next model call.The model context is not the source of truth. It is a generated view of the source of truth.A Reference Architecture for Durable AI AgentsThe durable runtime owns state, events, tools, workspace, approvals, and recovery. The model receives only the context needed for the next decision.A durable agent architecture does not need to be complex on day one. But it should have explicit boundaries. A useful starting design looks like this:1. Task APIThe task API receives user intent and creates a durable task. It should not immediately depend on a live model process finishing the entire workflow. The API returns a task ID and lets the user or UI subscribe to progress.POST /agent-tasks{ "goal": "Investigate failing checkout tests and draft a fix", "approval_policy": "require_review_before_patch", "workspace_id": "repo_742", "deadline": "2026-05-19T18:00:00Z"}That task ID becomes the stable handle for status, logs, artifacts, approvals, cost, and recovery.2. Durable OrchestratorThe orchestrator decides which step runs next. You can build it with a framework such as LangGraph, a workflow engine, a queue plus database, or your own finite-state machine. The key requirement is that every important transition is persisted before the system moves on.Do not hide the workflow inside one model call. Make the states visible: planned, waiting for tool, waiting for approval, running test, failed recoverably, completed, cancelled, needs human review.3. Context BuilderThe context builder reads task state, events, artifacts, and policy, then creates the next model input. This layer decides what the model needs now, not everything that ever happened.For example, a context package for a retry might include:The current goal and acceptance criteriaThe last successful checkpointThe failed tool call and stderrThe files changed since the checkpointThe retry policy and remaining budgetThe next allowed actionsThis is how durable agents connect to context engineering without duplicating the older topic. Context is a runtime product, not a transcript dump.4. Tool GatewayThe tool gateway wraps every external action. It adds authorization, validation, timeout handling, idempotency keys, logging, redaction, and blast-radius checks.async function runTool(taskId, stepId, toolName, input) { const idempotencyKey = `${taskId}:${stepId}:${toolName}`; await eventLog.append({ taskId, type: "tool_requested", toolName, inputHash: hash(input), idempotencyKey }); const result = await tools[toolName].execute(input, { idempotencyKey, timeoutMs: 30000 }); await eventLog.append({ taskId, type: "tool_completed", toolName, resultHash: hash(result), safeSummary: summarize(result) }); return result;}This pattern matters more than it looks. The model should not be the only thing preventing duplicate side effects. If a request times out after the external system succeeded, the retry should reuse the same idempotency key and return the original result when possible.5. Workspace RuntimeFor coding, research, browser, and document tasks, state is not only JSON. It is a workspace: files, dependency installs, scripts, screenshots, browser sessions, PDFs, test output, and review notes.A durable agent treats the workspace like a project folder with versioned artifacts. The next run can inspect the actual workspace instead of asking the model to reconstruct everything from memory.Checkpointing: What to Save and WhenCheckpointing is the heart of durable agent design. A checkpoint is a trusted recovery point.Good checkpoints are created after steps that change the world or establish important knowledge. For example:After the task plan is acceptedAfter a file patch is writtenAfter tests completeBefore sending an email, payment, update, or deletionAfter a human approval decisionAfter a batch of tool calls creates artifactsA useful checkpoint includes:{ "task_id": "task_123", "checkpoint_id": "cp_007", "status": "waiting_for_review", "goal": "Investigate failing checkout tests and draft a fix", "completed_steps": [ "mapped repo", "reproduced failing test", "patched validation branch", "reran targeted tests" ], "changed_artifacts": [ "src/checkout/validate.ts", "test/checkout/validate.test.ts" ], "next_action": "request human review before broader test run", "blocked_on": "review_approval", "budget_remaining": { "model_calls": 12, "tool_calls": 30 }}The checkpoint should be compact enough for quick inspection, but structured enough that a different worker, model, or process can continue the job.Human-in-the-Loop Is a Runtime Feature, Not a ButtonMany teams say they have human-in-the-loop because they put an approve button at the end. That is a weak version of the pattern. In durable agents, human review is an interruptible state transition.The system should know exactly what is being approved. It should store the proposed action, the context required to judge it, the reviewer, the decision, the timestamp, and the post-approval continuation step.For high-impact tools, use policy before execution:const policy = { send_email: "approval_required", update_customer_record: "approval_required", run_readonly_query: "auto_allowed", create_draft_document: "auto_allowed", delete_file: "blocked"};The approval state should survive hours or days. The worker may stop. The user may close the browser. A deploy may happen. None of that should erase the pending decision.How to Avoid Duplicate Side EffectsSide effects are where fragile agents become dangerous. A durable agent needs a clear rule: every side-effecting action must be either idempotent, reversible, or approval-gated.Use idempotency keys for APIs that support them. Store external IDs after successful calls. Before retrying, check whether the previous attempt already succeeded. For systems that do not support idempotency, create your own operation ledger.CREATE TABLE agent_operations ( operation_key TEXT PRIMARY KEY, task_id TEXT NOT NULL, tool_name TEXT NOT NULL, input_hash TEXT NOT NULL, external_id TEXT, status TEXT NOT NULL, created_at TIMESTAMP NOT NULL, completed_at TIMESTAMP);Before a tool executes, insert a pending operation. If the same operation key already exists, do not blindly run it again. Inspect the stored status and return the known result when safe.Observability for Durable AgentsDurability without observability creates a different problem: the agent survives, but nobody can understand it. Your logs should let an engineer answer five questions quickly:What was the agent trying to do?What did it know when it made the decision?Which tools did it call?Which side effects actually happened?Where should recovery continue?Durable agents need lifecycle visibility: current state, checkpoint history, pending approvals, retry budget, and recovery path.For each step, log the model, prompt template version, tool schema version, policy version, input hashes, output summaries, cost, latency, and result status. You do not need to store every raw token forever. You do need enough structured data to debug behavior, reproduce context, and satisfy compliance requirements when the agent touches sensitive workflows.Testing Durable AgentsNormal unit tests are still useful, but they are not enough. Durable agents need failure injection tests.Start with these cases:Crash after tool success: the tool succeeds, but the worker dies before the model sees the result. The retry should not repeat the side effect.Restart during approval: the workflow pauses for human input, the process restarts, and the approval resumes the correct step.Stale checkpoint: the agent tries to continue from old state, but the workspace changed. The runtime should detect the mismatch.Tool timeout ambiguity: the external call times out. The system should check operation status before retrying.Model swap: a different model continues from the checkpoint. The task state should remain understandable.Context compression failure: the generated context omits a critical constraint. The evaluation should catch it before the next unsafe action.The best tests do not ask, “Did the model produce the exact same words?” They ask, “Did the system preserve the invariant?” Key invariants include no duplicate side effects, no execution after denied approval, no continuation from an untrusted checkpoint, and no destructive tool call without policy clearance.Framework Choices: What to Use and What to OwnYou can build durable agents several ways. The right choice depends on how much control you need and how critical the workflow is.Agent frameworks are useful when you want built-in graph execution, state management, streaming, and human-in-the-loop patterns. LangGraph is a common choice for graph-shaped agents with checkpointing and persistence. OpenAI’s Agents SDK gives developers a structured way to build agents, tools, guardrails, and traces. These can reduce boilerplate, but you still need to own your task schema, tool policies, and product-specific state.Workflow engines are useful when reliability matters more than agent-specific convenience. Temporal, Restate, durable queues, and similar systems give you retries, timers, event history, and durable execution semantics. They are strong fits for agents that must coordinate payments, approvals, notifications, or multi-hour background jobs.Serverless durable runtimes are useful for agent systems that need colocated state, scheduled work, and edge-friendly execution. Cloudflare’s Agents model, built on Durable Objects, points to this direction: agent identity, state, and long-running behavior become runtime primitives rather than afterthoughts.The mistake is expecting any framework to solve your product semantics. No library knows which actions are destructive in your business, which artifacts prove completion, which user can approve what, or which retry is safe.A Practical Build ChecklistIf you are starting from a prototype, add durability in layers.Give every agent task a stable task ID.Persist task status outside the chat transcript.Create an append-only event log for model calls, tool calls, approvals, and failures.Wrap every side-effecting tool with idempotency and policy checks.Store workspace artifacts as files or objects, not only model messages.Add explicit checkpoints after important steps.Build a context generator that reads state and creates the next model input.Add recovery tests that kill workers between steps.Expose task status, pending approvals, and artifacts in the UI.Track cost, latency, retries, and completion rate per task type.That checklist turns an agent from a clever loop into an operational workflow.Common Anti-PatternsOne giant while loop: The agent runs until it is done or breaks. There are no visible states, no checkpoint boundaries, and no safe recovery point.Memory as a junk drawer: Every artifact gets summarized into chat memory. Logs, files, screenshots, approvals, and test results become lossy text instead of durable artifacts.Retries without operation identity: The agent retries a failed step, but the system cannot tell whether the previous external action succeeded.Approval after the blast radius: The user reviews the final answer after the agent already performed the risky action.Framework-as-architecture: The team assumes checkpointing exists because the framework has a checkpoint feature, but nobody defines what state matters for the business workflow.The Real Payoff: Trustworthy AutonomyDurability is not glamorous. It will not make a demo clip go viral by itself. But it is one of the differences between an agent that users admire once and an agent they trust every week.Reliable agents do not need to be fully autonomous. The best early durable agents are often semi-autonomous: they gather context, run tools, prepare artifacts, check status, and resume after interruption. They ask humans to approve irreversible steps and make progress visible.That is the practical path from AI assistant to dependable software worker. Do not start by asking how to make the model more agentic. Ask how to make the workflow recoverable.FAQWhat are durable AI agents?Durable AI agents are agent systems designed to survive interruptions, restarts, timeouts, human delays, and recoverable failures. They persist task state, event history, checkpoints, approvals, and workspace artifacts outside the model context.How are durable agents different from normal AI agents?A normal agent may rely on a live process and chat history to continue. A durable agent has a runtime that can reconstruct the workflow from trusted state and resume safely, even if the model, worker, or server changes.Do I need LangGraph, Temporal, or another workflow engine?Not always. For simple agents, a database, queue, event log, and clear state machine may be enough. Frameworks and workflow engines become more valuable when tasks are long-running, approval-heavy, side-effecting, or business-critical.What should I checkpoint in an AI agent?Checkpoint the task goal, status, completed steps, important decisions, changed artifacts, pending approvals, budget, current policy, and next safe action. Do not treat a generic chat summary as a complete checkpoint.How do durable agents prevent duplicate actions?They use idempotency keys, operation ledgers, external IDs, approval gates, and retry policies. Before repeating a side-effecting tool call, the runtime checks whether the same operation already succeeded or is still pending.Is chat memory still useful?Yes, but it should not be the system of record. Chat memory is useful for conversational continuity. Durable task state, event logs, and workspace artifacts are better for recovery, auditability, and safe execution.What is the best first step toward durable agents?Give every task a stable ID, persist task status, and wrap side-effecting tools with an event log and idempotency key. Those three changes immediately make failures easier to inspect and retries safer.Sources and Further ReadingFor implementation details, review the official documentation for the OpenAI Agents SDK, LangGraph persistence, Cloudflare long-running agents, Temporal durable execution, and Restate.Durable AI Agents: How to Build Long-Running Workflows That Survive Crashes, Restarts, and Real… was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.