AI agent failure recovery: retries, checkpoints and idempotency keys

AI agent platforms that handle failure recovery include Trigger.dev, Temporal and LangGraph. An agent that runs for three days can hit a 429, lose a worker and get deployed over. Recovering from that means knowing, for every line of your agent, whether it runs again.

A model call that runs twice costs tokens. An email or a card charge that runs twice costs you a customer's trust. This guide follows one TypeScript agent on Trigger.dev through a rate limit, a crash, a retry, a three-day wait and an email, and shows what runs again at each step and what stops it doing harm.

Trigger.dev publishes this page, and the comparison with Temporal and LangGraph near the end says where each of them is the better fit.

TL;DR

  • Trigger.dev is the open source platform for durable AI agents and workflows in TypeScript. It retries failed attempts with backoff, checkpoints runs while they wait, and records every attempt in the run trace (errors and retrying).
  • A Trigger.dev retry restarts run() from the top. Checkpoint-resume during a wait (wait.for, triggerAndWait, waitpoint tokens) restores the process where it paused, so code before the wait doesn't run again (how it works).
  • Trigger.dev idempotency keys (idempotencyKey on trigger, idempotencyKeys.create) stop a retry from triggering a subtask twice and return the finished subtask's result. They don't make the code inside run() idempotent (idempotency).
  • An email or a charge also needs the provider's own idempotency key, because only the provider can deduplicate its own API call. None of this is exactly-once execution; the keys make a repeat harmless (idempotency).
  • chat.agent recovers conversations a different way: a new run rebuilds the transcript from a saved snapshot plus a replay of the session streams (persistence and replay).
  • AI agent platforms that handle failure recovery include Trigger.dev (retries plus keyed subtasks and waits), Temporal (replay of the workflow's event history) and LangGraph (an agent framework with a checkpoint per graph step, which runs inside a runtime like the first two or on LangChain's Agent Server), and this page compares those three. Use Temporal for polyglot teams or if you already run it, LangGraph for graph-shaped agents in Python or TypeScript, and Trigger.dev for TypeScript agents you want run without managing workers.

An example follow-up agent

This agent drafts a sales follow-up with Claude, emails it, waits three days, and sends one more if the lead hasn't replied. It uses @trigger.dev/sdk v4, the AI SDK and Resend. getLead and hasReplied are your own data access.

// trigger/follow-up-agent.ts
import { AbortTaskRunError, idempotencyKeys, SubtaskUnwrapError, task, wait } from "@trigger.dev/sdk";
import { anthropic } from "@ai-sdk/anthropic";
import { APICallError, RetryError, generateText } from "ai";
import { Resend } from "resend";
import { getLead, hasReplied } from "@/lib/crm";

const resend = new Resend(process.env.RESEND_API_KEY);

// The AI SDK retries transient errors like 429 and 5xx twice by default, then wraps the last error in a RetryError.
function apiCallError(error: unknown) {
  const inner = RetryError.isInstance(error) ? error.lastError : error;
  return APICallError.isInstance(inner) ? inner : undefined;
}

export const draftFollowUp = task({
  id: "draft-follow-up",
  retry: { maxAttempts: 5, factor: 2, minTimeoutInMs: 2_000, maxTimeoutInMs: 60_000, randomize: true },
  catchError: async ({ error }: { error: unknown }) => {
    const apiError = apiCallError(error);
    if (!apiError) return; // not a model error: use the retry settings above
    if (!apiError.isRetryable) return { skipRetrying: true }; // 400, 401, 403: retrying won't help
    const retryAfter = Number(apiError.responseHeaders?.["retry-after"]);
    if (apiError.statusCode === 429 && retryAfter > 0) {
      return { retryAt: new Date(Date.now() + retryAfter * 1_000) };
    }
  },
  run: async (payload: { leadId: string; step: number }) => {
    const lead = await getLead(payload.leadId);
    // Fails the run now, with no retries
    if (!lead) throw new AbortTaskRunError(`Lead ${payload.leadId} not found`);

    const { text } = await generateText({
      model: anthropic("claude-sonnet-5-5"),
      system: "You write short, friendly sales follow-ups. Plain text, under 120 words.",
      prompt: `Follow-up #${payload.step} to ${lead.name} at ${lead.company}. Notes: ${lead.notes}`,
    });

    return { subject: `Following up, ${lead.company}`, body: text };
  },
});

