What happens when your AI agent fails on step 3? Durable execution for agents
By Rishabh Maurya, co-founder of BuildKodiq ยท 2026-11-30
If an AI agent crashes on step 3 of 4, one of two things usually happens. Either it starts again from step 1 and repeats what it already did (a second email to the same customer, a duplicate CRM record, another charge), or it stops and leaves steps 1 and 2 half-finished with nobody noticing.
The fix is to run the agent as a durable workflow: every model call and tool call is a recorded step, a crash resumes from the last finished step, and any step with side effects uses an idempotency key so a retry can't do it twice.
This is the same problem as any long, multi-step process. It shows up faster with agents because they call slow, rate-limited models and real tools, often many times per task.
What actually goes wrong when an agent fails halfway
An agent that does real work is a loop: ask the model what to do, run a tool, add the result, ask again. A task like "qualify this lead and book a call" might be eight or ten turns of that loop, spread over minutes.
Things that break it:
- The model API returns a rate-limit error or times out.
- A tool's API is down for a minute.
- The server running the agent restarts, or you deploy new code.
- The agent waits for a person (an approval, a reply) and the process holding that state goes away.
Without anything recording progress, the code has two bad choices: start over, or give up. Starting over repeats every side effect that already happened. Giving up leaves partial work behind: a record created but never finished, a follow-up that never goes out.
We saw exactly this on a client project before we moved it to Temporal: multi-step automations failed halfway and had to be restarted by hand.
Why adding retries doesn't fix it
The usual first fix is a try/except with a retry around the whole task. That makes it worse: retrying the whole task re-runs the steps that already succeeded. Retrying only the failed call is better, but the retry lives in memory, so a restart still loses it, and nothing knows which steps already ran.
What you need is a record, outside the process, of which steps finished and what they returned.
Durable execution in one paragraph
A durable execution engine (Temporal, Inngest and DBOS are the common ones) records the result of each step as it finishes. If the process dies, another worker picks the task up, replays the recorded results instead of re-running those steps, and carries on from the first step that hadn't finished. Each step gets its own timeout and retry policy. A task can also wait, for seconds or for days, without a process sitting in memory.
The agent loop as a Temporal workflow
Here is the shape we use, as a short Python sketch. The workflow holds the loop; each model call and each tool call is an activity, so its result is recorded.
from datetime import timedelta
from temporalio import workflow
from temporalio.common import RetryPolicy
with workflow.unsafe.imports_passed_through():
from .activities import call_model, run_tool
NEEDS_APPROVAL = {"send_email", "issue_refund"}
@workflow.defn
class AgentWorkflow:
def __init__(self) -> None:
self.approved: bool | None = None
@workflow.signal
def approve(self, ok: bool) -> None:
self.approved = ok
@workflow.run
async def run(self, task: str) -> str:
messages = [{"role": "user", "content": task}]
for step in range(20): # hard cap on turns
reply = await workflow.execute_activity(
call_model,
messages,
start_to_close_timeout=timedelta(minutes=2),
retry_policy=RetryPolicy(
maximum_attempts=5,
non_retryable_error_types=["BadRequest"]
),
)
if reply["type"] == "final":
return reply["text"]
if reply["tool"] in NEEDS_APPROVAL:
self.approved = None
await workflow.wait_condition(lambda: self.approved is not None)
if not self.approved:
messages.append({"role": "user", "content": "Not approved. Stop and summarise."})
continue
key = f"{workflow.info().workflow_id}-{step}"
result = await workflow.execute_activity(
run_tool,
args=[reply["tool"], reply["args"], key],
start_to_close_timeout=timedelta(minutes=5),
retry_policy=RetryPolicy(maximum_attempts=3),
)
messages.append({"role": "tool", "content": result})
return "Stopped: too many steps"
What this gives you:
- A crash on step 3 resumes at step 3. Steps 1 and 2 are replayed from the record, not re-run, so the model isn't called again and no tool runs twice.
- Each step has its own timeout and retries. A slow model call doesn't hold up the whole task, and a rate-limit error is retried with backoff.
- Approvals cost nothing while they wait. The workflow pauses on a signal until someone approves, whether that's ten seconds or two days. Nothing polls a status column. We use the same pattern on SpotBeam, where an order waits for a client to re-upload a broken file.
- There is a hard cap on turns, so a confused agent can't loop forever and run up model costs.
Make every side effect safe to repeat
Durable execution guarantees a step won't be re-run after it finished. But a step can fail after the side effect happened and before its result was saved, for example when the network drops right after an email is sent. Then the step is retried and the side effect happens twice.
So every tool that changes something outside your system takes an idempotency key. In the sketch it's the workflow ID plus the step number, which stays the same across retries:
- Payments: pass it as Stripe's
Idempotency-Keyheader. Stripe returns the first result instead of charging again. - Database writes: upsert on the key instead of inserting.
- Emails and messages: store the key with the message, and skip sending if it's already there.
Retries for model calls: let one layer do it
Model SDKs often retry on their own. If the workflow also retries, the attempts multiply: three SDK retries inside five workflow retries is fifteen calls. Pick one layer. We turn the SDK's retries off and let the workflow's retry policy handle rate limits, timeouts and server errors, because the workflow's retries survive a restart and show up in its history.
Don't retry errors that won't change: a malformed request or a prompt the model refuses will fail the same way every time. Mark those as non-retryable (the BadRequest type in the sketch) and handle them in the loop.
Keep big data out of the workflow
Everything a step returns is stored in the workflow's history, and Temporal limits how big that history and each payload can be. Long transcripts, documents and search results belong in your database or object storage. Pass their IDs between steps, not the content.
Doesn't have to be Temporal
The same ideas work in Inngest (each step.run is recorded and retried) and DBOS (steps are checkpointed in Postgres). We compared the three for small teams in Temporal vs Inngest vs DBOS. The choice matters less than making the agent's steps recorded, retryable and idempotent.
When you don't need this
A chat reply, a single model call or a quick classification doesn't need a workflow engine. If the whole thing can safely run again from scratch, a normal background job is simpler.
Reach for durable execution when an agent:
- takes several steps and calls outside systems,
- changes things that must not happen twice (emails, payments, records),
- runs for minutes, hours or days, or waits for a person,
- must not be silently lost when a server restarts.
Agents like the recruiting pipeline we built (source candidates, score them, send outreach with timed follow-ups, handle scheduling) tick every box: one candidate's run spans days once follow-ups are involved.
A short checklist
- Model calls and tool calls are separate, recorded steps.
- Every step has a timeout and a retry policy; errors that won't change are non-retryable.
- Only one layer retries model calls.
- Every side effect takes an idempotency key that is stable across retries.
- Approvals are waits on a signal, not polling.
- There's a hard cap on turns.
- Large content is stored outside the workflow and passed by ID.
FAQs
What is durable execution? Running code so that each step's result is recorded as it finishes. If the process crashes, the work resumes from the last finished step instead of starting over or being lost. Temporal, Inngest and DBOS all provide it.
Can't I just save progress in my own database? You can, and for two or three steps that's fine. As steps, retries, timeouts and human waits grow, you end up writing your own workflow engine. A durable execution engine gives you that as the programming model.
Does this make my agent slower? Each step adds a small amount of overhead to record its result. For agents whose steps are model calls taking seconds, that overhead is small next to the model time.
Does it work with the OpenAI, Anthropic or LangChain SDKs? Yes. The model call goes inside an activity (or a step in Inngest or DBOS). The SDK doesn't need to know it's running in a workflow; just turn off its own retries.
Rishabh Maurya builds durable workflows and AI agents at BuildKodiq. If your agent or automation fails halfway through tasks, our case studies are at buildkodiq.com/work, or email h****@buildkodiq.com.
Originally published on buildkodiq.com. BuildKodiq is a two-engineer studio building AI agents, automation, dashboards, MVPs and websites. Questions: h****@buildkodiq.com.
Comments
No comments yet. Start the discussion.