> ## Documentation Index
> Fetch the complete documentation index at: https://docs.canary.effectiveai.app/llms.txt
> Use this file to discover all available pages before exploring further.

# Writes to your systems

> How procedure code steps retry, what an idempotency key guarantees, and how to keep a refund, a cancellation or a notice from happening twice.

A procedure changes your systems through code steps: a [`call`](https://docs.canary.effectiveai.app/procedures/reference/nodes/call)
node runs a [function or effect](https://docs.canary.effectiveai.app/procedures/reference/nodes/function-and-effect.md) you declare in the
document. This page explains when that code can run more than once, and what you do so that a
repeated write doesn't apply twice. Effective doesn't guarantee that a write happens exactly once.
You send each write with an **idempotency key**, a value that lets the receiving system recognize
a repeat of the same request, and a system that honours the key applies it once.

## Finished steps don't run again

A run records each step's result when it finishes. If the run is interrupted and resumes, it uses
the recorded result and does not call your code again. A refund that finished and was recorded is
never sent a second time by a resume.

## Unfinished steps can run again

Code steps retry when they fail. By default a function or effect gets **three attempts** in all,
waiting one second before the first retry and doubling the wait each time, up to ten seconds. You
can set a different policy with a [`retry`](https://docs.canary.effectiveai.app/procedures/reference/nodes/retry) block.

* An error thrown by an effect is retried.
* Throw `FatalError` from the effect's context when another attempt can't help, such as a `4xx`
  answer or failed validation. The step fails at once without using its remaining attempts.
* An error thrown by a pure function is never retried, because running it again gives the same
  answer. Functions retry only when the attempt timed out or was lost.
* A timeout counts as an attempt and is retried.
* If the run loses contact with an attempt after it started, that attempt counts, and the effect
  runs again only if its policy allows more attempts.

So an effect that writes may run more than once, and a write may reach your system even when the
answer never comes back. Retries bound how many times the code runs; they don't make it run
once.

## Send the idempotency key

Every attempt of the same step gets the same `operation.idempotencyKey` in the effect's context.
Pass it to the system you write to, in the header or field that system uses for idempotency.
A system that honours the key applies the first request and answers later ones with the same
result, so a retried refund is paid once.

```ts effect id=issue-refund input=refund-request result=refund-receipt uses=fetch,secrets secrets=payments-token theme={"languages":{"custom":["languages/rsl.tmLanguage.json"]}}
async ({ policyNumber, amount }, { fetch, secrets, operation, signal, FatalError }) => {
  const token = await secrets.getText('payments-token');
  const response = await fetch('https://payments.example.com/v1/refunds', {
    method: 'POST',
    signal,
    headers: {
      authorization: `Bearer ${token}`,
      'content-type': 'application/json',
      'idempotency-key': operation.idempotencyKey,
    },
    body: JSON.stringify({ policyNumber, amount }),
  });
  if (response.status >= 400 && response.status < 500 && response.status !== 429) {
    throw new FatalError(`Refund refused: ${response.status}`);
  }
  if (!response.ok) throw new Error(`Refund failed: ${response.status}`);
  const body: unknown = await response.json();
  if (typeof body !== 'object' || body === null || !('id' in body) || typeof body.id !== 'string') {
    throw new FatalError('Unexpected refund response');
  }
  return { refundId: body.id };
};
```

> [!NOTE]
>
> The example's endpoint, header name and secret name are illustrative. Use your payment system's
> own idempotency convention. The effect also needs `refund-request` and `refund-receipt`
> [schemas](https://docs.canary.effectiveai.app/procedures/reference/nodes/schema.md) and a `payments-token`
> [secret](https://docs.canary.effectiveai.app/procedures/reference/nodes/secret.md) declaration in the same document. It keeps the
> default three attempts, which is safe only because the payment system honours the key. A `429`
> answer is left to retry, because a later attempt can succeed. A response body arrives untyped, so
> the effect checks its shape before returning it.

How the key is sent depends on the capability the effect uses:

| Capability | What you do |
| - | - |
| `fetch` | Reads need no key. For writes, pass `operation.idempotencyKey` yourself; Effective doesn't add a header, because systems name it differently. |
| `effective:<scope>` | For Effective API writes, Effective sends a stable `Idempotency-Key` for you. Some Effective API writes don't deduplicate the key; their API reference says so. An effect granted one of them must select a [retry policy](https://docs.canary.effectiveai.app/procedures/reference/nodes/retry.md), or compiling reports `PROC-EFFECT-007`. A YAML `call` of such an operation runs once. |
| `secrets` | Reading a secret needs no key. A write that uses the secret follows that write's own rules. |

## When your system has no idempotency key

A key only helps if the receiving system uses it. If it doesn't, and a duplicate is not
acceptable, give that step a policy with `maximum_attempts: 1`. The write is then tried at most
once. If the outcome is unknown, for example because the answer was lost, the step fails and a
person investigates, instead of a retry that could pay twice.

```yaml retry id=at-most-once theme={"languages":{"custom":["languages/rsl.tmLanguage.json"]}}
maximum_attempts: 1
initial_interval: 1s
backoff_coefficient: 2
maximum_interval: 10s
```

Select it on the effect with `retry=at-most-once`. For a refund endpoint with no idempotency key,
the same effect opens with:

````markdown theme={"languages":{"custom":["languages/rsl.tmLanguage.json"]}}
```ts effect id=issue-refund input=refund-request result=refund-receipt uses=fetch,secrets secrets=payments-token retry=at-most-once

```
````

A policy always names all four fields; with one attempt, the other three are never used.

Another safe pattern is to look first: before a write, read your system for a record of it by a
business key such as the policy number and cancellation date, and only write if none exists.

## Keep each write in its own step

Put each write that has to recover on its own, such as the cancellation and the refund, in its
own effect and its own `call` node. If the refund fails after the cancellation was recorded, the
retry repeats only the refund. The cancellation's result is already recorded and isn't sent again.

## When a step fails

When a step fails for good, because it threw `FatalError` or used up its attempts, the run ends
with status `failed` and a `failure` whose message names the step and the step's code, such as
`local-code-failed`. It doesn't include the message your code threw: a thrown message could hold
a secret value, so Effective doesn't show it. Return a refusal you need to see as a typed result
instead, and log the detail in your own system. A failed run's status is final, and the API has no
way to resume it. The results it recorded before the failure stay on the run; open its `webUrl` to
see each step. Writes that already reached your systems stay written, because failing the run
doesn't undo them.

A procedure has no catch or compensation node. To recover, find the cause from the failed step and
your own system's logs, fix it, and start a new run. In the Effective app, **Retry** on the run's
page starts a new run from a checkpoint instead; the steps from that point run again. See
[Safety for regulated operations](https://docs.canary.effectiveai.app/procedures/concepts/operational-safety.md#when-something-goes-wrong).
Design the procedure so that a new run is safe to repeat: build each write's key from the business
request, not from the run. Then a system that honours the key answers a write the failed run
already made with its first result, instead of applying it again.
[Cancel a policy](https://docs.canary.effectiveai.app/procedures/tutorials/cancel-a-policy.md#if-a-run-fails-partway) shows this.

## Writes to Effective

When an effect calls the Effective API and the API refuses with a `4xx`, nothing was applied.
Inside the effect, `effective.apiError(error)` returns the refusal's `status`, `code` and `body` so
you can turn the refusals you expect into a result the procedure can branch on with a
[`choice`](https://docs.canary.effectiveai.app/procedures/reference/nodes/choice) or [`repeat`](https://docs.canary.effectiveai.app/procedures/reference/nodes/repeat).
It returns `null` for a `5xx` or a lost answer, because those may have been applied; rethrow them
so the retry policy applies.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.