Skip to content

Durable Execution

Pydantic AI agents run durably, surviving crashes and restarts, on Temporal, DBOS, Prefect, Restate, Hatchet, AWS Lambda, Absurd, pgtask, Azure Durable Task and Apache Airflow.

Use durable execution in production when a run in flight has to survive its process stopping, through a deploy, a crash or a transient API failure, or when a workflow waits hours or days for a person or another system. A durable engine journals the agent’s model requests and the tool calls it wraps, and a restarted run replays the completed ones from the journal and retries the one in flight. Which tool calls (function tools, MCP servers) an engine wraps for you and how it delivers streaming differ per engine; each page below says.

Pydantic AI supports ten durable execution engines, plus a builder for any other engine. Each page below has a complete example:

EngineInstallMake an agent durable with
Temporalpydantic-ai-slim[temporal]TemporalDurability from pydantic_ai.durable_exec.temporal
DBOSpydantic-ai-slim[dbos]DBOSDurability from pydantic_ai.durable_exec.dbos
Prefectpydantic-ai-slim[prefect]PrefectDurability from pydantic_ai.durable_exec.prefect
Restaterestate_sdk[serde]RestateAgent from restate.ext.pydantic
Hatchetpydantic-ai-slim[hatchet]HatchetDurability from pydantic_ai.durable_exec.hatchet
AWS Lambdapydantic-ai-harness[aws-lambda]AWSLambdaDurability from pydantic_ai_harness.aws_lambda
Absurdpydantic-ai-harness[absurd]AbsurdDurability from pydantic_ai_harness.absurd
pgtaskpydantic-ai-harness[pgtask]PGTaskDurability from pydantic_ai_harness.pgtask
Azure Durable Taskpydantic-ai-harness[azure-durable-task]AzureDurableTaskDurability from pydantic_ai_harness.azure_durable_task
Apache Airflowapache-airflow-providers-common-aiAgentOperator(..., durable=True) from airflow.providers.common.ai.operators.agent

Temporal, DBOS, Prefect, Restate, and AWS Lambda are co-maintained by the Pydantic and vendor teams. AWS Lambda, Absurd, pgtask, and Azure Durable Task ship in Pydantic AI Harness; Restate and Airflow ship in the engine’s own package.

Batched model requests are recorded differently on each engine: see that section before batching under durable execution.

Capability authors can also move custom hook work into engine activities, steps, or tasks with durable capability operations.

Some capabilities can’t survive replay at all, such as the harness’s CDPBrowser, PlaywrightBrowser, Peers and IPythonCodeMode. Each says why in its durable_unsupported_reason, and the agent raises a UserError naming the capability and the engine: before anything binds, for a capability the agent is built with, deferred ones included, and likewise when a run or override(capabilities=...) adds the durability capability, and when a run starts in the workflow or flow, for a capability the run adds, as a capability function or DynamicCapability too. The deprecated wrapper agents, such as TemporalAgent, refuse them the same way, when they wrap an agent and when a run starts in their workflow or flow.

Append-on-change instructions derive their baseline and replacements from persisted history. Instruction callbacks still follow the engine’s replay rules: use a durable operation for external reads so replay uses the same values and produces the same history shape.

Third-party runtime authors can use the stable durable execution backend builder to integrate another engine without importing Pydantic AI internals.

Harness workspace capabilities such as Coder, Shell, and FileSystem also run inside a durable agent; the workspace guide shows how, and what works on each engine.

Enqueueing and emitting from a durable unit

When an engine runs a tool call or a capability’s durable operation in a durable unit, the unit’s recorded result carries what it enqueued with ctx.enqueue() and emitted with ctx.emit(). Code in the workflow queues those messages when the unit completes, on the first run and again on every replay, so a replayed run sees the same messages as the run that recorded them. Events work the same way, except on a first run where the engine runs the unit in the run’s own process (DBOS, Prefect, and the in-process harness engines): there, an event is still delivered live while the unit runs, as outside durable execution, and isn’t emitted again when the unit completes. A replay, a cache hit, or a unit that runs on another worker, such as a Temporal activity, emits the recorded events when the unit completes. A message a tool enqueues still goes next to that tool’s result. A tool that runs in workflow code doesn’t need this: for example, a DBOS function tool, or a tool with durable=False (see below). Its calls reach the run directly.