export const sendFollowUp = task({
  id: "send-follow-up",
  retry: { maxAttempts: 5 },
  run: async (payload: { leadId: string; step: number; to: string; subject: string; body: string }, { ctx }) => {
    const { data, error } = await resend.emails.send(
      { from: "Sales <[email protected]>", to: payload.to, subject: payload.subject, text: payload.body },
      // The run ID is the same on every retry of this run and new on a replay.
      // Resend keeps the key for 24 hours and returns the original email instead of sending again.
      { idempotencyKey: `follow-up/${ctx.run.id}` }
    );
    if (error) throw new Error(`Resend: ${error.message}`);
    return { emailId: data.id };
  },
});

export const followUpAgent = task({
  id: "follow-up-agent",
  // A crash fails the attempt like an error does; an out-of-memory crash retries on a bigger machine
  retry: { maxAttempts: 3, outOfMemory: { machine: "medium-2x" } },
  // A child that failed has used its own retries and its key is cleared, so a parent retry would start it again
  catchError: async ({ error }: { error: unknown }) => {
    if (error instanceof SubtaskUnwrapError) return { skipRetrying: true };
  },
  run: async (payload: { leadId: string; email: string; waitMinutes?: number }) => {
    for (const step of [1, 2]) {
      // Run-scoped by default: every attempt of this run gets the same keys
      const draftKey = await idempotencyKeys.create(`draft-${step}`);
      const waitKey = await idempotencyKeys.create(`wait-${step}`);
      // Global: one send per lead and step, even if the run is replayed
      const sendKey = await idempotencyKeys.create(["send", payload.leadId, String(step)], { scope: "global" });

      const draft = await draftFollowUp
        .triggerAndWait({ leadId: payload.leadId, step }, { idempotencyKey: draftKey })
        .unwrap();

      await sendFollowUp
        .triggerAndWait({ ...draft, leadId: payload.leadId, step, to: payload.email }, { idempotencyKey: sendKey })
        .unwrap();

      // Checkpointed while it waits. On a retry, a wait that already finished returns immediately.
      await wait.for({ minutes: payload.waitMinutes ?? 3 * 24 * 60, idempotencyKey: waitKey });

      if (await hasReplied(payload.leadId)) return { status: "replied", step };
    }

    return { status: "no-reply" };
  },
});

The model call and the email are separate tasks for a reason. Each gets its own retry policy, each shows up as its own run in the dashboard, and each can be deduplicated by an idempotency key when the parent retries. That's the pattern our docs call durable execution: break the work into subtasks, give each one a key, and a retry of the parent reuses the results it already has.

What happens when an AI agent run fails on Trigger.dev?

Here's the run above meeting a rate limit and a crash on its way through step 1.

MomentWhat goes wrongWhat Trigger.dev doesWhat runs again
Drafting, attempt 1Anthropic returns 429The AI SDK retries twice in-process, then catchError schedules the next attempt for the retry-after timeOnly draft-follow-up's run(). The parent is checkpointed, waiting on it
Drafting, attempt 2NothingStores the draft as the child run's outputNothing
SendingNothingResend accepts the email; its ID is the child run's outputNothing
Just after sendingThe worker dies (a crash, a node eviction)Fails attempt 1 of follow-up-agent and queues attempt 2 on the same code versionfollow-up-agent's run(), from the top
Attempt 2NothingThe same keys find the finished draft and send runs and return their outputsNo model call, no email
The 3-day waitNothingCheckpoints the run, frees the machine, stops billingNothing. On resume the code carries on from the line after wait.for
Step 2Same as aboveSame as above, with new keys for step 2Same as above

Transient model errors (429 and 5xx)

There are two layers of retry. The AI SDK retries a failed call twice by default (maxRetries), but only for errors it marks as retryable. Once those run out, the error leaves run() and the task's retry settings take over with exponential backoff.

