Durable Execution with Hatchet
Hatchet is a platform for running background tasks and durable workflows on your own workers, natively integrated with Pydantic AI.
A Hatchet durable task records what it does in an event log: each child task it spawns and the result it got back, each durable sleep, each recorded value. When a durable task is retried, evicted or reset, Hatchet runs its code again from the start and hands it the recorded results instead of spawning the child tasks again, checking each against the one it recorded, input included.
HatchetDurability runs an agent’s model requests, MCP communication and tool calls as child tasks, so a durable task that runs the agent picks up where it left off. The agent’s own loop runs in the durable task and is deterministic, so it replays to the same point.
+------------------+ spawn child task +----------------------+
| Durable task | ----------------------------> | Child task |
| (agent.run) | | (model request, |
| | <---------------------------- | tool call, MCP) |
+------------------+ recorded result +----------------------+
| |
v v
+----------------------------------------+ [External APIs, services, databases]
| Hatchet engine: event log, queues, |
| retries, dashboard |
+----------------------------------------+
A child task runs on whichever worker serves it, so the worker that runs the durable task doesn’t have to be the one that runs its model requests and tools.
See the Hatchet documentation for more information.
Install Pydantic AI with the Hatchet extra:
pip install 'pydantic-ai-slim[hatchet]'
uv add 'pydantic-ai-slim[hatchet]'
The extra installs hatchet-sdk 2.0, which needs a Hatchet engine of v0.80.0 or later.
Attach HatchetDurability to the agent, call the agent from a durable task, and pass the capability’s workflows to the worker alongside that task:
from hatchet_sdk import DurableContext, Hatchet
from pydantic import BaseModel
from pydantic_ai import Agent
from pydantic_ai.durable_exec.hatchet import HatchetDurability
hatchet = Hatchet()
durability = HatchetDurability(hatchet) # (1)
agent = Agent('openai:gpt-6.1-sol', name='geography', capabilities=[durability]) # (2)
class Question(BaseModel):
question: str
class Answer(BaseModel):
answer: str
@hatchet.durable_task(name='answer_question', input_validator=Question)
async def answer_question(input: Question, ctx: DurableContext) -> Answer:
result = await agent.run(input.question) # (3)
return Answer(answer=result.output)
worker = hatchet.worker('agent-worker', workflows=[answer_question, *durability.workflows]) # (4)
if __name__ == '__main__':
worker.start() The capability registers the agent's child tasks on hatchet when it's attached to an agent.
The agent's name goes into every task name, so it has to be unique among the agents on a Hatchet tenant and stay the same across deploys.
Inside a durable task, each model request and tool call is spawned as a child task. Outside one, the capability is transparent and the agent runs in-process as usual.
A worker needs the child tasks registered to serve them; any worker on the same tenant can.
Construct the agent at module level or in worker setup code, not inside the durable task: its tasks have to be registered with the worker before the task runs, so attaching HatchetDurability inside a durable task raises a UserError.
Task inputs and outputs are JSON, so the agent’s deps, model_settings, the RunContext metadata and tool_call_metadata, and tool metadata must be serializable with Pydantic’s TypeAdapter. Pass deps_type to HatchetDurability if it differs from the agent’s own.
A tool’s child task gets a HatchetRunContext with the fields that cross the task boundary. To carry another field, subclass it with your own serialize_run_context and pass it as run_context_type.
The model request, tool, MCP and capability tasks are registered on the Hatchet tenant like any other task, so anyone with an API token for the tenant can run one directly, choosing its input: the tool arguments, deps and the serialized run context. That skips the checks your durable task makes before agent.run() and the ones the agent loop makes before it calls a tool. Give tenant API tokens only to callers you trust with the worker’s tools and credentials, and don’t rely on checks in the durable task to authorize a tool call.
Hatchet keeps task inputs and outputs, including prompts, model responses, tool arguments and results, and deps, in its event log. Read credentials from the worker’s environment rather than passing them in deps.
A Model instance can’t be serialized into a task. Register the models a run may switch to with models= and refer to them by key; model name strings cross as written and are built on the worker.
durable=False on an async function tool runs it in the durable task itself instead of a child task; see Running a tool outside the durable unit. A tool’s 'hatchet' metadata can also be False for the same effect.
Tool calls still run in parallel in a durable task, but their events are emitted in call order once they’ve all finished, as a replay gets their results back in another order than they finished in. Run the agent in parallel_tool_call_execution_mode('sequential') to run them one at a time instead.
A run’s timeout= counts from the time the durable task first started the run, which its event log records, so a replayed run keeps the deadline it started with.
event_stream_handler sees the run’s events: model events are handled live inside the model request task, and every other event in a task of its own that the durable task spawns.
To observe a run from outside the durable task, as it happens or afterwards, pass event_stream=True (or a HatchetEventStream) to publish its events to a Hatchet durable stream topic, one per durable task and agent by default. Durable streams must be enabled for the Hatchet tenant: publishing to one without them raises a UserError. stream_agent_events() subscribes to it with the durable task’s workflow run ID and yields the events typed and in order, ending with the AgentRunResultEvent that carries the result:
durability = HatchetDurability(hatchet, event_stream=True)
agent = Agent('openai:gpt-6.1-sol', name='geography', capabilities=[durability])
ref = await answer_question.aio_run(Question(question='What is the capital of France?'), wait_for_result=False)
async for event in durability.stream_agent_events(ref.workflow_run_id):
print(event)
Model events are published from the model request task that produces them, so tokens stream through while the model responds. A replayed durable task publishes its events again, and the iterator yields each one once. A model request task that Hatchet retries publishes its events again under new IDs, so the iterator yields the failed attempt’s partial response before the retry’s. When the server hangs up an idle subscription, as while the run waits on a long tool call, the iterator subscribes again after the last event it read. Subscriptions that keep ending at once without an event, as when the tenant’s durable streams are turned off, are retried after a wait that doubles from 0.1 up to 5 seconds, and after 20 in a row the iterator raises a UserError naming the topic. If the run fails, including by its timeout=, the iterator ends early and its error holds the name of the exception’s class, but not its message, which can carry a provider’s error body. A run that fails while the durable task has retries left publishes no error, as the retry’s run publishes the outcome: if your durable task catches the run’s error instead of failing, give it no retries, or the iterator waits for the outcome of the task’s next agent run, if any, and reports that.
task_config is the base HatchetTaskConfig for every task, by default a 60-second execution_timeout and no retries. model_task_config, event_stream_handler_task_config and toolset_task_config (keyed by toolset ID) are merged on top of it:
from datetime import timedelta
from hatchet_sdk import RateLimit
durability = HatchetDurability(
hatchet,
task_config={'execution_timeout': timedelta(minutes=2)},
model_task_config={'retries': 3, 'backoff_factor': 2},
toolset_task_config={'search': {'rate_limits': [RateLimit(static_key='search-api', units=1)]}},
)
Hatchet registers each task once, so registration options like retries, execution_timeout and rate_limits can only vary per toolset. A tool’s 'hatchet' metadata can override the run options, which apply each time its task is spawned: priority, sticky, desired_worker_labels and additional_metadata.
from hatchet_sdk import DesiredWorkerLabel
@toolset.tool(metadata={'hatchet': {'desired_worker_labels': [DesiredWorkerLabel(key='gpu', value='true')]}})
async def transcribe(audio_url: str) -> str: ...
A model request task retries model errors as its retries allow, waiting as long as the provider’s Retry-After asks, up to a minute, on Hatchet engine v0.111.0 or later. non_retryable_model_errors lists the errors another attempt of the same request can’t fix, which fail the task without a retry; by default ModelRequestRejectedError, ModelQuotaExceededError and ModelRequestTimeout. Either way, the durable task receives a ModelAPIError as the Pydantic AI class the model raised, so ModelFallback and on_model_request_error hooks handle it as they would outside durable execution.
When the agent is built with RetryOnModelErrors, that capability retries model errors in the durable task, waiting on a durable sleep, and the model request task treats every model error as non-retryable, so the two don’t multiply each other’s attempts. Its retries still cover worker crashes and timeouts. A non_retryable_model_errors other than the default is then ignored, with a UserWarning. The model request task’s retries are set when HatchetDurability binds to the agent, so add RetryOnModelErrors to the agent’s capabilities: one that only a DynamicCapability returns for the run raises a UserError inside a durable task.
A UserError, or a result that can’t be serialized, fails a task the same way on every attempt, so it’s never retried.