Skip to content
AI Skills Central

Type to search Agent Skills, workflows, tutorials, tools and the glossary.

Tutorial

Make an agent survive crashes and restarts with durable execution

Build a durable AI agent with Temporal in Python: tool calls as activities, a worker you kill mid-run that resumes, retries and human approval as a signal.

By Intermediate1 h hands-on
Bookmark

Bookmarks are kept in your free account, so you can find this page again on any device.

Sign in to bookmark
Quiz at the end
On this page

In this tutorial you turn an agent loop into a Temporal workflow, so that every model call and tool call is recorded as it happens. Then you kill the worker in the middle of a refund, start it again and watch the run carry on from where it stopped, without repeating the steps it had finished and without refunding twice. You also add retries, timeouts and a human approval step that can wait for hours without holding a process open.

By the end you will understand what durable execution actually records, which code has to be deterministic and why, and what you still have to do yourself (idempotency) for side effects to be safe. Everything was run on 25 November 2026 with Python 3.12, temporalio 1.37.0 and the Temporal CLI 1.10.1 (server 1.32.2).

Why agents need this

A tool-using agent is a loop: call the model, run the tool it asks for, append the result, call the model again. In a plain Python process that loop lives in memory. If the process dies on step six of eight (a deploy, an out-of-memory kill, a laptop lid), you lose the history and the only option is to start again. Starting again is expensive, because model calls cost money, and dangerous, because some tools have already done things in the world.

Temporal splits your code in two:

Part Runs Rule
Workflow The loop and its decisions Must be deterministic. It is replayed from the recorded history after a crash.
Activities Anything that touches the outside world: model calls, APIs, files May fail and be retried. Each result is recorded once it succeeds.

When a worker restarts, Temporal replays the workflow code against the event history. Activities that already completed are not run again; their recorded results are fed back in. The loop arrives at the same point it had reached and continues.

1. Install the tools and start a server

Create a project and add the SDK:

uv init --bare --python 3.12 durable-agent
cd durable-agent
uv add "temporalio==1.37.0"

Install the Temporal CLI from the Temporal CLI setup page (Homebrew, or the archive for your platform), then start a local development server in its own terminal:

temporal server start-dev

That serves Temporal on localhost:7233 and a web UI on http://localhost:8233, with state in memory. Leave it running for the rest of the tutorial.

2. Put everything with side effects in activities

The agent handles refund requests. It has two tools, lookup_order and issue_refund, and a model call. To keep the tutorial runnable without a key, call_model is a stand-in that reads the history and returns the next step in the same shape a tool-calling model returns: a tool name and arguments, or a final answer. Step 6 shows where a real model goes.

Create activities.py:

# activities.py: everything that touches the outside world runs here
import asyncio
import json
from pathlib import Path

from temporalio import activity

LEDGER = Path("refunds.jsonl")
ORDERS = {
    "A100": {"total": 40.0, "days_since_delivery": 5},
    "A150": {"total": 120.0, "days_since_delivery": 2},
    "A200": {"total": 350.0, "days_since_delivery": 3},
}


@activity.defn
async def call_model(history: list[dict]) -> dict:
    """Stand-in for an LLM call. It reads the history and returns the next step
    in the shape a tool-calling model gives you: a tool call or a final answer."""
    activity.logger.info("model call, attempt %s", activity.info().attempt)
    await asyncio.sleep(1)  # a real model call takes seconds
    done = {h["tool"] for h in history if h["role"] == "tool"}
    order_id = history[0]["content"].split()[-1]
    if "lookup_order" not in done:
        return {"tool": "lookup_order", "args": {"order_id": order_id}}
    order = json.loads(next(h["content"] for h in history if h.get("tool") == "lookup_order"))
    if "issue_refund" not in done:
        return {"tool": "issue_refund", "args": {"order_id": order_id, "amount": order["total"]}}
    return {"final": f"Refunded {order['total']:.2f} for order {order_id}."}


@activity.defn
async def lookup_order(order_id: str) -> str:
    await asyncio.sleep(1)
    return json.dumps(ORDERS[order_id])


@activity.defn
async def issue_refund(order_id: str, amount: float, idempotency_key: str) -> str:
    # A real payment API takes an idempotency key. This ledger imitates one.
    if LEDGER.exists():
        for line in LEDGER.read_text().splitlines():
            if json.loads(line)["key"] == idempotency_key:
                return "already refunded"
    await asyncio.sleep(5)  # slow on purpose, so you can kill the worker here
    with LEDGER.open("a") as f:
        f.write(json.dumps({"key": idempotency_key, "order_id": order_id, "amount": amount}) + "\n")
    return "refund issued"

Notice idempotency_key on the refund. Temporal guarantees that a completed activity is not run again, but an activity that crashed halfway (the money moved, the result was never recorded) will be retried. Only the payment system can tell those apart, which is why real payment APIs accept an idempotency key. The ledger file plays that role here.

3. Write the agent loop as a workflow

Create workflow.py:

# workflow.py: the agent loop, as a Temporal workflow
from datetime import timedelta