catchError sees the error before Trigger.dev decides what to do with it. Return nothing to use the task's settings, { skipRetrying: true } to fail now, or { retryAt } to retry at a specific time (advanced error handling). The AI SDK's APICallError carries statusCode, responseHeaders and isRetryable, which is all you need to tell a rate limit from a bad API key.

For errors no retry can fix, like a lead that doesn't exist, throw AbortTaskRunError. It fails the run straight away.

A child that fails for good still has to get past the parent. .unwrap() throws a SubtaskUnwrapError in follow-up-agent, and left alone the parent would retry. Trigger.dev clears the idempotency key of a failed run, so each parent attempt would trigger a fresh draft run and another model call with the same bad API key. The parent's catchError stops that: a SubtaskUnwrapError means the child already spent its own retries, so the parent fails with it. The parent's maxAttempts: 3 is for crashes and its own errors.

Worker crashes

A crash is a failed attempt. If the process exits with a non-zero code or gets SIGTERM, the run engine treats it as a retryable error and retries if attempts remain. If the machine disappears without the process exiting, the run stops sending heartbeats. After 5 minutes without one, Trigger.dev marks the run stalled and fails the attempt with TASK_RUN_STALLED_EXECUTING, which is retried the same way.

Out-of-memory crashes are the exception. They only retry if you set retry.outOfMemory.machine, and then the next attempt runs on that bigger machine. Without it, the run ends as Crashed.

Crash retries count against maxAttempts, so leave room for them. With maxAttempts: 3 above, the agent survives two crashes, or a crash and an error, before it fails.

Deploys mid-run

A deploy doesn't move a run that's already going. Each run is locked to the version it started on, and so are its retries. A run that's three days into a wait when you deploy wakes up on the old code.

That cuts both ways. Your new code can't break an old run, and a fix won't reach a run that's failing either. After you deploy a fix, replay the failed runs, which runs them again on the latest version, one at a time or in bulk. A replay starts from the top as a new run, and the global send key in the example is what stops it emailing a lead twice.

What's the difference between task retries and checkpoint-resume?

These are the two ways a Trigger.dev run continues after an interruption, and they behave very differently.

Task retryCheckpoint-resume
Happens whenrun() throws, the process exits, the run stallsThe run waits: wait.for, wait.until, triggerAndWait, wait.forToken
Starts fromThe top of run()The line after the await
Local variablesGoneRestored
Code before the interruptionRuns againDoesn't run again
Compute while pausedNothing runs during the backoff delayWaits over 5 seconds aren't billed (Cloud)
Self-hostedYesNo checkpoints; the waiting run keeps its machine

A checkpoint is a snapshot of the whole process, memory included (checkpoint-resume). The run gives back its concurrency slot once it's been snapshotted, which for wait.for and wait.until happens soon after it starts waiting (wait for). Self-hosted Trigger.dev doesn't support checkpoints, so on your own infrastructure a three-day wait holds a machine for three days.

The two combine. If a run resumes from a checkpoint and then crashes, the retry starts from the top of run() and meets the wait again. That's why the wait in the example has an idempotency key: the second time, wait.for finds the finished wait and returns immediately instead of waiting another three days.

Waiting for a person works the same way. A waitpoint token checkpoints the run until someone approves, and our guide to human-in-the-loop AI agents covers it.

Where does agent state live across a crash?

+------------------------------------------------------------------+
|  Trigger.dev (survives the crash)                                |
|                                                                  |
|  run: status, attempt number, locked version, retry settings     |
|  idempotency keys -> the draft and send child runs + outputs     |
|  waitpoints: the 3-day timer, child run completions              |
|  checkpoint of a waiting process (Cloud only)                    |
|  trace: every attempt, log and span                              |
+------------------------------------------------------------------+
        ^  trigger, wait, complete        |  queue, restore, retry
        |                                 v
+--------------------------------+   +-----------------------------+
|  Worker machine (lost)         |   |  Providers                  |
|                                |   |                             |
|  run() local variables         |-->|  Anthropic: no dedupe;      |
|  open sockets, DB connections  |   |    a repeat costs tokens    |
|  the in-flight model call      |   |  Resend: Idempotency-Key,   |
|                                |   |    kept 24 hours            |
+--------------------------------+   +-----------------------------+

