All guides
Updated
Reading
10 min
By
Anlyon Team

How to resume an AI agent after a crash without repeating a refund or email

Persist a business operation key before an agent acts, recover unfinished work from that record on restart, and handle multi-step tasks so a crash never turns one refund or email into two.

  • restarts
  • operation keys
  • idempotency
  • recovery
  • multi-step actions

To resume an AI agent after a crash without repeating its work, recover each unfinished business operation from your own database and look up what already happened to it, instead of letting the restarted agent decide again. That only works if the operation had a stable key before it was dispatched. With Anlyon, sending the same operationKey with the same request returns the existing operation and sends nothing, so a restart that reuses the key cannot create a second refund or a second email.

TL;DR

  • Create a business operation key when your application accepts the task, and persist it before the agent invokes anything.
  • Send it as operationKey (and a matching idempotencyKey) on every attempt. Same key and same request returns the existing operation. Same key with a changed request is refused with 409 OPERATION_KEY_REUSE.
  • On startup, load unfinished operations and read their invocation or effect. Never re-invoke an unknown one.
  • Give every step of a multi-step task its own key, and use dependsOn so step two never runs on a pending or unknown step one.
  • A correction is a new governed effect with compensates, its own approval and its own receipt.

Why does a restart repeat actions in the first place?

A worker can crash after it submitted a refund and before it saved the response. When the process comes back, the model sees an unfinished task and, reasonably, issues the refund again. If the second call carries a fresh identity, nothing downstream can tell it apart from new work.

There are four windows where this happens:

Crash pointWhat is trueWhat recovery must do
Before dispatchNothing was sentResume the persisted operation under its existing key
After dispatch, before a responseThe provider may have done the workTreat it as started. Read the effect, do not invoke afresh
After the response, before your local saveIt happened, your database does not knowRecover it through the same key, which returns the existing operation
While approval is pendingA request is parked for a reviewerObserve the existing approval instead of creating another

The second window is the expensive one. It is also the one a stable key covers, because the key connects your database row to the Anlyon operation across the gap.

What makes a good operation key?

An operation key identifies one intended business operation, not a network attempt or an agent session. Generate it when your application accepts the task, store it, and only then let the agent act.

Candidate keyProblem or property
Current timestampEvery retry looks like a new operation
Agent session idA restart changes it, so the restart looks new
Order id aloneCan block a legitimate second partial refund on the same order
Persisted refund-request idIdentifies one refund decision across every attempt
Persisted outbound-message idIdentifies one intended email across workers

Use an opaque id and keep its meaning in your own database, so the key carries no customer data. Prefix it with the operation type (refund:rr_8812, email:msg_3307) when different actions share an upstream identifier.

Two different keys are two operations. Two refunds of the same payment under two keys are two refunds. Key design decides what counts as a duplicate, and an impact limit bounds how much any number of operations can move. Neither replaces the other.

How do operationKey and idempotencyKey behave on Anlyon?

An action invoke accepts two identities, and they cover different gaps.

  • idempotencyKey is between your process and Anlyon. The SDK sends one on every invoke and generates one when you pass none. A transport resend after a timeout or a 5xx carries the same key, so it is answered from the recorded invocation and not executed again. A generated key only covers one call to invoke. When your own code can call invoke twice for one business operation, which is exactly what a restart does, pass your own.
  • operationKey names the governed effect, the business operation itself. Same key and same request return the existing effect. A different request under the same key is refused with 409 OPERATION_KEY_REUSE.

The worker key in these examples holds actions:invoke to start work and actions:read to read invocations and effects back during recovery.

import { Client } from '@anlyonhq/sdk';

const agent = new Client({ apiKey: process.env.ANLYON_AGENT_KEY! });

// rr_8812 was created and saved when the support ticket was accepted.
const key = 'refund:rr_8812';

const { data } = await agent.actions.invoke(
  'refund',
  { paymentIntent: 'pi_3Pabc', amount: 1250, currency: 'usd' },
  { operationKey: key, idempotencyKey: key },
);