This has four consequences:

  • An event emitted inside a unit that runs on another worker, such as a Temporal activity, reaches the event stream when the unit completes, not while it runs. It still arrives before the tool’s result.
  • If the process crashes after a unit delivered an event live but before the engine recorded the unit’s result, the engine runs the unit again, so that event can be delivered twice. That’s the same at-least-once delivery as before events were recorded.
  • Only a unit whose result the engine records counts. If an attempt fails, its messages are dropped with it, and so are its events when the unit runs on another worker. That includes a durable operation that raises, and a tool that raises an error other than a control-flow exception like ModelRetry. On engines that run the unit in the run’s own process, a failed or retried attempt has already delivered its events live, as described for a crash above. A sub-agent run inside a unit keeps its own messages and events, as it would outside durable execution.
  • An event whose class is dispatched immediately (dispatch='immediate') can’t wait for the unit to complete, because its listeners have to answer before emit returns. Inside a unit, it isn’t recorded: it’s delivered live on engines whose units run in the run’s own process, and refused on the others.

When parallel tool calls run in durable units, the messages their units carry, and what’s enqueued for a call from the run itself, such as by an after_tool_execute hook, are queued in the order of the calls in the model response, not the order the units complete, so a replay queues them in the same order. A unit’s result is complete once its body returns: a task the body started without awaiting it can’t enqueue into it later, so ctx.enqueue() from such a task raises a UserError, as does ctx.emit() from it on a unit that runs on another worker.

Other durable units don’t carry messages. These include an event_stream_handler’s unit, a model request’s unit, and the units of the deprecated DBOSAgent and PrefectAgent wrappers. Calling ctx.enqueue() inside them raises a UserError. So do ctx.dequeue() and ctx.set_enqueue_priority() inside any durable unit.

Running a tool outside the durable unit

An engine runs each function tool call in a durable unit (an activity, step or task) so a restarted run reuses its recorded result. To run a tool in the workflow code itself instead, set durable=False on it, as you would sequential or timeout: on @agent.tool, Tool(...), @toolset.tool or a FunctionToolset for all its tools. The tool then runs again on every replay, so keep it deterministic: no I/O, clock or randomness of its own. What it does through a workspace call or a durable agent’s run is still recorded, unit by unit. Use it for a tool that has to see live run state, or that starts work which should be recorded step by step rather than as one unit:

durable_opt_out.py
from pydantic_ai import Agent, RunContext
from pydantic_ai.capabilities import LocalWorkspace
from pydantic_ai.durable_exec.temporal import TemporalDurability
from pydantic_ai.toolsets import FunctionToolset

toolset = FunctionToolset(id='files')


@toolset.tool(durable=False)  # (1)
async def copy_file(ctx: RunContext, source: str, destination: str) -> str:
    content = await ctx.workspace.read_bytes(source)  # (2)
    await ctx.workspace.write_bytes(destination, content)
    return f'Copied {source} to {destination}.'


agent = Agent(
    'openai:gpt-6.1-sol',
    name='files',
    toolsets=[toolset],
    capabilities=[LocalWorkspace('.'), TemporalDurability()],  # (3)
)

The same setting keeps the tool out of its durable unit on every engine.

Each workspace call is recorded as a unit of its own, so a run that restarts after the read reuses its result and only writes.

Swap in any other engine's durability capability; the tool stays the same.

To set it on function tools you don’t define yourself, such as a capability’s, change the tool definition in a prepare function or with PrepareTools. durable=True undoes an earlier durable=False, but not an opt-out in the engine’s own per-tool config, such as Temporal’s tool_activity_config:

durable_prepare_tools.py
from dataclasses import replace

from pydantic_ai import Agent, RunContext
from pydantic_ai.capabilities import PrepareTools
from pydantic_ai.durable_exec.temporal import TemporalDurability
from pydantic_ai.tools import ToolDefinition


