> ## 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.

# retry policy

> Declare how many times a function or effect may run, and how long to wait between attempts.

A `retry` block declares a reusable retry policy. It is not a step: it never runs on its own. A
[`ts function` or `ts effect`](https://docs.canary.effectiveai.app/procedures/reference/nodes/function-and-effect) selects it with
`retry=<policy-id>`, and every [`call`](https://docs.canary.effectiveai.app/procedures/reference/nodes/call) of that declaration uses
it. Without one, functions and effects use the default policy below.

## Syntax

```yaml retry id=pas-write-retry theme={"languages":{"custom":["languages/rsl.tmLanguage.json"]}}
maximum_attempts: 5
initial_interval: 2s
backoff_coefficient: 2
maximum_interval: 30s
```

A declaration selects it by ID on its info line:

```text theme={"languages":{"custom":["languages/rsl.tmLanguage.json"]}}
ts effect id=cancel-policy input=cancel-request result=cancellation uses=fetch retry=pas-write-retry
```

Like schemas and secrets, a policy can be declared anywhere in the document, before or after the
declarations that use it.

## Fields

All four fields are required. Unknown fields are invalid.

| Field | Type | Required | Default | What it does |
| - | - | - | - | - |
| `maximum_attempts` | integer | Yes | None | Total attempts, counting the first. A positive whole number. `1` means the code runs at most once. |
| `initial_interval` | duration | Yes | None | Wait before the first retry. |
| `backoff_coefficient` | number | Yes | None | Multiplies the wait for each later retry. At least `1`. |
| `maximum_interval` | duration | Yes | None | Longest wait between attempts. Not smaller than `initial_interval`. |

A duration is a positive whole number and one unit, with no spaces: `ms`, `s`, `m`, `h` or `d`,
for example `500ms`, `2s` or `1m`.

### Default policy

A function or effect without `retry=` uses:

```yaml theme={"languages":{"custom":["languages/rsl.tmLanguage.json"]}}
maximum_attempts: 3
initial_interval: 1s
backoff_coefficient: 2
maximum_interval: 10s
```

A selected policy replaces all four values.

## Which failures retry

An attempt uses up one of `maximum_attempts` and is retried, after the backoff wait, when:

* **An effect throws.** An uncaught error in an effect is retried, so a brief outage at the other
  end doesn't fail the run. Throw `new FatalError(...)` from the effect's context when another
  attempt can't help, such as a `4xx` answer or failed validation. The step then fails at once.
* **The attempt times out.** Timeouts are retried under the same count.
* **The run loses contact with an attempt after it started.** The code may have run, so the
  attempt counts. A pure function is simply recomputed. An effect runs again only if
  `maximum_attempts` is more than `1`.

These never retry:

* a `FatalError`;
* an error thrown by a pure function, because running it again gives the same answer;
* hitting a fixed compute or memory limit (`resource-exhausted`);
* a result that doesn't match the result schema;
* cancellation; and
* the code failing to load.

When the attempts run out, the step fails with `local-code-failed`, or `operation-timeout` for a
timeout, and the message notes that the policy is exhausted.

Some failures happen before any code starts, and the platform knows it. Those are retried
separately, on their own limit, and don't use up `maximum_attempts`.

## Example

The policy administration system deduplicates on `Idempotency-Key`, so the cancellation can retry
safely. The mail vendor has no idempotency protocol, so the printed notice is ordered at most
once:

````markdown cancel-policy.procedure.md theme={"languages":{"custom":["languages/rsl.tmLanguage.json"]}}
---
kind: procedure@v0
id: cancel-policy

inputs:
  policy_number: { type: string }
  effective_date: { type: string }
outputs:
  result: { schema: cancel-result }
---

# Cancel policy

Cancel a policy in the policy administration system, then order the printed
notice from the mail vendor.

## Cancel

The policy administration system deduplicates on `Idempotency-Key`, so this
write can retry safely.

```yaml call id=cancel-in-pas
function: '@local.cancel-policy'
input:
  policyNumber: $inputs.policy_number
  effectiveDate: $inputs.effective_date
output: cancellation
```

## Order notice

The mail vendor has no idempotency protocol, so the order runs at most once.

```yaml call id=order-notice
function: '@local.order-printed-notice'
input:
  policyNumber: $inputs.policy_number
  effectiveDate: $inputs.effective_date
output: mail_order
```

```yaml complete id=done
output: result
value:
  cancellationId: $cancellation.cancellationId
  mailOrderId: $mail_order.orderId
```

## Resources

```yaml retry id=pas-write-retry
maximum_attempts: 5
initial_interval: 2s
backoff_coefficient: 2
maximum_interval: 30s
```

```yaml retry id=once
maximum_attempts: 1
initial_interval: 1s
backoff_coefficient: 1
maximum_interval: 1s
```

```yaml schema id=cancel-request
type: object
additionalProperties: false
required: [policyNumber, effectiveDate]
properties:
  policyNumber: { type: string }
  effectiveDate: { type: string }
```

```yaml schema id=cancellation
type: object
additionalProperties: false
required: [cancellationId]
properties:
  cancellationId: { type: string }
```

```yaml schema id=mail-order
type: object
additionalProperties: false
required: [orderId]
properties:
  orderId: { type: string }
```

```yaml schema id=cancel-result
type: object
additionalProperties: false
required: [cancellationId, mailOrderId]
properties:
  cancellationId: { type: string }
  mailOrderId: { type: string }
```

```yaml secret id=pas-token
format: text
description: Token for the policy administration system API
```

```yaml secret id=mail-vendor-key
format: text
description: API key for the print and mail vendor
```

```ts effect id=cancel-policy input=cancel-request result=cancellation uses=fetch,secrets secrets=pas-token retry=pas-write-retry
async ({ policyNumber, effectiveDate }, { fetch, secrets, operation, signal, FatalError }) => {
  const token = await secrets.getText('pas-token');
  const response = await fetch(
    `https://pas.northwind.example/v1/policies/${policyNumber}/cancellations`,
    {
      method: 'POST',
      headers: {
        Authorization: `Bearer ${token}`,
        'Content-Type': 'application/json',
        'Idempotency-Key': operation.idempotencyKey,
      },
      body: JSON.stringify({ effectiveDate, reason: 'nonpayment' }),
      signal,
    }
  );
  if (response.status >= 400 && response.status < 500 && response.status !== 429) {
    throw new FatalError(`Cancellation refused (${response.status})`);
  }
  if (!response.ok) throw new Error(`Cancellation failed (${response.status})`);
  const body = await response.json();
  if (typeof body !== 'object' || body === null || !('id' in body) || typeof body.id !== 'string') {
    throw new Error('Cancellation response has no id');
  }
  return { cancellationId: body.id };
};
```

```ts effect id=order-printed-notice input=cancel-request result=mail-order uses=fetch,secrets secrets=mail-vendor-key retry=once
async ({ policyNumber, effectiveDate }, { fetch, secrets, signal }) => {
  const key = await secrets.getText('mail-vendor-key');
  const response = await fetch('https://print.mailvendor.example/v2/orders', {
    method: 'POST',
    headers: { 'X-Api-Key': key, 'Content-Type': 'application/json' },
    body: JSON.stringify({ template: 'cancellation-notice', policyNumber, effectiveDate }),
    signal,
  });
  if (!response.ok) throw new Error(`Mail order failed (${response.status})`);
  const body = await response.json();
  if (
    typeof body !== 'object' ||
    body === null ||
    !('orderId' in body) ||
    typeof body.orderId !== 'string'
  ) {
    throw new Error('Mail order response has no orderId');
  }
  return { orderId: body.orderId };
};
```
````

> [!NOTE]
>
> Both hosts, their paths, header names and both secrets are illustrative. Use each system's own API
> and idempotency convention.

With `maximum_attempts: 1`, the intervals and coefficient still have to be present and valid, but
they never take effect.

## Retries are not exactly once

A policy with more than one attempt limits how often the code may run. It doesn't make a write
happen once, and it doesn't make the other system idempotent. A write can reach your system and
its answer still be lost; a retry then sends it again.

* **For writes, send `operation.idempotencyKey`.** It is the same for every attempt of the same
  call. Pass it in the header or field your system uses for idempotency. Plain `fetch` doesn't add
  it for you. Effective API writes made through `effective.api.*` carry it as `Idempotency-Key`
  automatically.
* **No idempotency protocol?** Use a natural unique business key, or a policy with
  `maximum_attempts: 1`. Leaving out `retry=` keeps the three-attempt default and can duplicate the
  write. With one attempt, an unknown outcome fails the step for a person to check, instead of
  retrying.
* **Some Effective API writes don't deduplicate the key.** Their generated reference says so. An
  effect that is allowed one of them must select a `retry=` policy: `maximum_attempts: 1`, or more
  attempts when the effect checks the receiving system before it writes again.

Resuming is separate from retrying: when a run resumes, a call that already finished is not run
again. Its recorded result is used. See
[writes to your systems](https://docs.canary.effectiveai.app/procedures/concepts/writes-to-your-systems.md).

## Common errors

| Code | Cause | Fix |
| - | - | - |
| `PROC-FENCE-006` | The policy body is missing a field or has an unknown one, a duration is invalid, `initial_interval` is larger than `maximum_interval` (`yaml retry: initial_interval must not exceed maximum_interval.`), or the `retry=` attribute is malformed. | Give all four fields valid values. |
| `PROC-RETRY-002` | A declaration's `retry=` names a policy that doesn't exist. | Fix the ID, or declare the policy. |
| `PROC-EFFECT-006` | Warning: the effect reads the deprecated `operation.id`. | Use `operation.idempotencyKey`. |
| `PROC-EFFECT-007` | The effect may call an Effective API write that doesn't deduplicate retries, and selects no `retry=` policy. | Select a policy, usually with `maximum_attempts: 1`. |

## See also

* [Function and effect declarations](https://docs.canary.effectiveai.app/procedures/reference/nodes/function-and-effect.md)
* [`call` node](https://docs.canary.effectiveai.app/procedures/reference/nodes/call)
* [Writes to your systems](https://docs.canary.effectiveai.app/procedures/concepts/writes-to-your-systems.md)


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