// Save these before doing anything else with the result.
await db.operations.update(key, {
  invocationId: data!.id,
  effectId: data!.effectId ?? null,
  status: data!.status,
});

db here is your own persistence layer. What matters is the order: the row with the key exists before the invoke, and the returned ids are written straight after it.

If an operator changes the amount before dispatch, do not quietly reuse the key with the new input. That is refused, and it should be. Close the original operation explicitly and create a new persisted request with its own key and its own review.

How should the agent recover on startup?

Anlyon executes the actions your agent names. It does not host or restart the agent process, so the durable task state, and this loop, belong to your application. Make recovery a small state machine that runs before the agent takes new work. For each unfinished operation, read what Anlyon recorded and act on the state, not on what the model thinks happened.

import { Client } from '@anlyonhq/sdk';

const agent = new Client({ apiKey: process.env.ANLYON_AGENT_KEY! });

for (const op of await db.operations.unfinished()) {
  if (!op.invocationId) {
    // Crashed before or during dispatch. Re-send under the SAME keys:
    // if the first attempt landed, this returns it instead of sending again.
    const { data } = await agent.actions.invoke(op.action, op.input, {
      operationKey: op.key,
      idempotencyKey: op.key,
    });
    await db.operations.update(op.key, { invocationId: data!.id, effectId: data!.effectId ?? null });
    continue;
  }

  if (op.effectId) {
    const { data: effect } = await agent.actions.effect(op.effectId);
    switch (effect!.grade) {
      case 'confirmed':
      case 'acknowledged':
        await db.operations.settle(op.key, 'succeeded', effect!.grade);
        break;
      case 'failed':
      case 'refused':
      case 'denied':
        // It did not run. Report why; a new attempt is a new decision.
        await db.operations.settle(op.key, 'not_run', effect!.grade);
        break;
      case 'unknown':
        // May have happened. Hand it to reconciliation, never re-invoke.
        await db.operations.markNeedsReconciliation(op.key);
        break;
      default:
        // pending: waiting for approval or for the provider to finish. Keep observing.
        break;
    }
    continue;
  }

  // An action with no adapter or declaration has an invocation and no effect.
  const { data: inv } = await agent.actions.invocation(op.invocationId);
  if (inv!.status === 'unknown') await db.operations.markNeedsReconciliation(op.key);
  else if (inv!.status === 'succeeded' || inv!.status === 'failed') await db.operations.settle(op.key, inv!.status);
}

Three rules keep this honest:

  • Pending stays pending. A request waiting for approval, or a refund the provider accepted and has not finished, is observed. It is not resubmitted.
  • Unknown is routed, not retried. Anlyon records a lost response as unknown and does not send the request again. Reconciliation reads the provider's record. See how to reconcile an unknown agent action.
  • An application timeout is not a reason to start over. When your own wait gives up, keep the operation and its key. A closed browser tab or a killed worker should not erase the task.

When is a deliberate retry allowed?

Sometimes the operation really did fail and the business still wants it done. That is a new decision, and Anlyon makes it visible. A deliberate re-run names the invocation it retries with retryOf and carries a new idempotency key. It is allowed only when the original is failed, either on its own or resolved as failed. An unknown original is refused until it is resolved.

await agent.actions.invoke('refund-order', input, {
  retryOf: 'inv_01JABCDEF',
  idempotencyKey: 'refund:rr_8812:retry-1',
});

Record the retry against the same business operation in your database. Anlyon links the two invocations as retryOf and retriedBy.

How do you resume a multi-step task?

A refund followed by a confirmation email crosses two external operations. No platform turns them into one atomic transaction. If the refund succeeds and the email does not, the task is partially complete, and replaying the whole task from the beginning can issue a second refund.

Give each step its own persisted key, derived from the task and the step name, and record each step's outcome separately.

RefundEmailWhat resume should do
SucceededNot startedSend the email under its own key
SucceededUnknownReconcile the email. Do not refund again or resend blindly
UnknownNot startedResolve the refund before claiming anything to the customer
RefusedNot startedReport the boundary that stopped it, and stop