async def keep_in_workflow(ctx: RunContext, tool_defs: list[ToolDefinition]) -> list[ToolDefinition]:
    return [replace(td, durable=False) if td.name == 'plan_next_step' else td for td in tool_defs]


agent = Agent('openai:gpt-6.1-sol', name='planner', capabilities=[PrepareTools(keep_in_workflow), TemporalDurability()])

Changing a tool’s placement on an agent that’s already deployed adds or removes a durable unit on every engine except DBOS, which doesn’t wrap function tools, so runs already in flight fail or diverge when they replay. Let them finish first, or deploy the change as a new version of the workflow. For the same reason, a prepare function that sets durable must be deterministic, like the tool itself: it has to make the same choice when the run replays.

Only async function tools can leave their durable unit this way. On a sync tool, an MCP tool or a dynamic toolset’s tool that the engine runs in a durable unit, durable=False raises a UserError when the tool is called, because those run in a thread or perform I/O. DBOS runs function tools in workflow code without wrapping them, so it doesn’t check them: keep an agent you may move to another engine to async tools.

An engine’s own metadata key wins when a tool sets it, so a tool with durable=False and metadata={'temporal': ActivityConfig(...)} still runs in a Temporal activity. Engine keys also carry the engine’s own configuration for the unit, which durable can’t express, and follow the engine’s own rules on which tools may opt out. durable=False in turn wins over per-tool config set in code, such as Azure Durable Task’s and Render Workflows’ resolve_tool_options:

EngineWhere durable=False runs the toolEngine’s own metadata key
Temporalworkflow code'temporal'
DBOSworkflow code, where DBOS already runs function tools, so it doesn’t check the field on themnone; {'dbos': {'child_workflow': ...}} selects a child workflow
Prefectflow code'prefect'
Hatchetdurable task code'hatchet'
AWS Lambdahandler code, outside any step'aws_lambda'
Azure Durable Taskorchestrator code'azure_durable_task'
Absurdtask handler code, outside any stepnone
pgtasktask code, outside any stepnone
Render Workflowsthe parent task run'render_workflows', whose False only lets a per-run toolset through; per tool, resolve_tool_options can return False

Restate and Apache Airflow ship their own integrations; see their pages for how they wrap tools.

Secrets in tool arguments

Temporal, Azure Durable Task, Render Workflows and Hatchet run a function tool in another process and send its arguments there as JSON, which writes a SecretStr, SecretBytes or Secret[T] as '**********'. So each one is sent with its value instead, and the tool gets the secret, as it would outside a durable engine. The engine stores the value in its history in plaintext, as it already stores the model response that requested the call. A secret that isn’t in that response, because a hook added it to the arguments or a validator built it, say from a reference the model passed, newly lands in history. Encrypt that history where the engine supports it, as Temporal does with a payload codec, and give a tool secrets your application owns, such as API keys, through deps or the worker’s environment rather than tool arguments, so the model never sees or chooses them. The other engines that ship in Pydantic AI and Pydantic AI Harness run a function tool in the process that validated its arguments, and pass them on unchanged. Each engine’s page says how it stores the value.

A secret’s value is sent only where the secret’s place in the argument’s JSON form can be matched to its place in the Python form. Where it can’t, the tool gets '**********', and a UserWarning names the tool and the argument, once per tool and process. That’s the case, for example, for a secret in a Json value, which is a JSON string by the time it is sent, one in a set, which has no order to match its JSON list by, one in a list or tuple in an argument with a serializer function of your own over a secret, such as a field_serializer, which could reorder it in JSON mode only, and one in an argument whose JSON form has other keys than its Python form, such as a model whose model_serializer renames its fields in JSON mode. Take such a secret as a parameter of its own. What can’t be detected is a serializer of your own that swaps the values of two keys both forms have, in JSON mode only: each field may then get the other’s secret, though never one from outside the call’s own arguments. A secret that a computed field returns isn’t an argument, as the tool computes it again, so it’s sent as '**********', without a warning.