Anything that only exists on the worker is gone after a crash. Anything Trigger.dev stored (child run outputs, finished waits, keys) is there for the next attempt. Anything you sent to a provider happened, and only the provider's own idempotency key stops it happening twice.

Trigger.dev idempotency keys vs the provider's idempotency key

The example uses two kinds of key, and they protect different things.

Trigger.dev idempotency keyProvider idempotency key
StopsA task being triggered twiceAn API call taking effect twice
Set withidempotencyKey on trigger() or triggerAndWait(), idempotencyKeys.create()The provider's SDK option or Idempotency-Key header
A repeat returnsThe original run and, with triggerAndWait, its outputThe original response (an email ID, a charge)
Lifetime30 days by default, change it with idempotencyKeyTTLSet by the provider; 24 hours for Resend
After a failureCleared when the run fails, so the next trigger starts a new runDepends on the provider

Trigger.dev keys are scoped to the parent run by default, so idempotencyKeys.create("draft-1") gives the same key on every attempt of one run and a different key in another run. Use scope: "global" when it has to be unique across runs, like the send key in the example, which stops a replay sending the same follow-up twice.

Why both? A Trigger.dev key stops the parent's retry from triggering a second send run. But the send run can retry on its own. If Resend accepts the email and the connection drops before the response arrives, send-follow-up fails, retries and calls Resend again. Only Resend's key stops that second call sending a second email. As our docs put it, "Only the provider can deduplicate its own API call."

The provider key has to be stable across attempts of the send run. ctx.run.id is: retries are attempts of the same run, so the ID doesn't change, and a replay is a new run with a new ID. A replay of a run that already sent doesn't reach Resend, though: the parent's global send key returns the send run that already finished. A key built from business IDs, like follow-up/${leadId}/${step}, also dedupes across runs for 24 hours, but Resend rejects a reused key with a different payload with a 409. A send with a regenerated draft inside that window would fail with a 409 instead of sending. Use a business ID only when the payload is the same every time.

For a side effect with no idempotency support at all, record that you did it in your own database and check that record first.

Is this exactly-once execution?

No. A step can run more than once: the send run above calls Resend twice in the dropped-connection case, and a model call that fails halfway is paid for twice. What the keys guarantee is that the repeat has no extra effect. The email goes once, the subtask's output is reused, and the finished wait isn't waited again.

So design every step to be safe to repeat, and make the expensive or irreversible ones subtasks with keys.

How do you test AI agent failure recovery?

Don't wait for production to tell you the keys work. Add a test-only flag that throws a fake 429 on the first draft attempt and kills the process after the first email:

// In draftFollowUp: add `chaos?: boolean` to the payload and take `{ ctx }` as run()'s second argument
if (payload.chaos && ctx.attempt.number === 1) {
  throw new APICallError({
    message: "Injected 429",
    url: "https://api.anthropic.com/v1/messages",
    requestBodyValues: {},
    statusCode: 429,
    responseHeaders: { "retry-after": "5" },
    isRetryable: true,
  });
}

// In followUpAgent: add `chaos?: boolean`, take `{ ctx }`, pass chaos to draftFollowUp, and put this after sendFollowUp
if (payload.chaos && step === 1 && ctx.attempt.number === 1) process.exit(1);

ctx.attempt.number is the current attempt, so each failure fires once and the retry gets through.

Then trigger a run with a short wait and check what happened:

// scripts/chaos-follow-up.ts (run with TRIGGER_SECRET_KEY set)
import { runs, tasks } from "@trigger.dev/sdk";
import type { followUpAgent } from "../trigger/follow-up-agent";

const handle = await tasks.trigger<typeof followUpAgent>("follow-up-agent", {
  leadId: `lead_test_${Date.now()}`, // a new lead each run, so the global send keys are new
  email: "[email protected]",
  waitMinutes: 2, // the wait checkpoints once deployed
  chaos: true,
});

const run = await runs.poll(handle, { pollIntervalMs: 5_000 });
const sends = run.relatedRuns.children?.filter((c) => c.taskIdentifier === "send-follow-up") ?? [];

console.log({ status: run.status, attempts: run.attemptCount, sendRuns: sends.length });

