Durable execution for agents

In one sentence

Persist the agent's state after every step so it survives crashes, deploys and multi-day human waits: resume from the last checkpoint, retry steps with idempotency keys, never re-run what already succeeded.

Analogy: A video-game save point: die in level 7 and you restart at the last checkpoint, not the title screen — and the coins you already collected aren't collected twice.

Success-then-timeout: replay restores the recorded LLM decision, and the retry reuses the step's idempotency key, so the refund happens exactly once.

How it works

  • Without it, a crash or deploy restarts from zero, re-paying LLM calls and maybe re-running side effects.
  • Engines like Temporal replay completed steps from the event history instead of re-executing them.
  • Success-then-timeout: the refund succeeded but the response was lost; an idempotency key makes the retry a no-op.
  • Durable waits pause for a human signal for days at zero compute, then resume.
  • Workflow code must be deterministic: no clock, randomness or I/O outside activities, or replay diverges.

Check yourself

Answer to mark it learned; your answers aren't scored.

Your agent runs as a Temporal workflow. After a routine worker restart, in-flight runs fail replay with non-determinism errors. The workflow code calls the LLM directly to choose each next step. What's the cause?

Go deeper

Full explanation

Durable execution makes a long-running agent survive failures. A 40-step agent that runs for 20 minutes — or waits 3 days for an approval — will meet a crash, deploy, OOM or rate limit. Without durability it restarts from zero, re-paying every LLM call and possibly re-running side effects.

The mechanism:

  • Checkpoint every step — messages, tool results and plan go to a durable store (Postgres, Temporal's event history). On restart the engine replays completed steps from the log instead of re-executing them: the trajectory is event-sourced.
  • Steps are activities — LLM and tool calls run as retriable units with timeouts and backoff; the orchestration code stays deterministic.
  • Idempotency keys — the classic trap is success-then-timeout: the refund API succeeded, the response was lost, the retry refunds again. Derive a key from workflow id + step id so a retry is a no-op (Idempotency).
  • Durable waits — pause for a human signal for days at zero compute, then resume (Human-in-the-loop & approvals).

Tools: Temporal (workflows + activities, replay), LangGraph checkpointers (state saved per super-step, keyed by thread_id), AWS Step Functions (Standard workflows run up to 1 year; .waitForTaskToken for callbacks), plus Restate, Inngest and DBOS.

The constraint: workflow code must be deterministic — no clock, randomness or I/O outside activities, or replay diverges from history.

Code Agent loop as a Temporal workflow
pythonAgent loop as a Temporal workflow
from datetime import timedelta
from temporalio import activity, workflow
from temporalio.common import RetryPolicy

@activity.defn
async def call_llm(history: list[dict]) -> dict:
    return await llm_next_step(history)  # non-deterministic, so it is an activity

@activity.defn
async def run_tool(step: dict) -> str:
    key = f"{activity.info().workflow_id}:{step['id']}"  # identical on every retry
    return await execute_tool(step, idempotency_key=key)

@workflow.defn
class AgentWorkflow:
    approved: bool | None = None
    @workflow.signal
    def approve(self, ok: bool) -> None:  # sent by the review UI, maybe days later
        self.approved = ok
    @workflow.run
    async def run(self, goal: str) -> str:
        history = [{"role": "user", "content": goal}]
        opts = dict(start_to_close_timeout=timedelta(minutes=2), retry_policy=RetryPolicy(maximum_attempts=3))
        for _ in range(30):  # step budget; completed steps replay from history
            step = await workflow.execute_activity(call_llm, history, **opts)
            if step["type"] == "final":
                return step["text"]
            if step["risky"]:  # durable wait: no worker or thread is held
                await workflow.wait_condition(lambda: self.approved is not None)
                if not self.approved:
                    return "Rejected by reviewer"
                self.approved = None
            result = await workflow.execute_activity(run_tool, step, **opts)
            history += [step["message"], {"role": "user", "content": result}]
        return "Step budget exhausted"
Real example

A procurement agent gathers 3 quotes, drafts a purchase order, waits for a manager's approval, then submits it to the ERP. On Temporal, each LLM and tool call is an activity with a 2-minute timeout and 3 retries. The manager approves after 2 days; meanwhile 4 deploys restarted the workers, and the workflow resumed from its event history without re-calling the LLM. The ERP call timed out after actually creating PO-881; the retry carried the same idempotency key, so the ERP returned PO-881 instead of creating a duplicate.

Trade-offs +3 · −3

+ You gain

  • A crash or deploy costs one step, not the whole run and its LLM spend.
  • Human approvals can take days with zero compute held.
  • Full event history: replay, debug and audit any run step by step.

− You pay

  • Determinism discipline: no clock, randomness or I/O in workflow code, or replay breaks.
  • Another platform to run or pay for: a Temporal cluster, Step Functions state transitions.
  • Long transcripts bloat history and hit payload limits; store blobs outside and pass references.

Use it when

Agents that run minutes to days, have side effects (payments, tickets, emails), wait on humans or external callbacks, or are expensive enough that restarting from zero hurts.

Avoid it when

Short, read-only, chat-style agents that finish in seconds: retrying the whole request is cheaper than running a workflow engine.

Numbers to know 4
  • AWS Step Functions: Standard workflows run up to 1 year; Express workflows up to 5 minutes.
  • Step Functions caps each state's input/output at 256 KB: keep transcripts in S3 and pass pointers.
  • Temporal: event history caps at 51,200 events or 50 MB per execution; use Continue-As-New for long agents.
  • Stripe may drop idempotency keys after 24 hours: a retry window, not a forever guarantee.
Common pitfalls 4
  • Calling the LLM or datetime.now() directly in workflow code: replay takes a different path and fails.
  • Retrying side-effecting tools without idempotency keys: duplicate refunds, emails and tickets.
  • Checkpointing only at the end: a crash at step 39 of 40 loses everything.
  • Deploying changed workflow code under in-flight runs without versioning: old histories stop replaying.
Interview questions 2

Answer out loud first, then reveal.

Your agent crashes at step 30 of 40, right after charging a customer. What should happen on restart?Show answer

It should resume at step 30, not step 1, and must not charge again. I run the agent as a durable workflow: every LLM and tool call is an activity whose result is recorded in an event log, so on restart completed steps replay from history instead of re-executing. The charge carries an idempotency key derived from workflow id plus step id, so if it succeeded but the response was lost, the retry returns the original charge. Without both pieces you either redo expensive work or double-charge.

Temporal, LangGraph checkpointers or Step Functions: how do you choose?Show answer

By where the agent lives, how long it runs and what it touches. For a LangGraph app with human pauses of hours, its Postgres checkpointer is the simplest thing that works. If the agent runs for days, moves money or calls many services, I want a durable-execution engine like Temporal, whose replay model handles retries, timers and signals properly. If we're all-in on AWS and the flow is mostly fixed steps, Step Functions with task-token callbacks is fine. The trade-off is operational cost versus guarantees.