from temporalio import workflow
from temporalio.common import RetryPolicy

with workflow.unsafe.imports_passed_through():
    from activities import call_model, issue_refund, lookup_order

APPROVAL_LIMIT = 200.0
MAX_STEPS = 8


@workflow.defn
class RefundAgent:
    def __init__(self) -> None:
        self.approved: bool | None = None
        self.waiting = False

    @workflow.signal
    def review(self, approved: bool) -> None:
        self.approved = approved

    @workflow.query
    def waiting_for_approval(self) -> bool:
        return self.waiting

    @workflow.run
    async def run(self, request: str) -> str:
        history: list[dict] = [{"role": "user", "content": request}]
        model_retry = RetryPolicy(initial_interval=timedelta(seconds=2), maximum_attempts=5)

        for step in range(MAX_STEPS):
            decision = await workflow.execute_activity(
                call_model,
                history,
                start_to_close_timeout=timedelta(seconds=60),
                retry_policy=model_retry,
            )
            if "final" in decision:
                return decision["final"]

            tool, args = decision["tool"], decision["args"]
            workflow.logger.info("step %s: %s %s", step, tool, args)

            if tool == "lookup_order":
                result = await workflow.execute_activity(
                    lookup_order,
                    args["order_id"],
                    start_to_close_timeout=timedelta(seconds=10),
                )
            elif tool == "issue_refund":
                if args["amount"] > APPROVAL_LIMIT:
                    self.waiting = True
                    await workflow.wait_condition(lambda: self.approved is not None)
                    self.waiting = False
                    if not self.approved:
                        return f"A person declined the refund of {args['amount']:.2f}."
                key = f"{workflow.info().workflow_id}-refund"
                result = await workflow.execute_activity(
                    issue_refund,
                    args=[args["order_id"], args["amount"], key],
                    start_to_close_timeout=timedelta(seconds=30),
                    retry_policy=RetryPolicy(maximum_attempts=3),
                )
            else:
                result = f"error: unknown tool {tool}"

            history.append({"role": "tool", "tool": tool, "content": result})

        return "Stopped: step limit reached."

The decisions this file makes:

  • The loop has no side effects of its own. It only decides and calls activities. That is what makes replay safe: given the same recorded results, it takes the same path.
  • Each activity has a timeout and a retry policy. A slow model call is retried up to five times with back-off. The refund gets three attempts, not unlimited ones, because a payment that keeps failing needs a person.
  • The idempotency key comes from the workflow ID, which is stable across retries and replays. Never build it from the current time or a random number.
  • Approval is a signal. wait_condition parks the workflow until review is called. While it waits, nothing is running and no process holds the state; the server does.
  • imports_passed_through lets the workflow refer to activity functions without the sandbox re-importing their module on every replay.

4. Run a worker and start an agent

Create worker.py, which runs your code, and start.py, which asks the server to start a run:

# worker.py: runs the workflow and activity code. Kill it and start it again at will.
import asyncio
import logging

from temporalio.client import Client
from temporalio.worker import Worker

from activities import call_model, issue_refund, lookup_order
from workflow import RefundAgent


async def main() -> None:
    logging.basicConfig(level=logging.INFO, format="%(asctime)s %(message)s", datefmt="%H:%M:%S")
    client = await Client.connect("localhost:7233")
    worker = Worker(
        client,
        task_queue="refund-agent",
        workflows=[RefundAgent],
        activities=[call_model, lookup_order, issue_refund],
    )
    print("worker started")
    await worker.run()


if __name__ == "__main__":
    asyncio.run(main())
# start.py: start an agent run and wait for its answer
import asyncio
import sys

from temporalio.client import Client

from workflow import RefundAgent


async def main(order_id: str) -> None:
    client = await Client.connect("localhost:7233")
    handle = await client.start_workflow(
        RefundAgent.run,
        f"Please refund order {order_id}",
        id=f"refund-{order_id}",
        task_queue="refund-agent",
    )
    print("started", handle.id)
    print("result:", await handle.result())


if __name__ == "__main__":
    asyncio.run(main(sys.argv[1]))

Start the worker in a second terminal, then start a run for the small order in a third:

uv run worker.py
uv run start.py A100
started refund-A100
result: Refunded 40.00 for order A100.

The worker logs each step. Temporal appends a dictionary of context (workflow ID, run ID, attempt) to every log line; it is trimmed here:

14:15:42 model call, attempt 1
14:15:43 step 0: lookup_order {'order_id': 'A100'}
14:15:44 model call, attempt 1
14:15:45 step 1: issue_refund {'amount': 40.0, 'order_id': 'A100'}
14:15:50 model call, attempt 1

5. Kill the worker in the middle of a refund

This is the step that shows what durability buys. Start a run for order A150:

uv run start.py A150

When the worker logs issue_refund, kill it hard from another terminal before the five-second refund finishes. kill -9 imitates a crash: the worker gets no chance to tidy up or report back.

kill -9 $(pgrep -f "python worker.py")

The start.py process keeps waiting: the run is not lost, it has no worker. The ledger is still empty because the refund never finished. Start the worker again:

uv run worker.py

About half a minute later, start.py prints its result:

started refund-A150
result: Refunded 120.00 for order A150.

The first worker’s log had stopped at the refund:

14:17:07 model call, attempt 1
14:17:08 step 0: lookup_order {'order_id': 'A150'}
14:17:09 model call, attempt 1
14:17:10 step 1: issue_refund {'amount': 120.0, 'order_id': 'A150'}

The restarted worker logged only one line:

14:17:46 model call, attempt 1

It did not call the model twice more or look the order up again. Those results were in the history. It retried the refund, which had never completed, and then made the final model call. The ledger holds exactly one refund:

cat refunds.jsonl
{"key": "refund-A150-refund", "order_id": "A150", "amount": 120.0}

To see why the restart took about 30 seconds, read the history:

temporal workflow show --workflow-id refund-A150
   23  2026-11-25T08:47:10Z  ActivityTaskScheduled
   24  2026-11-25T08:47:41Z  ActivityTaskStarted
   25  2026-11-25T08:47:46Z  ActivityTaskCompleted

The refund was scheduled at 08:47:10 and started again at 08:47:41. The server had no way to know the first worker had died, so it waited for the activity’s 30-second start_to_close_timeout before handing it to the new worker. Pitfalls below show how to detect a dead worker sooner.

6. Ask a person before a large refund

Order A200 is over the 200 limit, so the workflow will wait for a signal. Create approve.py:

# approve.py: a person answers the approval request
import asyncio
import sys

from temporalio.client import Client

from workflow import RefundAgent


async def main(workflow_id: str, answer: str) -> None:
    client = await Client.connect("localhost:7233")
    handle = client.get_workflow_handle(workflow_id)
    print("waiting for approval:", await handle.query(RefundAgent.waiting_for_approval))
    await handle.signal(RefundAgent.review, answer == "yes")
    print("sent:", answer)


if __name__ == "__main__":
    asyncio.run(main(sys.argv[1], sys.argv[2]))

Start the run, and once the worker has logged the refund step, answer it:

uv run start.py A200
uv run approve.py refund-A200 yes
waiting for approval: True
sent: yes

And in the first terminal:

started refund-A200
result: Refunded 350.00 for order A200.

The history now contains a WorkflowExecutionSignaled event. The approval could have come a minute or a week later; nothing was running while the workflow waited. In a real system approve.py is a button in a review tool that calls the same signal. Human approval for agent actions covers what the person should be shown before they decide.

What the workflow may and may not do

Workflow code is replayed, so it has to make the same decisions every time it sees the same history. Inside a workflow:

  • Do not call a model, an API, the file system or the clock directly. Put it in an activity. For time, use workflow.now(); for waiting, asyncio.sleep inside a workflow is turned into a durable timer by the SDK.
  • Do not use random or uuid4 for anything that affects decisions. Use workflow.uuid4() or derive values from the workflow ID.
  • Do keep payloads small. Temporal’s default limits warn at 512 KB per payload and fail at 2 MB, and terminate a workflow whose history passes 50 MB or 51,200 events (Temporal defaults). An agent that appends whole web pages to history will hit them. Store large tool results elsewhere and pass a reference.

If you would rather not write the loop yourself, Temporal maintains an integration with the OpenAI Agents SDK that runs model calls as activities for you (Temporal docs). Agent frameworks compared lists which frameworks have durable execution built in.

Pitfalls

The restart took 30 seconds and you thought it had hung. The server only learns a worker is gone when the activity’s timeout expires. For long activities, set heartbeat_timeout on execute_activity and call activity.heartbeat() inside the activity; a missed heartbeat lets the server retry within seconds instead of waiting for the full start_to_close_timeout.

A refund was issued twice after a crash. Durable execution stops completed activities from running again. It cannot stop an activity that crashed after the money moved from being retried. Every activity with a side effect needs an idempotency key that is stable across retries, such as the workflow ID plus the step.

Your kill command killed the wrong process. pkill -f and pgrep -f match the full command line of every process. In a script, that includes the shell running the script if its own command line contains worker.py. Check what pgrep -f "python worker.py" returns before you kill it, or note the worker’s process ID when you start it.

Replay fails with a non-determinism error after you edit the workflow. Changing the order of activities in workflow code while runs are in flight means the replayed code no longer matches the history. Let old runs finish, or use Temporal’s versioning APIs, before changing the loop’s shape.

start.py fails with “workflow execution already started”. Workflow IDs are unique among running workflows. Use one ID per real-world job, such as the order ID, which also stops two refunds for one order running at once.

History grows until the workflow is terminated. Appending full tool results to history on every step makes payloads and history large. Keep the conversation short, summarise, or store results outside and pass IDs.

Next steps

Covers

Check your understanding

Durable agents with Temporal quiz

Workflows and activities, replay after a crash, idempotency keys, retries and timeouts, approval as a signal, determinism rules, payload limits and heartbeats.

8 questions · pass mark 70%

Question 1 of 80 answered
  1. In the Temporal version of the agent, where does the model call go?
Back to top