// One crash means 2 attempts; 2 steps means 2 send runs. A 3rd send run means a key isn't stable.
if (run.status !== "COMPLETED" || run.attemptCount !== 2 || sends.length !== 2) process.exit(1);

[email protected] is Resend's test address, so check the Resend dashboard too: two emails, not three. Rerun the test as often as you like: each run uses a new leadId, so the sends aren't deduplicated against an earlier run. Have getLead return a test lead for those IDs.

Run it against the dev server (npx trigger.dev@latest dev) with retries.enabledInDev: true in your trigger.config.ts, then against a staging environment, where crashes take the same path as production. Stopping the dev CLI isn't a good crash test: a SIGKILL of the CLI cancels in-flight dev runs, and a Ctrl-C leaves them to stall out after the 5 minute heartbeat timeout (dev mode).

How do you check recovery in the dashboard and get alerted?

The run page shows every attempt. In the test above, follow-up-agent has a failed attempt 1 with the process exit error and a successful attempt 2. The draft run has a failed attempt with the injected 429, then the retry. Attempt 2 of the parent points at the same draft and send runs instead of creating new ones, and the wait shows as a span with its duration.

To find runs that needed recovery across a project, use Query from the dashboard or the SDK:

SELECT run_id, status, attempt_count
FROM runs
WHERE task_identifier = 'follow-up-agent' AND attempt_count > 1

Runs that recovered show as Completed with more than one attempt. Runs that didn't show as Failed, Crashed or Timed out (run statuses).

For alerts, a run fails alert goes to email, Slack or a webhook for every run that fails once its retries are exhausted. A recovered crash doesn't page anyone; a run that used up its attempts does. An error group alert, set up from the Errors page, tells you when a new kind of error appears instead. If your own code needs to react to the final failure, an onFailure hook runs once all retries are used (it doesn't fire for Crashed, System failure or Canceled runs).

Coding agents like Claude Code can run the same checks through the Trigger.dev MCP server, with list_runs, get_run_details and query.

How does chat.agent recover a conversation?

chat.agent is a different shape of agent, and it recovers differently. A chat run boots, answers a turn, and suspends or exits. The next message may start a new run with nothing in memory, so chat.agent rebuilds the conversation from durable state.

After every turn the runtime saves a snapshot of the transcript. A new run reads that snapshot, then replays the tail of the session's output and input streams to pick up anything after it (persistence and replay). If the previous run crashed mid-answer, the replay finds the partial answer and the message it was answering, and the model sees both. You can change that policy with onRecoveryBoot.

That's transcript recovery, and it's separate from task retries. chat.agent doesn't take the generic retry options. If you set oomMachine, an out-of-memory turn re-runs once on a bigger machine without re-processing finished turns. For other retry behavior, the docs suggest a raw task() with the chat primitives.

Side effects still need keys. A tool that was mid-call when the run died has no result in the transcript, so the model may call it again on the next turn. Key tools that send or charge on a business ID from the tool's input, like an order ID.

Which AI agent platforms handle failure recovery?

Platforms with durable execution do. They include Trigger.dev, Temporal, LangGraph with a persistent checkpointer, Inngest, Restate, DBOS, Cloudflare Workflows and AWS Step Functions, and this page compares the first three. LangGraph is an agent framework rather than a runtime: it decides what the graph does next, and the graph runs inside a process you provide, such as a Trigger.dev task or a Temporal workflow, or on LangChain's Agent Server. Each of the three recovers a different unit of work.

Temporal records every step of a workflow in an event history, which the Temporal Service persists "so your application state survives crashes or failures". After a crash, the workflow is replayed against that history to rebuild its state, so workflow code must be deterministic, and LLM calls, API calls and database queries go in Activities. Activities retry by default with unlimited attempts; workflows don't retry by default. There's a Vercel AI SDK integration for TypeScript that runs model calls as Activities for you, and Temporal's AI docs list integrations for the OpenAI Agents SDK, LangGraph, Google ADK and more. On Temporal Cloud, your Workers stay in your environment, so you run the processes that execute your code.