Anlyon can hold the order for you. dependsOn admits a governed effect only when the effects it names already hold the stated outcome. Pending and unknown never satisfy it, and an unmet dependency is refused with 409 DEPENDENCY_UNRESOLVED before anything is sent. It is checked again before dispatch.

import { Client } from '@anlyonhq/sdk';

const agent = new Client({ apiKey: process.env.ANLYON_AGENT_KEY! });

const task = 'task_5521';

// Step one. On a restart this same call returns the existing refund.
const refund = await agent.actions.invoke(
  'refund',
  { paymentIntent: 'pi_3Pabc', amount: 1250, currency: 'usd' },
  { operationKey: `${task}:refund`, idempotencyKey: `${task}:refund` },
);
const refundEffect = refund.data!.effectId!;
await db.tasks.saveStep(task, 'refund', refundEffect);

// Step two runs once your recovery loop has seen the refund settle.
const { data: settled } = await agent.actions.effect(refundEffect);
// Pending, unknown or not run: leave the email for the next pass.
if (settled!.outcome === 'succeeded') {
  await agent.actions.invoke(
    'send-receipt',
    {
      from: 'billing@mail.example.com',
      to: ['customer@example.com'],
      subject: 'Your refund',
      text: 'We refunded $12.50 to your card.',
    },
    {
      operationKey: `${task}:email`,
      idempotencyKey: `${task}:email`,
      dependsOn: [{ effect: refundEffect, outcome: 'succeeded' }],
    },
  );
}

Derive step keys from the persisted task, never from the current session or a retry counter. That way a restart in the middle of the task lands on the same two operations.

What if a step needs undoing?

Some effects cannot be undone. A sent email cannot be recalled, and a refund cannot be reversed through the Stripe API. Where a correction does exist, such as a new reviewed GitHub file update that restores the old content, model it as its own operation. Invoke the correcting action with compensates: 'eff_...' and it becomes a separate governed effect with its own preview, approval, impact and receipt. Do not hide a correction inside a retry of the original.

How do you test that recovery works?

Use a safe fixture and kill the worker at each boundary: before dispatch, after dispatch but before the response is saved, while the approval is pending, and between the two steps of a multi-step task. Restart it and count the provider-side effects, not the HTTP 200s. On stripe.refund in test mode, the fault drill (faultDrill: 'drop_response_after_send') discards a real Stripe response on purpose, which is the closest you can get to a lost response on demand. The lost-response example shows the same reasoning locally with no provider at all.

Also test the opposite failure: a key that is too broad. Create a legitimate second partial refund for the same order and confirm your key design lets it through as its own operation.

Frequently asked questions

How do I stop an AI agent from repeating an action after it restarts?
Give each business operation a stable key, persist it in your own database before the agent invokes the action, and send it as the operationKey on every attempt. On restart, load unfinished operations and read their existing invocation or effect instead of invoking again. With Anlyon, the same operationKey and the same request return the existing operation and nothing is sent again.
What should the operation key be based on?
A persisted identifier for one business decision, such as a refund-request id or an outbound-message id created when your application accepts the task. Not a timestamp, which makes every attempt new, and not an agent session id, which changes on restart. An order id alone can be too broad if one order can legitimately receive two partial refunds.
Can I just retry an action whose outcome is unknown?
No. Unknown means the provider may already have done the work. Anlyon does not send the request again, and a deliberate retry with retryOf is refused while the original is unknown. Reconcile it from the provider's record, or have an operator resolve it, and only then decide whether a new attempt is needed.
Does Anlyon restart my agent process?
No. Anlyon executes the actions your agent names and records what happened to each one. Your application hosts the agent and owns its durable task state, including which business operations are unfinished and which keys they use.

Let your agent act for your users, safely.

A few lines of server code, then send a user a connect link. Nothing to host.

$ claude mcp add --transport http anlyon https://api.anlyon.com/mcp