LangGraph saves a checkpoint at each super-step of the graph. If a node fails, you restart from the last successful step, and nodes that already succeeded in that step aren't re-run. You pick the checkpointer (Postgres, MongoDB or Redis for production; the in-memory one is for experimentation), or LangChain's Agent Server handles persistence for you. A node resumed after an interrupt runs again from its beginning, so side effects before the interrupt should be idempotent.

Trigger.devTemporalLangGraph
Unit of recoveryA run attempt; subtasks and waits reused by keyEach workflow step, by event history replayEach graph super-step, by checkpoint
After a crashrun() restarts from the top; finished subtasks and waits are reusedThe workflow replays to its last stateYou restart from the last successful step
Code rulesPlain async TypeScript; steps safe to repeatDeterministic workflow code; side effects in ActivitiesSide effects before an interrupt should be idempotent
Long waitsCheckpointed, not billed (Cloud)Durable timers and Signals; no Worker held while waitingInterrupts, saved by your checkpointer
LanguagesTypeScriptPython, TypeScript, Go, Java, .NET and morePython, TypeScript
Who runs your codeWe do (Cloud), or you self-hostYou run the WorkersYou, or LangChain's Agent Server

Use Temporal if you already run it, need several languages, or want every step recorded and replayed without placing keys yourself. Its replay model is the most precise of the three about what already happened. Use LangGraph if your agent is a graph and you want state saved after every step. Use Trigger.dev if your agent is TypeScript, you want plain async code without determinism rules, and you don't want to run workers. There's more in Trigger.dev vs Temporal and on our AI agents page.

Limits of Trigger.dev's recovery model

  • No step memoization. A retry re-runs run() from the top. Anything not in a keyed subtask or keyed wait runs again, including model calls.
  • Keys are yours to get right. A key built from something that changes between attempts (a timestamp, a random ID, regenerated text) dedupes nothing. The failure-injection test above is how you catch that.
  • Self-hosted runs don't checkpoint. Waits hold the machine, and a crash during a wait means a retry from the top.
  • Retries stay on the old version. A fix only reaches failed runs through replay.
  • TypeScript only. You can run Python scripts from a task with a build extension, but there's no Python SDK.

FAQs

  • Which AI agent platforms handle failure recovery? They include Trigger.dev, Temporal and LangGraph (with a persistent checkpointer or LangChain's Agent Server), which all recover agent runs after crashes. Trigger.dev retries runs and reuses finished subtasks through idempotency keys, Temporal replays a workflow's event history, and LangGraph restarts from the last saved graph step.

  • What are the agent runtime platforms with failure recovery for TypeScript? Trigger.dev runs TypeScript agents with retries, checkpoint-resume during waits and idempotency keys, and runs the compute for you. Temporal has a TypeScript SDK and an AI SDK integration, and you run the workers. LangGraph has a TypeScript library with checkpointers.

  • What makes an AI agent platform production-ready for handling failures? Retries with backoff you can override per error, durable waits that survive restarts and deploys, a way to stop retries repeating side effects, a trace of every attempt, and alerts when a run finally fails. Test it by injecting a crash and checking that nothing ran twice.

  • Which AI workflow automation tools have the best reliability? It depends on what has to recover. Temporal records every workflow step, LangGraph checkpoints every graph step, and Trigger.dev retries whole runs while reusing keyed subtasks. All three still need idempotency keys on the external calls your agent makes.

  • Do AI automation platforms with failure recovery guarantee exactly-once execution? No. Trigger.dev tasks, Temporal Activities and LangGraph nodes can all run a step more than once after a failure. Idempotency keys, on the subtask and on the provider call, make the repeat harmless.

  • Does a Trigger.dev retry re-run code before a wait? Yes. A retry restarts run() from the top. Resuming from a wait doesn't: the checkpoint restores the process and execution continues after the await. Give waits an idempotency key so a retry skips waits that already finished.

  • What happens to a running Trigger.dev agent when I deploy? It keeps running on the version it started on, and so do its retries. Replay failed runs to run them on the new version.

  • Do I need idempotency keys if the AI SDK already retries? Yes. The AI SDK's retries cover one model call. Trigger.dev idempotency keys cover what happens when the whole task retries, and the provider's key covers an email or charge that was accepted before the failure.